Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): add a thread layout beside the terminal grid
rubenluetke10-beep0199db04a79c
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.pyindex 42d9de4254..1f8024a2f1 100644--- a/jarvis/agent_chat/store.py+++ b/jarvis/agent_chat/store.py@@ -274,6 +274,26 @@ class AgentChatStore:).fetchall()return [self._row_to_session(r) for r in rows]+ def title_is_automatic(self, session: AgentChatSession) -> bool:+ """Whether ``session``'s title is still the one its first message gave it.++ A title the person typed differs from that; a session with no message+ yet has nothing to compare and counts as automatic.+ """+ with self._lock:+ row = self._conn.execute(+ "SELECT payload FROM agent_chat_events WHERE session_id = ? "+ "AND kind IN ('user_message', 'agent_message') ORDER BY seq ASC LIMIT 1",+ (session.session_id,),+ ).fetchone()+ if row is None:+ return True+ try:+ text = str((json.loads(row["payload"]) or {}).get("text") or "")+ except (TypeError, ValueError, AttributeError):+ return True+ return session.title == _title_from(text)+def list_sessions_matching(self, prefix: str, suffix: str = "", *, limit: int = 200) -> list[AgentChatSession]:diff --git a/jarvis/agentic_ide/cli_title.py b/jarvis/agentic_ide/cli_title.pyindex 95a979a6cf..7d8e2f4ca0 100644--- a/jarvis/agentic_ide/cli_title.py+++ b/jarvis/agentic_ide/cli_title.py@@ -145,7 +145,32 @@ def _recorded(term: Any) -> str:return ""# Lifetime id, like the recap cache: two workspaces can each hold a "t5".pane = str(getattr(term, "history_id", "") or getattr(term, "key", "") or "")- key = (pane, session_id)+ return _cached_title((pane, session_id), agent, session_id, _home(term))+++def session_title(agent: str, session_id: str, account_id: str = "") -> str:+ """The title a CLI gave the conversation ``session_id``, or "" when it has none.++ For a chat thread rather than a pane: the thread knows its CLI, the+ vendor's session id and the subscription seat it runs on, but has no+ terminal and therefore no window title. Same records, same cache.+ """+ try:+ agent = (agent or "").strip().lower()+ session_id = (session_id or "").strip()+ if agent not in ("claude", "codex") or not session_id:+ return ""+ if "/" in session_id or "\\" in session_id:+ return ""+ home = _account_home(agent, account_id)+ return _clip(_cached_title(("thread", session_id), agent, session_id, home))+ except Exception as exc: # noqa: BLE001 - a title must never break a session list+ logger.debug("Agentic IDE: CLI title of thread {} unreadable: {}", session_id, exc)+ return ""+++def _cached_title(key: tuple[str, str], agent: str, session_id: str, home: Path | None) -> str:+ """The title cached under ``key``, refreshed from the CLI's record on a slow clock."""entry = _records.get(key)if entry is None:if len(_records) >= MAX_ENTRIES:@@ -155,7 +180,6 @@ def _recorded(term: Any) -> str:if entry.inflight or (entry.checked_at and now - entry.checked_at < RECHECK_S):return entry.titleentry.inflight = True- home = _home(term)def _read() -> None:try:@@ -268,6 +292,24 @@ def _home(term: Any) -> Path | None:return None+def _account_home(agent: str, account_id: str) -> Path | None:+ """The config dir a chat thread's CLI writes its record to.++ A thread with no seat of its own runs on the platform's active account,+ so that account's folder is where its record lands.+ """+ try:+ from jarvis import agent_accounts++ if agent not in agent_accounts.platforms():+ return None+ seat = account_id or agent_accounts.active_account(agent).id # type: ignore[arg-type]+ return agent_accounts.config_dir_for(agent, seat) # type: ignore[arg-type]+ except Exception as exc: # noqa: BLE001 - the default home is the honest fallback+ logger.debug("Agentic IDE: account folder for thread on {} is unknown: {}", agent, exc)+ return None++def forget(key: str) -> None:"""Drop what is remembered about one pane (its lifetime id) — it has been closed."""for cached in [item for item in _records if item[0] == key]:diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 80cd3f2128..a83b685270 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -777,11 +777,37 @@ def list_sessions(continued = s.to_dict()d["running"] = svc.is_running(s.session_id)+ if s.surface == "agent":+ d["pending_approvals"] = svc.pending_approvals(s.session_id)+ d["cli_title"] = _cli_title(svc, s)out.append(d)_title_jarvis_chats(request, svc, out)return {"sessions": out}+def _cli_title(svc: Any, session: Any) -> str:+ """The name the coding CLI gave a thread's conversation itself, or "".++ Claude Code and Codex title their own sessions on their own subscription;+ a thread shows that name the way a terminal pane does. A title the person+ typed wins, so the CLI's is only offered while the stored one is still+ the first message's.+ """+ if not session.vendor_session:+ return ""+ from jarvis.agent_chat.catalog import provider_row+ from jarvis.agentic_ide import cli_title++ row = provider_row(session.provider)+ agent = row.agent if row is not None else ""+ if agent not in ("claude", "codex"):+ return ""+ title = cli_title.session_title(agent, session.vendor_session, session.account_id)+ if not title or not svc.store.title_is_automatic(session):+ return ""+ return title++def _title_jarvis_chats(request: Request, svc: Any, rows: list[dict[str, Any]]) -> None:"""Give the Jarvis chats a topic title instead of their first words.diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.pyindex ed20b78d1c..34972ba681 100644--- a/jarvis/ui/web/agentic_ide_git_routes.py+++ b/jarvis/ui/web/agentic_ide_git_routes.py@@ -3,6 +3,8 @@Endpoints (all under ``/api/agentic-ide/git``)::GET /inspect Branch, changes, ahead/behind, branches, worktrees+ GET /changes Changed files under a folder, with line counts+ GET /diff One file's change against the last commitGET /overview A workspace's branches with merged-into, PR and CI stateGET /github/repos The person's GitHub repositories, for the one-time pickPUT /github/binding Remember which GitHub repository a workspace folder is@@ -25,10 +27,12 @@ UI can offer the follow-up it has for that code (``dirty`` → "remove anyway?")from __future__ import annotations+from dataclasses import asdict+from fastapi import APIRouter, HTTPException, Queryfrom pydantic import BaseModel, Field-from jarvis.agentic_ide import git_ops, git_overview, github_link, github_status+from jarvis.agentic_ide import git_changes, git_ops, git_overview, github_link, github_statusfrom jarvis.agentic_ide.git_ops import GitError, PrepareModefrom jarvis.agentic_ide.session import account_home, get_registryfrom jarvis.agentic_ide.session_branches import PaneBranchRecord@@ -77,6 +81,23 @@ def inspect_folder(folder: str = Query(..., min_length=1)) -> dict:raise _fail(exc) from exc[email protected]("/changes", summary="Changed files under a folder, with line counts")+def folder_changes(folder: str = Query(..., min_length=1)) -> dict:+ """What a thread's diff panel lists — the same reading as a workspace's+ Changes tab, for a folder no workspace has open (a thread's worktree)."""+ return asdict(git_changes.workspace_changes(folder))++[email protected]("/diff", summary="How one file under a folder differs from the last commit")+def folder_file_diff(+ folder: str = Query(..., min_length=1), path: str = Query(..., min_length=1)+) -> dict:+ try:+ return asdict(git_changes.file_diff(folder, path))+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None++@router.get("/overview", summary="Branches of a workspace's repository with PR and CI state")def workspace_overview(workspace_id: str = Query(..., min_length=1),diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsxindex 127c3a99bd..831c55b591 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx@@ -7,6 +7,7 @@ import { useComputerChoices } from "@/hooks/useComputers";import { addTerminal, fetchWorkspacePanes, interruptTerminal, placeWorkspace, removeWorkspace, renameWorkspace, startIdeSession, IdeApiError, reorderWorkspaces, type IdeProject, type ProjectWorkspace, type WorkspacePaneRow } from "@/lib/agenticIdeApi";import { useEventStore } from "@/store/events";import { useIdeProjectsStore } from "@/store/ideProjects";+import { IdeLayoutSwitch } from "./threads/IdeLayoutSwitch";const EXPANSION_KEY = "jarvis.ide.projectExpansion.v1";const WORKSPACE_DRAG_MIME = "application/x-jarvis-workspace-id";@@ -779,6 +780,7 @@ export function IdeProjectTree() {<div className="flex h-8 items-center justify-between pl-2 pr-1 text-[15px] font-semibold text-foreground"><span>Workspaces</span><div className="flex items-center gap-0.5">+ <IdeLayoutSwitch /><button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={toggleVoice}className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Mic className="h-3.5 w-3.5" /></button><button type="button" aria-label="Connect project" title="Connect project folder" onClick={connectProject}diff --git a/jarvis/ui/web/frontend/src/components/agentic/LazyIdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/LazyIdeProjectTree.tsxindex 2ccdd595a8..fa33c53118 100644--- a/jarvis/ui/web/frontend/src/components/agentic/LazyIdeProjectTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/LazyIdeProjectTree.tsx@@ -2,16 +2,20 @@ import { lazy, Suspense } from "react";import { ViewErrorBoundary } from "@/components/ViewErrorBoundary";import { useT } from "@/i18n";import { useEventStore } from "@/store/events";+import { useIdeThreadsStore } from "@/store/ideThreads";const IdeProjectTree = lazy(() => import("./IdeProjectTree").then((module) => ({ default: module.IdeProjectTree })));+const ThreadTree = lazy(() => import("./threads/ThreadTree").then((module) => ({ default: module.ThreadTree })));/** The normal chat sidebar needs no project/file operations or workspace UI. */export function LazyIdeProjectTree() {const t = useT();const setActive = useEventStore((state) => state.setActiveSection);+ // The thread layout lists threads instead of workspaces.+ const layout = useIdeThreadsStore((state) => state.layout);return <ViewErrorBoundary viewName={t("nav.agentic_ide")} resetKey="ide-project-tree" onRecover={() => setActive("chats")}><Suspense fallback={<p role="status" aria-busy="true" className="px-3 py-4 text-sm text-muted-foreground">{t("common.loading")}</p>}>- <IdeProjectTree />+ {layout === "threads" ? <ThreadTree /> : <IdeProjectTree />}</Suspense></ViewErrorBoundary>;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/IdeLayoutSwitch.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/IdeLayoutSwitch.tsxnew file mode 100644index 0000000000..c4527e7f57--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/IdeLayoutSwitch.tsx@@ -0,0 +1,29 @@+import { LayoutGrid, MessagesSquare } from "lucide-react";+import { cn } from "@/lib/utils";+import { useIdeThreadsStore, type IdeLayout } from "@/store/ideThreads";++const CHOICES: { layout: IdeLayout; label: string; Icon: typeof LayoutGrid }[] = [+ { layout: "grid", label: "Terminal grid", Icon: LayoutGrid },+ { layout: "threads", label: "Threads", Icon: MessagesSquare },+];++/**+ * Grid or threads — the two ways the Agentic IDE is laid out. Two buttons,+ * not one that cycles, so each says where it leads; the one that is on wears+ * the lift surface.+ */+export function IdeLayoutSwitch() {+ const layout = useIdeThreadsStore((state) => state.layout);+ const setLayout = useIdeThreadsStore((state) => state.setLayout);+ return <div role="group" aria-label="IDE layout" className="flex items-center gap-0.5 rounded-md bg-secondary/60 p-0.5">+ {CHOICES.map(({ layout: choice, label, Icon }) => <button key={choice} type="button"+ data-testid={`ide-layout-${choice}`} aria-pressed={layout === choice} aria-label={label} title={label}+ onClick={() => setLayout(choice)}+ className={cn(+ "flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ layout === choice && "bg-background text-foreground shadow-rim",+ )}>+ <Icon aria-hidden className="h-3.5 w-3.5" />+ </button>)}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadBranchBar.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadBranchBar.tsxnew file mode 100644index 0000000000..77f53fb7db--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadBranchBar.tsx@@ -0,0 +1,134 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { Check, ChevronDown, FolderGit2, GitBranch, Laptop, Loader2 } from "lucide-react";+import { inspectGit, prepareGit, type GitRepoInfo } from "@/lib/gitApi";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { ThreadMenuHeading, ThreadMenuItem, ThreadPopover } from "./ThreadPopover";+import { folderLabel } from "./threadModel";++/** Where a new thread's agent works: the project's own checkout, or a worktree of its own. */+export type ThreadCheckout = "current" | "worktree";++const BUTTON = "flex h-7 min-w-0 items-center gap-1.5 rounded-md px-2 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50";++/** The repository state behind a folder, refreshed when the folder changes and on demand. */+export function useGitInfo(folder: string): { info: GitRepoInfo | null; loading: boolean; refresh: () => void } {+ const [info, setInfo] = useState<GitRepoInfo | null>(null);+ const [loading, setLoading] = useState(false);+ const [nonce, setNonce] = useState(0);+ useEffect(() => {+ if (!folder) { setInfo(null); return; }+ const controller = new AbortController();+ setLoading(true);+ inspectGit(folder, controller.signal)+ .then((next) => { if (!controller.signal.aborted) setInfo(next); })+ .catch(() => { if (!controller.signal.aborted) setInfo(null); })+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });+ return () => controller.abort();+ }, [folder, nonce]);+ const refresh = useCallback(() => setNonce((value) => value + 1), []);+ return { info, loading, refresh };+}++/**+ * The strip under the composer. A new thread chooses where its agent works —+ * the current checkout or a fresh worktree — and which branch: the branch to+ * switch the checkout to, or the base a worktree starts from. A running+ * thread shows where it works and leaves the branch alone.+ */+export function ThreadBranchBar({+ folder,+ draft,+ checkout,+ onCheckout,+ base,+ onBase,+ locked,+}: {+ /** The thread's folder — the project's for a new thread. */+ folder: string;+ draft: boolean;+ checkout: ThreadCheckout;+ onCheckout: (next: ThreadCheckout) => void;+ /** The branch a new worktree starts from; "" = the current branch. */+ base: string;+ onBase: (branch: string) => void;+ /** The agent is working: switching its branch now would pull files from under it. */+ locked: boolean;+}) {+ const pushToast = useEventStore((state) => state.pushToast);+ const { info, loading, refresh } = useGitInfo(folder);+ const [menu, setMenu] = useState<"checkout" | "branch" | null>(null);+ const [switching, setSwitching] = useState(false);+ const checkoutAnchor = useRef<HTMLButtonElement | null>(null);+ const branchAnchor = useRef<HTMLButtonElement | null>(null);++ const repo = Boolean(info?.is_repo);+ const worktreeDraft = draft && checkout === "worktree";+ const shownBranch = worktreeDraft ? base || info?.branch || "" : info?.branch || "";++ const pickBranch = async (name: string) => {+ setMenu(null);+ if (worktreeDraft) { onBase(name === info?.branch ? "" : name); return; }+ if (!info || name === info.branch) return;+ setSwitching(true);+ try {+ const result = await prepareGit(folder, { mode: "switch_branch", branch: name, base: "" });+ if (result.message) pushToast("success", result.message);+ } catch (error) {+ pushToast("error", error instanceof Error ? error.message : String(error));+ } finally {+ setSwitching(false);+ refresh();+ }+ };++ return <div className="mx-auto flex w-full max-w-3xl items-center justify-between gap-2 px-3 pt-1.5" data-testid="thread-branch-bar">+ {draft+ ? <button ref={checkoutAnchor} type="button" className={BUTTON} disabled={!repo} aria-haspopup="menu" aria-expanded={menu === "checkout"}+ onClick={() => setMenu(menu === "checkout" ? null : "checkout")} title={repo ? "Where the agent works" : "Not a git repository"}>+ {checkout === "worktree" ? <FolderGit2 aria-hidden className="h-3.5 w-3.5 shrink-0" /> : <Laptop aria-hidden className="h-3.5 w-3.5 shrink-0" />}+ <span className="truncate">{checkout === "worktree" ? "New worktree" : "Current checkout"}</span>+ {repo && <ChevronDown aria-hidden className="h-3 w-3 shrink-0" />}+ </button>+ : <span className={cn(BUTTON, "hover:bg-transparent hover:text-muted-foreground")} title={folder}>+ {info?.is_worktree ? <FolderGit2 aria-hidden className="h-3.5 w-3.5 shrink-0" /> : <Laptop aria-hidden className="h-3.5 w-3.5 shrink-0" />}+ <span className="truncate">{info?.is_worktree ? `Worktree · ${folderLabel(folder)}` : "Current checkout"}</span>+ </span>}+ {repo && <button ref={branchAnchor} type="button" className={BUTTON} disabled={switching || (!draft && locked)}+ aria-haspopup="menu" aria-expanded={menu === "branch"}+ title={worktreeDraft ? "The branch the new worktree starts from" : locked ? "The agent is working on this branch" : "Switch branch"}+ onClick={() => { refresh(); setMenu(menu === "branch" ? null : "branch"); }}>+ {switching || loading ? <Loader2 aria-hidden className="h-3.5 w-3.5 shrink-0 animate-spin" /> : <GitBranch aria-hidden className="h-3.5 w-3.5 shrink-0" />}+ <span className="max-w-[220px] truncate font-mono">{worktreeDraft ? `from ${shownBranch || "HEAD"}` : shownBranch || "detached"}</span>+ {info && info.dirty && !worktreeDraft && <span className="text-warning" title="Uncommitted changes">•</span>}+ <ChevronDown aria-hidden className="h-3 w-3 shrink-0" />+ </button>}++ <ThreadPopover anchor={checkoutAnchor} open={menu === "checkout"} onClose={() => setMenu(null)} label="Where the agent works" side="top" width={280}>+ <div role="menu">+ <ThreadMenuItem icon={<Laptop className="h-3.5 w-3.5" />} selected={checkout === "current"}+ label="Current checkout" hint={checkout === "current" ? <Check className="h-3.5 w-3.5" /> : undefined}+ onSelect={() => { onCheckout("current"); setMenu(null); }} />+ <ThreadMenuItem icon={<FolderGit2 className="h-3.5 w-3.5" />} selected={checkout === "worktree"}+ label="New worktree" hint={checkout === "worktree" ? <Check className="h-3.5 w-3.5" /> : "own branch"}+ onSelect={() => { onCheckout("worktree"); setMenu(null); }} />+ </div>+ </ThreadPopover>+ <ThreadPopover anchor={branchAnchor} open={menu === "branch"} onClose={() => setMenu(null)} label="Branches" side="top" align="end" width={300}>+ <div role="menu">+ <ThreadMenuHeading>{worktreeDraft ? "Start the worktree from" : "Switch to"}</ThreadMenuHeading>+ {(info?.branches ?? []).map((branch) => {+ const busyElsewhere = !worktreeDraft && Boolean(branch.worktree) && !branch.current;+ return <ThreadMenuItem key={branch.name} icon={<GitBranch className="h-3.5 w-3.5" />}+ label={<span className="font-mono text-xs">{branch.name}</span>}+ selected={branch.name === shownBranch}+ hint={branch.name === shownBranch ? <Check className="h-3.5 w-3.5" /> : busyElsewhere ? "in a worktree" : branch.name === info?.default_branch ? "default" : undefined}+ disabled={busyElsewhere}+ onSelect={() => void pickBranch(branch.name)} />;+ })}+ {info && info.branches.length === 0 && <p className="px-2 py-2 text-xs text-muted-foreground">No local branches yet.</p>}+ </div>+ </ThreadPopover>+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsxnew file mode 100644index 0000000000..d95cf7e3ab--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx@@ -0,0 +1,343 @@+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";+import { ArrowUp, FileText, Image as ImageIcon, Loader2, MessageCircleQuestion, Paperclip, ShieldAlert, Square, X } from "lucide-react";+import { ComposerTypeahead } from "@/components/agentchat/ComposerTypeahead";+import { runningTurn, type QuestionState, type Timeline, type ToolBlock } from "@/components/agentchat/reduce";+import { useChatAttachments } from "@/components/agentchat/useChatAttachments";+import { useComposerTypeahead } from "@/components/agentchat/useComposerTypeahead";+import type { ChatAttachment } from "@/lib/agentChatApi";+import { joinProviderOptions } from "@/store/agentChat";+import { cn } from "@/lib/utils";+import { AccessPicker, AgentModelPicker, EffortPicker } from "./ThreadPickers";+import { threadAgents, useThreadChatStore } from "./threadModel";++/** A message typed while the agent was still working, sent when it is free. */+interface QueuedMessage {+ id: number;+ text: string;+ attachments: ChatAttachment[];+}++/** Draft text per thread, so switching threads never loses a half-written message. */+const drafts = new Map<string, string>();++/** The open question card of the newest turn, if any. */+function openQuestion(timeline: Timeline): { block: ToolBlock; question: QuestionState } | null {+ for (let i = timeline.items.length - 1; i >= 0; i--) {+ const item = timeline.items[i];+ if (item.type !== "turn") continue;+ for (const block of item.blocks) {+ if (block.kind === "tool" && block.question && !block.question.closed) return { block, question: block.question };+ }+ return null;+ }+ return null;+}++function ApprovalPanel({ timeline, onDecide }: { timeline: Timeline; onDecide: (id: string, decision: "allow" | "allow_always" | "deny") => void }) {+ const pending = timeline.pendingApprovals[0];+ if (!pending) return null;+ const input = pending.input && typeof pending.input === "object" ? pending.input as Record<string, unknown> : {};+ const detail = String(input.command ?? input.file_path ?? input.path ?? input.url ?? "");+ return <div data-testid="thread-approval" className="border-b border-border px-4 py-3">+ <div className="flex items-start gap-2.5">+ <ShieldAlert aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-warning" />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-foreground-strong">Approval needed{timeline.pendingApprovals.length > 1 ? ` (${timeline.pendingApprovals.length})` : ""}</p>+ <p className="mt-0.5 text-sm text-muted-foreground">{pending.summary || pending.name}</p>+ {detail && <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-secondary px-2.5 py-1.5 font-mono text-xs text-foreground scrollbar-jarvis">{detail}</pre>}+ </div>+ </div>+ <div className="mt-3 flex flex-wrap justify-end gap-2">+ <button type="button" onClick={() => onDecide(pending.approvalId, "deny")}+ className="rounded-lg px-3 py-1.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Decline</button>+ <button type="button" onClick={() => onDecide(pending.approvalId, "allow_always")}+ className="rounded-lg border border-border px-3 py-1.5 text-sm text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Always allow</button>+ <button type="button" data-testid="thread-approve" onClick={() => onDecide(pending.approvalId, "allow")}+ className="rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-accent-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Approve</button>+ </div>+ </div>;+}++function QuestionPanel({ timeline }: { timeline: Timeline }) {+ const open = openQuestion(timeline);+ const [text, setText] = useState("");+ const [error, setError] = useState("");+ const [sending, setSending] = useState(false);+ if (!open) return null;+ const { question } = open;+ const index = question.answers.findIndex((answer) => answer === null);+ if (index < 0) return null;+ const item = question.questions[index];+ const answer = async (payload: { optionIndex: number } | { text: string }) => {+ setSending(true);+ setError("");+ try {+ await useThreadChatStore.getState().answerQuestion(question.questionId, index, payload);+ setText("");+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSending(false);+ }+ };+ return <div data-testid="thread-question" className="border-b border-border px-4 py-3">+ <div className="flex items-start gap-2.5">+ <MessageCircleQuestion aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-accent" />+ <div className="min-w-0 flex-1">+ <p className="text-xs text-muted-foreground">{question.asker || "The agent"} asks{question.questions.length > 1 ? ` · ${index + 1} of ${question.questions.length}` : ""}</p>+ <p className="mt-0.5 text-sm font-medium text-foreground-strong">{item.question}</p>+ <div className="mt-2 flex flex-col gap-1">+ {item.options.map((option, optionIndex) => <button key={optionIndex} type="button" disabled={sending}+ onClick={() => void answer({ optionIndex })}+ className="flex w-full items-start gap-2 rounded-lg border border-border px-3 py-2 text-left text-sm hover:bg-secondary disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span className="min-w-0 flex-1"><span className="text-foreground">{option.label}</span>+ {option.description && <span className="block text-xs text-muted-foreground">{option.description}</span>}</span>+ {optionIndex === 0 && <span className="shrink-0 text-xs text-accent">Recommended</span>}+ </button>)}+ </div>+ <form className="mt-2 flex gap-2" onSubmit={(event) => { event.preventDefault(); if (text.trim()) void answer({ text: text.trim() }); }}>+ <input value={text} onChange={(event) => setText(event.target.value)} placeholder="Or type your own answer" disabled={sending}+ className="min-w-0 flex-1 rounded-lg border border-input bg-background px-3 py-1.5 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ <button type="button" disabled={sending} onClick={() => void useThreadChatStore.getState().skipQuestion(question.questionId).catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))}+ className="rounded-lg px-3 py-1.5 text-sm text-muted-foreground hover:bg-secondary">Skip</button>+ </form>+ {error && <p role="alert" className="mt-1 text-xs text-destructive">{error}</p>}+ </div>+ </div>+ </div>;+}++/**+ * The thread's composer: a rounded card with the text box, the files that+ * will go with the message, and one row of picks — agent and model, effort,+ * access — beside the paperclip and the send button. An approval or a+ * question the agent is waiting on opens at the top of the card, where the+ * person's eyes already are.+ *+ * `prepareDraft` runs before a NEW thread's first message and says which+ * folder the thread starts in (its project, or a fresh worktree of it);+ * returning null cancels the send.+ */+export function ThreadComposer({+ threadKey,+ prepareDraft,+ placeholder = "Ask for changes, send follow-ups, or attach images",+ autoFocusNonce,+}: {+ /** Which thread the box is typing for — the session id, or `draft:<project>`. */+ threadKey: string;+ prepareDraft: () => Promise<string | null>;+ placeholder?: string;+ autoFocusNonce: number;+}) {+ const draft = useThreadChatStore((state) => state.draft);+ const timeline = useThreadChatStore((state) => state.timeline);+ const activeSessionId = useThreadChatStore((state) => state.activeSessionId);+ const activeSession = useThreadChatStore((state) => state.activeSession);+ const catalog = useThreadChatStore((state) => state.catalog);+ const connections = useThreadChatStore((state) => state.connections);+ const liveModels = useThreadChatStore((state) => state.liveModels);+ const busy = useThreadChatStore((state) => state.busy);+ const lastError = useThreadChatStore((state) => state.lastError);+ const [value, setValueState] = useState(() => drafts.get(threadKey) ?? "");+ const [queue, setQueue] = useState<QueuedMessage[]>([]);+ const [problem, setProblem] = useState("");+ const [starting, setStarting] = useState(false);+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);+ const cardRef = useRef<HTMLDivElement | null>(null);+ const fileInput = useRef<HTMLInputElement | null>(null);+ const queueId = useRef(0);++ const providers = useMemo(+ () => threadAgents(catalog ? joinProviderOptions(catalog.providers, connections) : []),+ [catalog, connections],+ );+ const provider = providers.find((option) => option.id === draft.provider) ?? null;+ const running = runningTurn(timeline) !== null || Boolean(activeSession?.running);+ const started = timeline.items.length > 0;++ // A coding thread only runs on a coding agent: an API row left in the draft+ // from elsewhere moves to the first connected CLI.+ useEffect(() => {+ if (activeSessionId || providers.length === 0) return;+ if (providers.some((option) => option.id === draft.provider && option.connected)) return;+ const pick = providers.find((option) => option.connected) ?? providers[0];+ if (pick && pick.id !== draft.provider) void useThreadChatStore.getState().setDraft({ provider: pick.id });+ }, [activeSessionId, providers, draft.provider]);++ const setValue = useCallback((next: string) => {+ setValueState(next);+ drafts.set(threadKey, next);+ }, [threadKey]);++ // Another thread: its own half-written text, its own queue.+ useEffect(() => {+ setValueState(drafts.get(threadKey) ?? "");+ setQueue([]);+ setProblem("");+ }, [threadKey]);++ useEffect(() => {+ if (autoFocusNonce > 0) textareaRef.current?.focus();+ }, [autoFocusNonce]);++ // Grow with the text, up to a third of the window.+ useEffect(() => {+ const box = textareaRef.current;+ if (!box) return;+ box.style.height = "auto";+ box.style.height = `${Math.min(box.scrollHeight, Math.max(160, window.innerHeight / 3))}px`;+ }, [value]);++ const files = useChatAttachments(+ { sessionId: activeSessionId, cwd: draft.cwd, provider: draft.provider, surface: "agent" },+ (message) => setProblem(message),+ );+ const triggers = useMemo(() => provider?.typeahead ?? [], [provider]);+ const typeahead = useComposerTypeahead(textareaRef, value, setValue, {+ surface: "agent",+ provider: draft.provider,+ cwd: draft.cwd,+ triggers,+ });++ const dispatch = useCallback(async (text: string, attachments: ChatAttachment[]) => {+ const store = useThreadChatStore.getState();+ if (!store.activeSessionId) {+ setStarting(true);+ try {+ const cwd = await prepareDraft();+ if (cwd === null) return false;+ if (cwd !== store.draft.cwd) await store.setDraft({ cwd });+ } catch (error) {+ setProblem(error instanceof Error ? error.message : String(error));+ return false;+ } finally {+ setStarting(false);+ }+ }+ await useThreadChatStore.getState().send(text, attachments);+ return !useThreadChatStore.getState().lastError;+ }, [prepareDraft]);++ // A queued message goes out the moment the agent is free again.+ useEffect(() => {+ if (running || busy || starting || queue.length === 0 || !activeSessionId) return;+ const [next, ...rest] = queue;+ setQueue(rest);+ void dispatch(next.text, next.attachments);+ }, [running, busy, starting, queue, activeSessionId, dispatch]);++ const submit = async () => {+ const text = value.trim();+ if (!text && files.attachments.length === 0) return;+ if (files.analyzing > 0 || starting) return;+ if (!provider || !provider.connected) {+ setProblem("Choose a connected coding agent first.");+ return;+ }+ const attachments = files.attachments;+ setValue("");+ files.clear();+ setProblem("");+ if (running || busy) {+ setQueue((current) => [...current, { id: ++queueId.current, text, attachments }]);+ return;+ }+ const sent = await dispatch(text, attachments);+ if (!sent && !useThreadChatStore.getState().activeSessionId) {+ // Nothing was created: give the words back instead of losing them.+ setValue(text);+ }+ };++ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (typeahead.onKeyDown(event)) return;+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ void submit();+ }+ };++ const decide = (approvalId: string, decision: "allow" | "allow_always" | "deny") => {+ void useThreadChatStore.getState().decide(approvalId, decision);+ };++ const canSend = (value.trim().length > 0 || files.attachments.length > 0) && files.analyzing === 0 && !starting;+ const error = problem || lastError || "";++ return <div className="mx-auto w-full max-w-3xl">+ {queue.length > 0 && <div className="mb-2 flex flex-col gap-1 px-2" data-testid="thread-queue">+ {queue.map((entry) => <div key={entry.id} className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-1.5 text-sm">+ <span className="shrink-0 text-xs text-muted-foreground">Queued</span>+ <span className="min-w-0 flex-1 truncate text-foreground">{entry.text || `${entry.attachments.length} file(s)`}</span>+ <button type="button" aria-label="Remove queued message" onClick={() => setQueue((current) => current.filter((row) => row.id !== entry.id))}+ className="rounded p-0.5 text-muted-foreground hover:text-foreground"><X className="h-3.5 w-3.5" /></button>+ </div>)}+ </div>}+ <div ref={cardRef} {...files.dragHandlers}+ className={cn(+ "relative overflow-hidden rounded-3xl border border-border bg-card shadow-rim transition-colors focus-within:border-border-strong",+ files.dragging && "border-accent ring-2 ring-accent/40",+ )}>+ <ApprovalPanel timeline={timeline} onDecide={decide} />+ <QuestionPanel timeline={timeline} />+ {(files.attachments.length > 0 || files.analyzing > 0) && <div className="flex flex-wrap gap-1.5 px-4 pt-3">+ {files.attachments.map((file) => <span key={file.name} className="inline-flex max-w-[220px] items-center gap-1.5 rounded-lg border border-border bg-background px-2 py-1 text-xs text-foreground" title={file.note || file.name}>+ {file.kind === "image" ? <ImageIcon aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <FileText aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}+ <span className="truncate">{file.name}</span>+ <button type="button" aria-label={`Remove ${file.name}`} onClick={() => files.remove(file.name)} className="rounded text-muted-foreground hover:text-foreground"><X className="h-3 w-3" /></button>+ </span>)}+ {files.analyzing > 0 && <span className="inline-flex items-center gap-1.5 px-1 text-xs text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin" />Reading {files.analyzing} file{files.analyzing === 1 ? "" : "s"}…</span>}+ </div>}+ <textarea ref={textareaRef} value={value} rows={2} data-testid="thread-composer-input"+ aria-label="Message the coding agent"+ placeholder={running ? "Queue a follow-up for when the agent is done" : placeholder}+ onChange={(event) => { setValue(event.target.value); typeahead.refresh(); }}+ onKeyDown={onKeyDown}+ onKeyUp={() => typeahead.refresh()}+ onClick={() => typeahead.refresh()}+ onBlur={() => typeahead.blur()}+ onPaste={files.onPaste}+ className="block max-h-[40vh] min-h-[56px] w-full resize-none bg-transparent px-4 pb-1 pt-3.5 text-base leading-6 text-foreground outline-none placeholder:text-faint-foreground" />+ <div className="flex items-center gap-1 px-2 pb-2 pt-1">+ <AgentModelPicker providers={providers} liveModels={liveModels} draft={draft}+ lockedProvider={started && activeSessionId ? draft.provider : null}+ onPick={(nextProvider, model) => {+ const store = useThreadChatStore.getState();+ void store.setDraft(nextProvider !== draft.provider ? { provider: nextProvider, model } : { model });+ }} />+ <EffortPicker provider={provider} draft={draft} liveModels={liveModels}+ onPick={(effort) => void useThreadChatStore.getState().setDraft({ effort })} />+ <AccessPicker provider={provider} draft={draft}+ onPick={(permissionMode) => void useThreadChatStore.getState().setDraft({ permissionMode })} />+ <div className="ml-auto flex items-center gap-1">+ <input ref={fileInput} type="file" multiple hidden onChange={(event) => {+ const picked = Array.from(event.target.files ?? []);+ if (picked.length) files.attachFiles(picked);+ event.target.value = "";+ }} />+ <button type="button" aria-label="Attach files" title="Attach files or images" onClick={() => fileInput.current?.click()}+ className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Paperclip className="h-4 w-4" />+ </button>+ {running && !canSend+ ? <button type="button" aria-label="Stop the agent" title="Stop" data-testid="thread-stop"+ onClick={() => void useThreadChatStore.getState().cancel()}+ className="flex h-8 w-8 items-center justify-center rounded-full bg-foreground text-background hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Square className="h-3 w-3 fill-current" />+ </button>+ : <button type="button" aria-label={running ? "Queue message" : "Send message"} title={running ? "Queue for when the agent is done" : "Send"}+ data-testid="thread-send" disabled={!canSend} onClick={() => void submit()}+ className="flex h-8 w-8 items-center justify-center rounded-full bg-accent text-accent-foreground transition-opacity hover:opacity-90 disabled:opacity-35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {starting || busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <ArrowUp className="h-4 w-4" />}+ </button>}+ </div>+ </div>+ </div>+ {error && <p role="alert" className="mt-2 px-3 text-xs text-destructive">{error}</p>}+ <ComposerTypeahead anchorRef={cardRef} open={typeahead.open} trigger={typeahead.token?.trigger ?? null}+ items={typeahead.items} loading={typeahead.loading} activeIndex={typeahead.activeIndex}+ onHover={typeahead.setActiveIndex} onPick={typeahead.pick} />+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsxnew file mode 100644index 0000000000..8af84a4856--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx@@ -0,0 +1,113 @@+import { useEffect, useState } from "react";+import { ChevronLeft, FileDiff, Loader2, RefreshCw, X } from "lucide-react";+import { DiffView } from "@/components/agentic/sidePanel/explorer/DiffView";+import { fetchFolderChanges, fetchFolderDiff, type FolderChange, type FolderChanges, type FolderDiff } from "@/lib/gitApi";+import { cn } from "@/lib/utils";++const STATUS_MARK: Record<FolderChange["status"], { letter: string; className: string }> = {+ modified: { letter: "M", className: "text-warning" },+ added: { letter: "A", className: "text-success" },+ untracked: { letter: "U", className: "text-success" },+ deleted: { letter: "D", className: "text-destructive" },+ conflicted: { letter: "!", className: "text-destructive" },+};++function splitPath(path: string): { name: string; dir: string } {+ const parts = path.split("/");+ const name = parts.pop() ?? path;+ return { name, dir: parts.join("/") };+}++/**+ * The thread's own diff panel: every file changed under the thread's folder,+ * and one file's change against the last commit. It reads the thread's+ * folder — a worktree no workspace has open included — and reads again when+ * a turn ends (`version`).+ */+export function ThreadDiffPanel({ folder, version, onClose }: { folder: string; version: number; onClose: () => void }) {+ const [changes, setChanges] = useState<FolderChanges | null>(null);+ const [error, setError] = useState("");+ const [loading, setLoading] = useState(false);+ const [nonce, setNonce] = useState(0);+ const [openPath, setOpenPath] = useState<string | null>(null);+ const [diff, setDiff] = useState<FolderDiff | null>(null);+ const [diffError, setDiffError] = useState("");++ useEffect(() => {+ const controller = new AbortController();+ setLoading(true);+ setError("");+ fetchFolderChanges(folder, controller.signal)+ .then((next) => { if (!controller.signal.aborted) setChanges(next); })+ .catch((err: unknown) => { if (!controller.signal.aborted) setError(err instanceof Error ? err.message : String(err)); })+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });+ return () => controller.abort();+ }, [folder, version, nonce]);++ useEffect(() => {+ setOpenPath(null);+ }, [folder]);++ useEffect(() => {+ if (!openPath) { setDiff(null); return; }+ const controller = new AbortController();+ setDiff(null);+ setDiffError("");+ fetchFolderDiff(folder, openPath, controller.signal)+ .then((next) => { if (!controller.signal.aborted) setDiff(next); })+ .catch((err: unknown) => { if (!controller.signal.aborted) setDiffError(err instanceof Error ? err.message : String(err)); });+ return () => controller.abort();+ }, [folder, openPath, version]);++ const files = (changes?.files ?? []).filter((file) => !file.is_directory);+ const added = files.reduce((sum, file) => sum + (file.added ?? 0), 0);+ const removed = files.reduce((sum, file) => sum + (file.removed ?? 0), 0);++ return <aside aria-label="Changes" data-testid="thread-diff-panel" className="flex h-full min-h-0 flex-col border-l border-border bg-background">+ <div className="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3">+ {openPath+ ? <button type="button" aria-label="Back to the changed files" onClick={() => setOpenPath(null)}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"><ChevronLeft className="h-4 w-4" /></button>+ : <FileDiff aria-hidden className="h-4 w-4 text-muted-foreground" />}+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground-strong" title={openPath ?? undefined}>+ {openPath ? splitPath(openPath).name : "Changes"}+ </span>+ {!openPath && files.length > 0 && <span className="shrink-0 font-mono text-xs tabular-nums">+ <span className="text-success">+{added}</span> <span className="text-destructive">−{removed}</span>+ </span>}+ <button type="button" aria-label="Read the changes again" title="Refresh" onClick={() => setNonce((value) => value + 1)}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground">+ {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}+ </button>+ <button type="button" aria-label="Close changes" onClick={onClose} className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"><X className="h-4 w-4" /></button>+ </div>+ <div className="min-h-0 flex-1 overflow-auto scrollbar-jarvis">+ {openPath+ ? diffError ? <p className="px-4 py-3 text-sm text-destructive">{diffError}</p>+ : !diff ? <p className="flex items-center gap-2 px-4 py-3 text-sm text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin" />Loading the diff…</p>+ : diff.binary ? <p className="px-4 py-3 text-sm text-muted-foreground">A binary file — no line diff.</p>+ : diff.hunks.length === 0 ? <p className="px-4 py-3 text-sm text-muted-foreground">No changes in this file.</p>+ : <DiffView hunks={diff.hunks} />+ : error ? <p className="px-4 py-3 text-sm text-destructive">{error}</p>+ : changes && !changes.available ? <p className="px-4 py-3 text-sm text-muted-foreground">{changes.reason || "This folder is not a git repository."}</p>+ : files.length === 0 ? <p className="px-4 py-3 text-sm text-muted-foreground">{loading ? "Reading the changes…" : "No changes yet."}</p>+ : <ul className="py-1">+ {files.map((file) => {+ const { name, dir } = splitPath(file.path);+ const mark = STATUS_MARK[file.status] ?? STATUS_MARK.modified;+ return <li key={file.path}>+ <button type="button" onClick={() => setOpenPath(file.path)} title={file.path}+ className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">+ <span className={cn("w-3 shrink-0 text-center font-mono text-xs", mark.className)}>{mark.letter}</span>+ <span className="min-w-0 flex-1 truncate"><span className="text-foreground">{name}</span>{dir && <span className="ml-1.5 text-xs text-muted-foreground">{dir}</span>}</span>+ <span className="shrink-0 font-mono text-xs tabular-nums">+ {file.added != null && file.added > 0 && <span className="text-success">+{file.added}</span>}+ {file.removed != null && file.removed > 0 && <span className="ml-1 text-destructive">−{file.removed}</span>}+ </span>+ </button>+ </li>;+ })}+ </ul>}+ </div>+ </aside>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadHeader.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadHeader.tsxnew file mode 100644index 0000000000..295c061ea5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadHeader.tsx@@ -0,0 +1,289 @@+import { useEffect, useRef, useState } from "react";+import {+ ChevronDown, FileDiff, FolderOpen, GitCommitHorizontal, GitPullRequest, Globe, Loader2, Pencil, Play, Plus,+ SquareCode, SquareTerminal, Trash2, Upload,+} from "lucide-react";+import { patchAgentChatSession } from "@/lib/agentChatApi";+import { fetchProjectLaunchers, openProjectIn, revealProject, type ProjectLaunchers } from "@/lib/chatLibraryApi";+import { commitAll, openPullRequest, pushBranch } from "@/lib/gitApi";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { useGitInfo } from "./ThreadBranchBar";+import { ThreadMenuHeading, ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "./ThreadPopover";+import { deleteProjectAction, readProjectActions, saveProjectAction, type ProjectAction } from "./projectActions";+import { useThreadChatStore } from "./threadModel";++const PILL = "flex h-7 items-center gap-1.5 rounded-md border border-border px-2 text-xs text-foreground transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50";+const ICON_BUTTON = "flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";++const FILE_MANAGER_LABEL = (() => {+ const platform = typeof navigator === "undefined" ? "" : navigator.userAgent;+ if (/Windows/i.test(platform)) return "Show in Explorer";+ if (/Mac OS X|Macintosh/i.test(platform)) return "Show in Finder";+ return "Show in file manager";+})();++const LAST_EDITOR_KEY = "jarvis.ide.threadOpenIn.v1";++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/** "Add action", or the project's first action with the rest behind a chevron. */+function ActionsControl({ projectId, onRun }: { projectId: string; onRun: (action: ProjectAction) => void }) {+ const [actions, setActions] = useState<ProjectAction[]>(() => readProjectActions(projectId));+ const [menu, setMenu] = useState(false);+ const [editing, setEditing] = useState<ProjectAction | null>(null);+ const anchor = useRef<HTMLDivElement | null>(null);+ useEffect(() => { setActions(readProjectActions(projectId)); }, [projectId]);+ const first = actions[0];+ const startNew = () => { setEditing({ id: `action-${Date.now().toString(36)}`, name: "", command: "" }); setMenu(true); };+ const save = () => {+ if (!editing || !editing.name.trim() || !editing.command.trim()) return;+ setActions(saveProjectAction(projectId, { ...editing, name: editing.name.trim(), command: editing.command.trim() }));+ setEditing(null);+ setMenu(false);+ };+ return <div ref={anchor} className="flex items-center">+ {first+ ? <div className="flex items-center">+ <button type="button" className={cn(PILL, "rounded-r-none")} onClick={() => onRun(first)} title={first.command} data-testid="thread-action-run">+ <Play aria-hidden className="h-3 w-3" />{first.name}+ </button>+ <button type="button" aria-label="More actions" aria-haspopup="menu" aria-expanded={menu}+ className={cn(PILL, "rounded-l-none border-l-0 px-1")} onClick={() => { setEditing(null); setMenu(!menu); }}>+ <ChevronDown aria-hidden className="h-3 w-3" />+ </button>+ </div>+ : <button type="button" className={cn(PILL, "border-transparent text-muted-foreground hover:text-foreground")} onClick={startNew} data-testid="thread-add-action">+ <Plus aria-hidden className="h-3 w-3" />Add action+ </button>}+ <ThreadPopover anchor={anchor} open={menu} onClose={() => { setMenu(false); setEditing(null); }} label="Project actions" align="end" width={320}>+ {editing+ ? <form className="space-y-2 p-2" onSubmit={(event) => { event.preventDefault(); save(); }}>+ <p className="text-sm font-medium text-foreground-strong">{actions.some((row) => row.id === editing.id) ? "Edit action" : "New action"}</p>+ <p className="text-xs text-muted-foreground">A command this project runs often. It opens in the terminal drawer.</p>+ <label className="block text-xs text-muted-foreground">Name+ <input autoFocus value={editing.name} onChange={(event) => setEditing({ ...editing, name: event.target.value })} placeholder="Dev server" maxLength={40}+ className="mt-1 w-full rounded-md border border-input bg-background px-2 py-1.5 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ </label>+ <label className="block text-xs text-muted-foreground">Command+ <input value={editing.command} onChange={(event) => setEditing({ ...editing, command: event.target.value })} placeholder="npm run dev"+ className="mt-1 w-full rounded-md border border-input bg-background px-2 py-1.5 font-mono text-xs text-foreground outline-none focus:ring-2 focus:ring-ring" />+ </label>+ <div className="flex justify-end gap-2 pt-1">+ <button type="button" onClick={() => setEditing(null)} className="rounded-md px-2.5 py-1 text-sm text-muted-foreground hover:bg-secondary">Cancel</button>+ <button type="submit" disabled={!editing.name.trim() || !editing.command.trim()} className="rounded-md bg-accent px-2.5 py-1 text-sm text-accent-foreground disabled:opacity-40">Save</button>+ </div>+ </form>+ : <div role="menu">+ {actions.map((action) => <div key={action.id} className="group/action flex items-center">+ <div className="min-w-0 flex-1"><ThreadMenuItem icon={<Play className="h-3.5 w-3.5" />} label={action.name}+ hint={<span className="font-mono">{action.command.length > 22 ? `${action.command.slice(0, 21)}…` : action.command}</span>}+ onSelect={() => { setMenu(false); onRun(action); }} /></div>+ <button type="button" aria-label={`Edit ${action.name}`} onClick={() => setEditing(action)} className="rounded p-1 text-muted-foreground opacity-0 hover:text-foreground group-hover/action:opacity-100"><Pencil className="h-3.5 w-3.5" /></button>+ <button type="button" aria-label={`Delete ${action.name}`} onClick={() => setActions(deleteProjectAction(projectId, action.id))} className="rounded p-1 text-muted-foreground opacity-0 hover:text-destructive group-hover/action:opacity-100"><Trash2 className="h-3.5 w-3.5" /></button>+ </div>)}+ <ThreadMenuSeparator />+ <ThreadMenuItem icon={<Plus className="h-3.5 w-3.5" />} label="Add action" onSelect={startNew} />+ </div>}+ </ThreadPopover>+ </div>;+}++/** "Open" in the editor last used, with every editor and the file manager behind the chevron. */+function OpenInControl({ projectId }: { projectId: string }) {+ const pushToast = useEventStore((state) => state.pushToast);+ const [launchers, setLaunchers] = useState<ProjectLaunchers | null>(null);+ const [menu, setMenu] = useState(false);+ const anchor = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ let live = true;+ fetchProjectLaunchers(projectId).then((next) => { if (live) setLaunchers(next); }).catch(() => { if (live) setLaunchers(null); });+ return () => { live = false; };+ }, [projectId]);+ const editors = launchers?.editors ?? [];+ let remembered = "";+ try { remembered = localStorage.getItem(LAST_EDITOR_KEY) ?? ""; } catch { /* blocked storage: the first editor leads */ }+ const preferred = editors.find((editor) => editor.id === remembered) ?? editors[0];+ const open = async (target: string) => {+ setMenu(false);+ try {+ if (target === "files") { await revealProject(projectId); return; }+ if (target === "remote" && launchers?.remote_url) { await openExternalUrl(launchers.remote_url); return; }+ await openProjectIn(projectId, target);+ try { localStorage.setItem(LAST_EDITOR_KEY, target); } catch { /* a convenience only */ }+ } catch (error) {+ pushToast("error", errorText(error));+ }+ };+ if (!launchers) return null;+ return <div ref={anchor} className="flex items-center">+ <button type="button" className={cn(PILL, "rounded-r-none")} data-testid="thread-open-in"+ onClick={() => void open(preferred ? preferred.id : "files")} title={preferred ? `Open in ${preferred.label}` : FILE_MANAGER_LABEL}>+ {preferred ? <SquareCode aria-hidden className="h-3.5 w-3.5" /> : <FolderOpen aria-hidden className="h-3.5 w-3.5" />}Open+ </button>+ <button type="button" aria-label="Open in…" aria-haspopup="menu" aria-expanded={menu} className={cn(PILL, "rounded-l-none border-l-0 px-1")} onClick={() => setMenu(!menu)}>+ <ChevronDown aria-hidden className="h-3 w-3" />+ </button>+ <ThreadPopover anchor={anchor} open={menu} onClose={() => setMenu(false)} label="Open in" align="end" width={240}>+ <div role="menu">+ {editors.map((editor) => <ThreadMenuItem key={editor.id} icon={<SquareCode className="h-3.5 w-3.5" />} label={editor.label}+ selected={editor.id === preferred?.id} onSelect={() => void open(editor.id)} />)}+ {launchers.file_manager && <ThreadMenuItem icon={<FolderOpen className="h-3.5 w-3.5" />} label={FILE_MANAGER_LABEL} onSelect={() => void open("files")} />}+ {launchers.remote_url && <ThreadMenuItem icon={<Globe className="h-3.5 w-3.5" />} label={launchers.remote_label ? `Open on ${launchers.remote_label}` : "Open the remote"} onSelect={() => void open("remote")} />}+ </div>+ </ThreadPopover>+ </div>;+}++/** Commit, push and open a pull request for the thread's folder. */+function GitControl({ folder, version, defaultMessage }: { folder: string; version: number; defaultMessage: string }) {+ const pushToast = useEventStore((state) => state.pushToast);+ const { info, refresh } = useGitInfo(folder);+ const [menu, setMenu] = useState(false);+ const [message, setMessage] = useState("");+ const [working, setWorking] = useState<string | null>(null);+ const anchor = useRef<HTMLButtonElement | null>(null);+ useEffect(() => { if (menu) { refresh(); setMessage((current) => current || defaultMessage); } }, [menu, refresh, defaultMessage]);+ useEffect(() => { if (version > 0) refresh(); }, [version, refresh]);+ if (!info?.is_repo) return null;+ const changed = info.changes.length;+ const hasRemote = info.remotes.length > 0;+ const label = info.dirty ? (hasRemote ? "Commit & push" : "Commit") : info.ahead > 0 ? "Push" : "Create PR";+ const run = async (what: string, work: () => Promise<void>) => {+ setWorking(what);+ try { await work(); }+ catch (error) { pushToast("error", errorText(error)); }+ finally { setWorking(null); refresh(); }+ };+ const commit = (push: boolean) => run(push ? "commit-push" : "commit", async () => {+ const text = message.trim();+ if (!text) throw new Error("Write a commit message first.");+ const result = await commitAll(folder, text);+ if (push) await pushBranch(folder);+ pushToast("success", push ? `Committed ${result.commit.slice(0, 7)} and pushed.` : `Committed ${result.commit.slice(0, 7)}.`);+ setMessage("");+ setMenu(false);+ });+ const push = () => run("push", async () => {+ const result = await pushBranch(folder);+ pushToast("success", `Pushed to ${result.upstream}.`);+ setMenu(false);+ });+ const pullRequest = () => run("pr", async () => {+ const result = await openPullRequest(folder, { title: message.trim() || defaultMessage });+ pushToast("success", "Pull request opened.");+ setMenu(false);+ if (result.url) void openExternalUrl(result.url);+ });+ return <>+ <button ref={anchor} type="button" className={PILL} aria-haspopup="dialog" aria-expanded={menu} onClick={() => setMenu(!menu)} data-testid="thread-git">+ {working ? <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin" /> : <GitCommitHorizontal aria-hidden className="h-3.5 w-3.5" />}+ {label}+ <ChevronDown aria-hidden className="h-3 w-3" />+ </button>+ <ThreadPopover anchor={anchor} open={menu} onClose={() => setMenu(false)} label="Git" align="end" width={340}>+ <div className="space-y-2 p-2">+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">+ <span className="truncate font-mono">{info.branch || "detached"}</span>+ <span className="shrink-0 tabular-nums">+ {changed > 0 ? `${changed} changed` : "clean"}+ {(info.insertions > 0 || info.deletions > 0) && <> · <span className="text-success">+{info.insertions}</span> <span className="text-destructive">−{info.deletions}</span></>}+ {info.ahead > 0 && ` · ${info.ahead} ahead`}+ {info.behind > 0 && ` · ${info.behind} behind`}+ </span>+ </div>+ {info.dirty && <>+ <textarea value={message} onChange={(event) => setMessage(event.target.value)} rows={3} aria-label="Commit message" placeholder="Commit message"+ className="w-full resize-none rounded-md border border-input bg-background px-2 py-1.5 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ <div className="flex justify-end gap-2">+ <button type="button" disabled={working !== null} onClick={() => void commit(false)} className="rounded-md border border-border px-2.5 py-1 text-sm hover:bg-secondary disabled:opacity-50">Commit</button>+ {hasRemote && <button type="button" disabled={working !== null} onClick={() => void commit(true)} className="rounded-md bg-accent px-2.5 py-1 text-sm text-accent-foreground disabled:opacity-50">Commit & push</button>}+ </div>+ </>}+ {!info.dirty && <p className="text-sm text-muted-foreground">{info.ahead > 0 ? `${info.ahead} commit${info.ahead === 1 ? "" : "s"} not pushed yet.` : "Nothing to commit."}</p>}+ <div role="menu" className="border-t border-border pt-1">+ <ThreadMenuHeading>More</ThreadMenuHeading>+ <ThreadMenuItem icon={<Upload className="h-3.5 w-3.5" />} label="Push" disabled={!hasRemote || working !== null || (info.ahead === 0 && Boolean(info.upstream))} onSelect={() => void push()} />+ <ThreadMenuItem icon={<GitPullRequest className="h-3.5 w-3.5" />} label="Create pull request" hint={info.gh_available ? undefined : "needs gh"}+ disabled={!hasRemote || !info.gh_available || working !== null || info.branch === info.default_branch} onSelect={() => void pullRequest()} />+ </div>+ </div>+ </ThreadPopover>+ </>;+}++/**+ * The bar over a thread: where it lives and what it is called on the left,+ * the project's actions, "Open", the git actions and the two drawer+ * switches on the right.+ */+export function ThreadHeader({+ projectId,+ projectName,+ folder,+ title,+ sessionId,+ terminalOpen,+ onToggleTerminal,+ diffOpen,+ onToggleDiff,+ gitVersion,+ onRunAction,+}: {+ projectId: string;+ projectName: string;+ folder: string;+ title: string;+ sessionId: string | null;+ terminalOpen: boolean;+ onToggleTerminal: () => void;+ diffOpen: boolean;+ onToggleDiff: () => void;+ /** Changes when a turn ends, so the git button reads the folder again. */+ gitVersion: number;+ onRunAction: (action: ProjectAction) => void;+}) {+ const pushToast = useEventStore((state) => state.pushToast);+ const [renaming, setRenaming] = useState<string | null>(null);+ const rename = async (next: string) => {+ setRenaming(null);+ const clean = next.trim();+ if (!sessionId || !clean || clean === title) return;+ try {+ await patchAgentChatSession(sessionId, { title: clean });+ await useThreadChatStore.getState().loadSessions();+ } catch (error) {+ pushToast("error", errorText(error));+ }+ };+ return <header className="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4" data-testid="thread-header">+ <div className="flex min-w-0 flex-1 items-center gap-2 text-sm">+ <span className="shrink-0 truncate text-muted-foreground">{projectName}</span>+ <span aria-hidden className="text-faint-foreground">/</span>+ {renaming !== null+ ? <input autoFocus aria-label="Thread name" value={renaming} maxLength={120}+ onChange={(event) => setRenaming(event.target.value)} onBlur={() => void rename(renaming)}+ onKeyDown={(event) => { if (event.key === "Enter") void rename(renaming); if (event.key === "Escape") { event.stopPropagation(); setRenaming(null); } }}+ className="min-w-0 flex-1 rounded border border-input bg-background px-2 py-0.5 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ : <h1 className={cn("min-w-0 truncate font-medium text-foreground-strong", sessionId && "cursor-text")} title={sessionId ? `${title} — double-click to rename` : title}+ onDoubleClick={() => { if (sessionId) setRenaming(title); }} data-testid="thread-title">{title}</h1>}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ <ActionsControl projectId={projectId} onRun={onRunAction} />+ <OpenInControl projectId={projectId} />+ <GitControl folder={folder} version={gitVersion} defaultMessage={title === "New thread" ? "" : title} />+ <span aria-hidden className="mx-0.5 h-4 w-px bg-border" />+ <button type="button" aria-label={terminalOpen ? "Hide terminal" : "Show terminal"} title="Terminal" aria-pressed={terminalOpen}+ onClick={onToggleTerminal} className={cn(ICON_BUTTON, terminalOpen && "bg-secondary text-foreground")} data-testid="thread-terminal-toggle">+ <SquareTerminal className="h-4 w-4" />+ </button>+ <button type="button" aria-label={diffOpen ? "Hide changes" : "Show changes"} title="Changes" aria-pressed={diffOpen}+ onClick={onToggleDiff} className={cn(ICON_BUTTON, diffOpen && "bg-secondary text-foreground")} data-testid="thread-diff-toggle">+ <FileDiff className="h-4 w-4" />+ </button>+ </div>+ </header>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsxnew file mode 100644index 0000000000..06083a650b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx@@ -0,0 +1,119 @@+import { useMemo } from "react";+import { AgentMark } from "@/components/agentic/AgentMark";+import { permissionModeIcon } from "@/components/agentchat/permissionIcons";+import { Combobox, type ComboboxGroup } from "@/components/ui/combobox";+import { useT } from "@/i18n";+import type { CuratedModel } from "@/lib/agentChatApi";+import type { ComposerDraft, ProviderOption } from "@/store/agentChat";++/**+ * The three picks under a thread's composer: which coding agent and model+ * answer, how hard it thinks, and how much it may do without asking. Quiet+ * text buttons until opened; each opens the app's own searchable list.+ */++const TRIGGER = "w-auto max-w-[220px] gap-1.5 bg-transparent px-2 py-1 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground";++/** The name a coding agent goes by, not its API brand ("Claude Code", not "Anthropic Claude"). */+export function agentName(provider: Pick<ProviderOption, "agent" | "label">): string {+ switch (provider.agent) {+ case "claude": return "Claude Code";+ case "codex": return "Codex";+ default: return provider.label;+ }+}++const SEP = "\u0000";++const EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);++/** An effort level in the chat's own words ("" is the agent's default). */+function effortLabel(level: string, t: (key: string) => string): string {+ if (!level) return t("agent_chat.effort_default");+ return EFFORTS.has(level) ? t(`agent_chat.effort_${level}`) : level;+}++/** The models a provider row offers: its live list when it has one, else the curated one. */+export function modelsOf(provider: ProviderOption, liveModels: Record<string, CuratedModel[]>): CuratedModel[] {+ const live = liveModels[provider.id];+ return provider.models_source === "live" && live && live.length ? live : provider.curated_models ?? [];+}++export function AgentModelPicker({+ providers,+ liveModels,+ draft,+ lockedProvider,+ onPick,+}: {+ providers: ProviderOption[];+ liveModels: Record<string, CuratedModel[]>;+ draft: ComposerDraft;+ /** A thread that has started keeps its coding agent; only the model can change. */+ lockedProvider: string | null;+ onPick: (provider: string, model: string) => void;+}) {+ const groups = useMemo<ComboboxGroup[]>(() => providers.map((provider) => {+ const locked = lockedProvider !== null && provider.id !== lockedProvider;+ const disabled = !provider.connected || locked;+ const hint = locked ? "new thread" : !provider.connected ? (provider.cli_installed === false ? "not installed" : "connect first") : undefined;+ const icon = <AgentMark agent={provider.agent ?? ""} label={provider.label} logoUrl={provider.logoUrl} variant="plain" size="sm" />;+ const models = modelsOf(provider, liveModels).filter((model) => model.id);+ return {+ id: provider.id,+ label: agentName(provider),+ options: [+ { value: `${provider.id}${SEP}`, label: agentName(provider), hint: hint ?? "default model", icon, disabled },+ ...models.map((model) => ({+ value: `${provider.id}${SEP}${model.id}`,+ label: model.label || model.id,+ hint: hint ?? model.note,+ searchText: `${model.id} ${agentName(provider)}`,+ icon,+ disabled,+ })),+ ],+ };+ }), [providers, liveModels, lockedProvider]);+ return <Combobox ariaLabel="Coding agent and model" testId="thread-model-picker"+ value={`${draft.provider}${SEP}${draft.model}`} groups={groups}+ onChange={(value) => { const [provider, model = ""] = value.split(SEP); onPick(provider, model); }}+ fallbackLabel={draft.model || "Choose an agent"} searchPlaceholder="Search agents and models"+ triggerHint={false} className={TRIGGER} />;+}++export function EffortPicker({ provider, draft, liveModels, onPick }: {+ provider: ProviderOption | null;+ draft: ComposerDraft;+ liveModels: Record<string, CuratedModel[]>;+ onPick: (effort: string) => void;+}) {+ const t = useT();+ const levels = useMemo(() => {+ if (!provider) return [];+ const model = modelsOf(provider, liveModels).find((entry) => entry.id === draft.model);+ return model?.efforts ?? provider.effort_levels;+ }, [provider, liveModels, draft.model]);+ if (levels.length === 0 || (levels.length === 1 && levels[0] === "")) return null;+ return <Combobox ariaLabel="Reasoning effort" testId="thread-effort-picker" value={draft.effort}+ groups={[{ id: "effort", options: levels.map((level) => ({ value: level, label: effortLabel(level, t) })) }]}+ onChange={onPick} fallbackLabel={effortLabel(draft.effort, t)} triggerHint={false} className={TRIGGER} />;+}++export function AccessPicker({ provider, draft, onPick }: {+ provider: ProviderOption | null;+ draft: ComposerDraft;+ onPick: (mode: string) => void;+}) {+ const modes = provider?.permission_modes ?? [];+ if (modes.length === 0) return null;+ return <Combobox ariaLabel="What the agent may do without asking" testId="thread-access-picker" value={draft.permissionMode}+ groups={[{+ id: "access",+ options: modes.map((mode) => {+ const Icon = permissionModeIcon(mode.id);+ return { value: mode.id, label: mode.label, hint: mode.description, icon: <Icon aria-hidden className="h-3.5 w-3.5" /> };+ }),+ }]}+ onChange={onPick} fallbackLabel={draft.permissionMode || "Access"} triggerHint={false} className={TRIGGER} />;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPopover.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPopover.tsxnew file mode 100644index 0000000000..36c312ebf5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPopover.tsx@@ -0,0 +1,134 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";++/**+ * A small floating panel anchored to a button — the thread view's menus+ * (Open in, Git actions, project actions, a thread's row menu).+ *+ * Portalled to `body` so a scroll column never clips it, placed below the+ * anchor (above when there is no room) and kept inside the viewport. Escape+ * and a press outside close it; focus returns to the anchor.+ */+export function ThreadPopover({+ anchor,+ open,+ onClose,+ align = "start",+ side = "bottom",+ width = 260,+ className,+ label,+ children,+}: {+ anchor: RefObject<HTMLElement | null>;+ open: boolean;+ onClose: () => void;+ align?: "start" | "end";+ side?: "top" | "bottom";+ width?: number;+ className?: string;+ /** Accessible name of the panel. */+ label: string;+ children: ReactNode;+}) {+ const panel = useRef<HTMLDivElement | null>(null);+ const [place, setPlace] = useState<{ left: number; top: number; maxHeight: number } | null>(null);++ const measure = useCallback(() => {+ const host = anchor.current;+ if (!host) return;+ const rect = host.getBoundingClientRect();+ const margin = 8;+ const height = panel.current?.offsetHeight ?? 0;+ const below = window.innerHeight - rect.bottom - margin;+ const above = rect.top - margin;+ const wantTop = side === "top" ? above > Math.min(height, 240) || above > below : below < Math.min(height, 240) && above > below;+ const left = align === "end" ? rect.right - width : rect.left;+ const clampedLeft = Math.max(margin, Math.min(left, window.innerWidth - width - margin));+ const room = Math.max(120, wantTop ? above - 4 : below - 4);+ const top = wantTop ? Math.max(margin, rect.top - 4 - Math.min(height, room)) : rect.bottom + 4;+ setPlace({ left: clampedLeft, top, maxHeight: room });+ }, [anchor, align, side, width]);++ useLayoutEffect(() => {+ if (!open) { setPlace(null); return; }+ measure();+ // A second pass once the panel has its real height.+ const frame = requestAnimationFrame(measure);+ return () => cancelAnimationFrame(frame);+ }, [open, measure]);++ useEffect(() => {+ if (!open) return;+ const onDown = (event: PointerEvent) => {+ const target = event.target as Node | null;+ if (!target) return;+ if (panel.current?.contains(target) || anchor.current?.contains(target)) return;+ onClose();+ };+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.stopPropagation();+ onClose();+ anchor.current?.focus();+ };+ window.addEventListener("pointerdown", onDown, true);+ window.addEventListener("keydown", onKey, true);+ window.addEventListener("resize", measure);+ return () => {+ window.removeEventListener("pointerdown", onDown, true);+ window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("resize", measure);+ };+ }, [open, onClose, anchor, measure]);++ if (!open) return null;+ return createPortal(+ <div ref={panel} role="dialog" aria-label={label}+ style={{ left: place?.left ?? -9999, top: place?.top ?? -9999, width, maxHeight: place?.maxHeight }}+ className={cn("fixed z-[90] overflow-y-auto rounded-xl border border-border bg-popover p-1 text-sm text-popover-foreground shadow-float scrollbar-jarvis", className)}>+ {children}+ </div>,+ document.body,+ );+}++/** One row of a popover menu: icon, words, an optional quiet hint. */+export function ThreadMenuItem({+ icon,+ label,+ hint,+ onSelect,+ disabled = false,+ danger = false,+ selected = false,+}: {+ icon?: ReactNode;+ label: ReactNode;+ hint?: ReactNode;+ onSelect: () => void;+ disabled?: boolean;+ danger?: boolean;+ selected?: boolean;+}) {+ return <button type="button" role="menuitem" disabled={disabled} onClick={onSelect}+ className={cn(+ "flex min-h-8 w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-45",+ danger ? "text-destructive hover:bg-destructive/10" : "hover:bg-secondary",+ selected && "bg-secondary text-foreground-strong",+ )}>+ {icon && <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground">{icon}</span>}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {hint && <span className="shrink-0 text-xs text-muted-foreground">{hint}</span>}+ </button>;+}++/** A quiet group heading inside a popover. */+export function ThreadMenuHeading({ children }: { children: ReactNode }) {+ return <div className="px-2 pb-1 pt-2 text-xs font-medium text-muted-foreground">{children}</div>;+}++export function ThreadMenuSeparator() {+ return <div role="separator" className="my-1 h-px bg-border" />;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsxnew file mode 100644index 0000000000..2db84b5756--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx@@ -0,0 +1,83 @@+import { useCallback, useRef, type PointerEvent as ReactPointerEvent } from "react";+import { Plus, SquareTerminal, X } from "lucide-react";+import { WorkspaceTerminal } from "@/components/workspace/WorkspaceTerminal";+import { cn } from "@/lib/utils";++/** One shell in the drawer: plain, or started to run a project action. */+export interface DrawerTerminal {+ id: string;+ title: string;+ folder: string;+ /** Typed once when the shell is ready (an action's command plus Enter). */+ input?: string;+}++const MIN_HEIGHT = 140;++/**+ * A terminal drawer under the conversation: shells in the thread's own+ * folder, one tab each. Project actions open here in a tab of their own. The+ * top edge drags to resize; the height is the caller's to keep.+ */+export function ThreadTerminalDrawer({+ terminals,+ active,+ height,+ onSelect,+ onAdd,+ onCloseTab,+ onClose,+ onResize,+}: {+ terminals: DrawerTerminal[];+ active: string;+ height: number;+ onSelect: (id: string) => void;+ onAdd: () => void;+ onCloseTab: (id: string) => void;+ onClose: () => void;+ onResize: (height: number) => void;+}) {+ const drag = useRef<{ startY: number; startHeight: number } | null>(null);+ const onPointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {+ event.preventDefault();+ drag.current = { startY: event.clientY, startHeight: height };+ event.currentTarget.setPointerCapture(event.pointerId);+ }, [height]);+ const onPointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {+ if (!drag.current) return;+ const next = drag.current.startHeight + (drag.current.startY - event.clientY);+ onResize(Math.max(MIN_HEIGHT, Math.min(next, Math.round(window.innerHeight * 0.75))));+ }, [onResize]);+ const onPointerUp = useCallback(() => { drag.current = null; }, []);++ return <section aria-label="Terminal" data-testid="thread-terminal-drawer" style={{ height }}+ className="relative flex shrink-0 flex-col border-t border-border bg-background">+ <div role="separator" aria-orientation="horizontal" aria-label="Resize the terminal"+ onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp}+ className="absolute inset-x-0 -top-1 z-10 h-2 cursor-row-resize" />+ <div className="flex h-9 shrink-0 items-center gap-1 border-b border-border px-2">+ <div role="tablist" aria-label="Terminals" className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-none">+ {terminals.map((terminal) => <div key={terminal.id} role="tab" aria-selected={terminal.id === active}+ className={cn("group/tab flex h-7 shrink-0 items-center gap-1.5 rounded-md pl-2 pr-1 text-xs transition-colors",+ terminal.id === active ? "bg-secondary text-foreground" : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground")}>+ <button type="button" onClick={() => onSelect(terminal.id)} className="flex items-center gap-1.5 focus-visible:outline-none">+ <SquareTerminal aria-hidden className="h-3.5 w-3.5" /><span className="max-w-[160px] truncate">{terminal.title}</span>+ </button>+ <button type="button" aria-label={`Close ${terminal.title}`} onClick={() => onCloseTab(terminal.id)}+ className="rounded p-0.5 opacity-60 hover:bg-background hover:opacity-100"><X className="h-3 w-3" /></button>+ </div>)}+ <button type="button" aria-label="New terminal" title="New terminal" onClick={onAdd}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground"><Plus className="h-3.5 w-3.5" /></button>+ </div>+ <button type="button" aria-label="Hide terminal" onClick={onClose}+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground"><X className="h-4 w-4" /></button>+ </div>+ <div className="relative min-h-0 flex-1">+ {terminals.map((terminal) => <div key={terminal.id} hidden={terminal.id !== active} className="absolute inset-0 p-1">+ <WorkspaceTerminal paneKey={terminal.id} agentName="shell" folder={terminal.folder} initialInput={terminal.input}+ title={terminal.title} bare active={terminal.id === active} />+ </div>)}+ </div>+ </section>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsxnew file mode 100644index 0000000000..f42ca2b31f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx@@ -0,0 +1,408 @@+import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ ArrowDown, Brain, Check, ChevronRight, Copy, Eye, FilePlus2, FileText, FolderOpen, Globe, Image as ImageIcon,+ MessageCircleQuestion, Search, ShieldAlert, SquarePen, SquareTerminal, Wrench, X,+} from "lucide-react";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import type { ReasoningBlock, TextBlock, TimelineItem, ToolBlock, TurnItem, UserItem } from "@/components/agentchat/reduce";+import { toolDiff, type DiffFile } from "@/components/agentchat/toolDiff";+import { buildTimeline, readableOutput, traceDuration, type ActivityEntry, type Call } from "@/components/agentchat/traceEntries";+import { useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";+import { cn } from "@/lib/utils";++/**+ * A thread's conversation: the person's messages on the right, the agent's+ * answer as plain reading text on the left, and the work in between as quiet+ * rows — one line per stretch of tool calls ("Ran 3 commands, read 2 files")+ * that opens to the single calls, and a call that opens to what it ran, the+ * diff it made or what came back. A running turn always ends in a live+ * "Working for 12s" line; a finished one says how long it worked and which+ * files it changed.+ */++const PROSE = cn(+ "prose prose-neutral max-w-none text-base leading-6 text-foreground dark:prose-invert dark:text-foreground [overflow-wrap:anywhere]",+ "[&>div>:first-child]:mt-0 [&>div>:last-child]:mb-0",+ "prose-p:my-2 prose-p:text-foreground prose-li:text-foreground prose-strong:text-foreground-strong",+ "prose-headings:mb-1.5 prose-headings:mt-4 prose-headings:font-semibold prose-headings:tracking-normal prose-headings:text-foreground-strong",+ "prose-h1:text-lg prose-h2:text-base prose-h3:text-base prose-h4:text-base",+ "prose-a:text-foreground-strong prose-a:underline prose-a:decoration-border-strong prose-a:underline-offset-2",+ "prose-code:rounded prose-code:bg-secondary prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",+ "prose-pre:my-2 prose-pre:rounded-lg prose-pre:border prose-pre:border-border prose-pre:bg-card prose-pre:text-sm",+ "prose-li:my-0.5 prose-ul:my-2 prose-ol:my-2 prose-ul:pl-5 prose-ol:pl-5",+ "prose-table:my-3 prose-table:text-sm prose-th:text-foreground-strong prose-td:text-foreground",+);++const KIND_ICONS: Record<Call["kind"], typeof SquareTerminal> = {+ command: SquareTerminal,+ read: Eye,+ list: FolderOpen,+ search: Search,+ edit: SquarePen,+ write: FilePlus2,+ image: ImageIcon,+ web: Globe,+ family: Wrench,+ service: Wrench,+ tool: Wrench,+};++/** One row of the work log: a 24 px line with an icon, words and a trailing note. */+function WorkRow({+ icon,+ label,+ trailing,+ expanded,+ onToggle,+ live = false,+ failed = false,+ children,+}: {+ icon: ReactNode;+ label: ReactNode;+ trailing?: ReactNode;+ expanded?: boolean;+ onToggle?: () => void;+ live?: boolean;+ failed?: boolean;+ children?: ReactNode;+}) {+ const line = <span className="flex min-h-6 min-w-0 items-center gap-2 text-sm">+ <span className={cn("flex h-5 w-5 shrink-0 items-center justify-center", failed ? "text-destructive" : "text-muted-foreground")}>{icon}</span>+ <span className={cn("min-w-0 flex-1 truncate", failed ? "text-destructive" : "text-muted-foreground", live && "thinking-shimmer")}>{label}</span>+ {trailing}+ {onToggle && <ChevronRight aria-hidden className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-0 transition group-hover/row:opacity-100", expanded && "rotate-90 opacity-100")} />}+ </span>;+ return <div className="min-w-0">+ {onToggle+ ? <button type="button" aria-expanded={expanded} onClick={onToggle}+ className="group/row w-full rounded-md px-0.5 py-px text-left hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">{line}</button>+ : <div className="px-0.5 py-px">{line}</div>}+ {expanded && children}+ </div>;+}++function DiffStat({ added, removed }: { added: number; removed: number }) {+ if (!added && !removed) return null;+ return <span className="shrink-0 font-mono text-xs tabular-nums">+ {added > 0 && <span className="text-success">+{added}</span>}+ {added > 0 && removed > 0 && " "}+ {removed > 0 && <span className="text-destructive">−{removed}</span>}+ </span>;+}++function DiffView({ files }: { files: DiffFile[] }) {+ return <div className="space-y-2">+ {files.map((file, index) => <div key={`${file.path}:${index}`} className="overflow-hidden rounded-lg border border-border bg-card">+ {file.path && <div className="flex items-center gap-2 border-b border-border px-3 py-1.5 font-mono text-xs text-muted-foreground">+ <span className="min-w-0 flex-1 truncate">{file.path}</span><DiffStat added={file.added} removed={file.removed} />+ </div>}+ <pre className="m-0 max-h-80 overflow-auto py-1 font-mono text-xs leading-5 scrollbar-jarvis">+ {file.lines.map((line, i) => line.kind === "gap"+ ? <div key={i} className="px-3 text-muted-foreground">⋯</div>+ : <div key={i} className={cn("whitespace-pre px-3", line.kind === "add" && "diff-line-add", line.kind === "del" && "diff-line-del")}>+ <span aria-hidden className="mr-2 select-none opacity-60">{line.kind === "add" ? "+" : line.kind === "del" ? "-" : " "}</span>{line.text}+ </div>)}+ {file.truncated > 0 && <div className="px-3 text-muted-foreground">… {file.truncated} more lines</div>}+ </pre>+ </div>)}+ </div>;+}++function inputText(input: unknown): string {+ if (input == null) return "";+ if (typeof input === "string") return input;+ try { return JSON.stringify(input, null, 2); } catch { return String(input); }+}++/** What a call opened to: the diff it made, else what ran and what came back. */+function CallDetails({ call }: { call: Call }) {+ const block = call.block;+ const diff = useMemo(() => toolDiff(block.name, block.input, block.output), [block.name, block.input, block.output]);+ const output = readableOutput(block).trim();+ if (diff && diff.length > 0 && !block.isError) return <div className="mb-2 ml-7 mt-1"><DiffView files={diff} /></div>;+ const input = call.kind === "command" ? "" : inputText(block.input);+ return <div className="mb-2 ml-7 mt-1 space-y-1.5">+ {call.kind === "command" && <pre className="m-0 overflow-x-auto rounded-lg bg-secondary px-3 py-2 font-mono text-xs leading-5 text-foreground scrollbar-jarvis">$ {inputText((block.input as Record<string, unknown> | null)?.command ?? call.text)}</pre>}+ {input && input !== "{}" && <pre className="m-0 max-h-48 overflow-auto rounded-lg bg-secondary px-3 py-2 font-mono text-xs leading-5 text-muted-foreground scrollbar-jarvis">{input}</pre>}+ {output+ ? <pre className={cn("m-0 max-h-72 overflow-auto whitespace-pre-wrap rounded-lg border border-border px-3 py-2 font-mono text-xs leading-5 scrollbar-jarvis", block.isError ? "text-destructive" : "text-foreground-secondary")}>{output}</pre>+ : block.output === null ? null : <p className="text-xs text-muted-foreground">No output.</p>}+ </div>;+}++function CallRow({ call, nested }: { call: Call; nested: boolean }) {+ const [open, setOpen] = useState(false);+ const Icon = KIND_ICONS[call.kind] ?? Wrench;+ const failed = call.status === "failed" || call.status === "blocked" || call.status === "declined";+ const running = call.status === "running";+ const detail = call.detail || call.result;+ return <WorkRow+ icon={running ? <span className="h-1.5 w-1.5 rounded-full bg-muted-foreground animate-jarvis-pulse" /> : failed ? <X className="h-3.5 w-3.5" /> : <Icon className="h-3.5 w-3.5" />}+ label={<>+ <span className={cn(call.kind === "command" && "font-mono text-xs", !nested && call.kind !== "command" && "text-muted-foreground")}>{call.text}</span>+ {detail && <span className="ml-2 text-faint-foreground">{detail}</span>}+ {failed && call.reason && <span className="ml-2">— {call.reason}</span>}+ {call.status === "interrupted" && <span className="ml-2 text-faint-foreground">interrupted</span>}+ </>}+ trailing={<DiffStat added={call.added} removed={call.removed} />}+ live={running}+ failed={failed}+ expanded={open}+ onToggle={() => setOpen((value) => !value)}>+ <CallDetails call={call} />+ </WorkRow>;+}++function ActivityGroup({ entry, live }: { entry: ActivityEntry; live: boolean }) {+ const [open, setOpen] = useState<boolean | null>(null);+ const failed = entry.calls.some((call) => call.status === "failed" || call.status === "blocked" || call.status === "declined");+ if (entry.calls.length === 1) return <CallRow call={entry.calls[0]} nested={false} />;+ // A stretch the turn is still in stays open; a finished one folds to its line.+ const expanded = open ?? live;+ const added = entry.calls.reduce((sum, call) => sum + call.added, 0);+ const removed = entry.calls.reduce((sum, call) => sum + call.removed, 0);+ const running = entry.calls.some((call) => call.status === "running");+ return <WorkRow+ icon={<Wrench className="h-3.5 w-3.5" />}+ label={entry.summary}+ trailing={<DiffStat added={added} removed={removed} />}+ live={running}+ failed={failed && !expanded}+ expanded={expanded}+ onToggle={() => setOpen(!expanded)}>+ <div className="ml-2.5 border-l border-border pl-3">+ {entry.calls.map((call) => <CallRow key={call.id} call={call} nested />)}+ </div>+ </WorkRow>;+}++function ThoughtRow({ block }: { block: ReasoningBlock }) {+ const [open, setOpen] = useState(false);+ const seconds = block.durationMs ? traceDuration(block.durationMs) : "";+ return <WorkRow icon={<Brain className="h-3.5 w-3.5" />} label={seconds ? `Thought for ${seconds}` : "Thought"}+ expanded={open} onToggle={() => setOpen((value) => !value)}>+ <div className="mb-2 ml-7 mt-1 whitespace-pre-wrap text-sm leading-6 text-muted-foreground">{block.text}</div>+ </WorkRow>;+}++function LiveThinking({ block }: { block: ReasoningBlock }) {+ const tail = block.text.trim().split(/\r?\n/).filter((line) => line.trim()).slice(-3).join("\n");+ return <div>+ <WorkRow icon={<Brain className="h-3.5 w-3.5" />} label="Thinking" live />+ {tail && <div className="ml-7 line-clamp-3 whitespace-pre-wrap text-sm leading-6 text-faint-foreground">{tail}</div>}+ </div>;+}++/** Ticks once a second while a turn runs; the text alone changes, nothing re-lays out. */+function Elapsed({ since }: { since: number }) {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 1000);+ return () => window.clearInterval(timer);+ }, []);+ return <span className="tabular-nums">{traceDuration(Math.max(0, now - since))}</span>;+}++function CopyButton({ text, label }: { text: string; label: string }) {+ const [done, setDone] = useState(false);+ return <button type="button" aria-label={label} title={label}+ onClick={() => { void robustCopy(text).then(() => { setDone(true); window.setTimeout(() => setDone(false), 1200); }); }}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {done ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ </button>;+}++function clock(ms: number): string {+ return new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });+}++function UserBubble({ item }: { item: UserItem }) {+ return <div className="group flex flex-col items-end gap-1" data-testid="thread-user-message">+ <div className="jarvis-user-bubble max-w-[80%] rounded-2xl px-4 py-2.5">+ {item.attachments.length > 0 && <div className="mb-2 flex flex-wrap justify-end gap-2">+ {item.attachments.map((file) => file.url && file.kind === "image"+ ? <img key={file.name} src={file.url} alt={file.name} className="h-24 max-w-[200px] rounded-lg border border-border object-cover" />+ : <span key={file.name} className="inline-flex max-w-[240px] items-center gap-1.5 rounded-md border border-border bg-background/60 px-2 py-1 text-xs text-muted-foreground">+ <FileText aria-hidden className="h-3.5 w-3.5 shrink-0" /><span className="truncate">{file.name}</span>+ </span>)}+ </div>}+ {item.text && <div className="whitespace-pre-wrap text-base leading-6 [overflow-wrap:anywhere]">{item.text}</div>}+ </div>+ <div className="flex items-center gap-1 pr-1 text-xs text-muted-foreground opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100">+ <span className="tabular-nums">{clock(item.tsMs)}</span>+ {item.text && <CopyButton text={item.text} label="Copy message" />}+ </div>+ </div>;+}++/** Every file the turn's edits touched, with the size of the change. */+function changedFiles(turn: TurnItem): { path: string; added: number; removed: number; files: DiffFile[] }[] {+ const byPath = new Map<string, { path: string; added: number; removed: number; files: DiffFile[] }>();+ for (const block of turn.blocks) {+ if (block.kind !== "tool" || block.isError || block.output === null) continue;+ for (const file of toolDiff(block.name, block.input, block.output) ?? []) {+ if (!file.path) continue;+ const row = byPath.get(file.path) ?? { path: file.path, added: 0, removed: 0, files: [] };+ row.added += file.added;+ row.removed += file.removed;+ row.files.push(file);+ byPath.set(file.path, row);+ }+ }+ return [...byPath.values()];+}++function shortFile(path: string): string {+ const parts = path.replace(/\\/g, "/").split("/").filter(Boolean);+ return parts.length > 3 ? `…/${parts.slice(-3).join("/")}` : path;+}++function ChangedFiles({ turn }: { turn: TurnItem }) {+ const rows = useMemo(() => changedFiles(turn), [turn]);+ const [openPath, setOpenPath] = useState<string | null>(null);+ if (rows.length === 0) return null;+ const added = rows.reduce((sum, row) => sum + row.added, 0);+ const removed = rows.reduce((sum, row) => sum + row.removed, 0);+ return <section aria-label="Changed files" className="mt-3 overflow-hidden rounded-xl border border-border">+ <div className="flex items-center gap-2 border-b border-border bg-card px-3 py-2 text-sm">+ <span className="font-medium text-foreground">Changed {rows.length} {rows.length === 1 ? "file" : "files"}</span>+ <DiffStat added={added} removed={removed} />+ </div>+ <ul>+ {rows.map((row) => <li key={row.path} className="border-b border-border last:border-b-0">+ <button type="button" aria-expanded={openPath === row.path} onClick={() => setOpenPath(openPath === row.path ? null : row.path)}+ className="flex w-full items-center gap-2 px-3 py-1.5 text-left font-mono text-xs hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" title={row.path}>+ <ChevronRight aria-hidden className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", openPath === row.path && "rotate-90")} />+ <span className="min-w-0 flex-1 truncate text-foreground">{shortFile(row.path)}</span>+ <DiffStat added={row.added} removed={row.removed} />+ </button>+ {openPath === row.path && <div className="px-3 pb-3"><DiffView files={row.files.map((file) => ({ ...file, path: "" }))} /></div>}+ </li>)}+ </ul>+ </section>;+}++function answerText(turn: TurnItem): string {+ return turn.blocks.filter((block): block is TextBlock => block.kind === "text").map((block) => block.text.trim()).filter(Boolean).join("\n\n");+}++function pendingLabel(block: ToolBlock): { icon: ReactNode; text: string } | null {+ if (block.question && !block.question.closed) return { icon: <MessageCircleQuestion className="h-3.5 w-3.5" />, text: "Waiting for your answer below" };+ if (block.approval && block.approval.decision === null) {+ return { icon: <ShieldAlert className="h-3.5 w-3.5" />, text: `Waiting for approval — ${block.approval.summary || block.name}` };+ }+ return null;+}++const TurnView = memo(function TurnView({ turn }: { turn: TurnItem }) {+ const t = useT();+ const lang = t("trace_report.locale");+ const running = turn.status === "running";+ const timeline = useMemo(() => buildTimeline(turn.blocks, { t, lang, status: turn.status, live: true }), [turn.blocks, t, lang, turn.status]);+ const lastActivity = [...timeline.entries].reverse().find((entry) => entry.kind === "activity")?.id;+ const answer = answerText(turn);+ return <div className="space-y-1.5" data-testid="thread-turn" data-status={turn.status}>+ {timeline.entries.map((entry) => {+ if (entry.kind === "activity") return <ActivityGroup key={entry.id} entry={entry} live={running && entry.id === lastActivity} />;+ if (entry.kind === "prose") {+ if (entry.tone === "reasoning") return <ThoughtRow key={entry.id} block={entry.block as ReasoningBlock} />;+ return <div key={entry.id} className={PROSE}><ChatMarkdown text={entry.text} /></div>;+ }+ const block = entry.block;+ if (block.kind === "text") return <div key={entry.id} className={PROSE}><ChatMarkdown text={block.text} /></div>;+ if (block.kind === "reasoning") {+ return block.live && running ? <LiveThinking key={entry.id} block={block} /> : block.text.trim() ? <ThoughtRow key={entry.id} block={block} /> : null;+ }+ const pending = pendingLabel(block);+ return pending ? <WorkRow key={entry.id} icon={pending.icon} label={pending.text} live /> : null;+ })}+ {running+ ? <WorkRow icon={<span className="h-1.5 w-1.5 rounded-full bg-accent animate-jarvis-pulse" />} label={<>Working for <Elapsed since={turn.startedMs} /></>} live />+ : <>+ {turn.status === "error" && turn.error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{turn.error}</p>}+ <ChangedFiles turn={turn} />+ <div className="flex items-center gap-1.5 pt-1 text-xs text-muted-foreground">+ <span>+ {turn.status === "cancelled" ? "Stopped" : turn.status === "error" ? "Failed" : answer ? "" : "Finished without an answer"}+ {turn.durationMs != null && <>{turn.status === "done" && answer ? "Worked for " : " after "}{traceDuration(turn.durationMs)}</>}+ </span>+ {answer && <CopyButton text={answer} label="Copy answer" />}+ </div>+ </>}+ </div>;+});++function ErrorLine({ text }: { text: string }) {+ return <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{text}</p>;+}++/** One item of the conversation, drawn by its kind. */+function ItemView({ item }: { item: TimelineItem }) {+ if (item.type === "user") return <UserBubble item={item} />;+ if (item.type === "turn") return <TurnView turn={item} />;+ if (item.type === "error") return <ErrorLine text={item.text} />;+ if (item.type === "notice") {+ return <p className="text-center text-xs text-muted-foreground">{item.agentName ? `${item.agentName}: ` : ""}{item.text}</p>;+ }+ return <div className="rounded-xl border border-border px-3 py-2 text-sm">+ <p className="mb-1 text-xs text-muted-foreground">Message from {item.message.sender_name}</p>+ <div className={PROSE}><ChatMarkdown text={item.message.text} /></div>+ </div>;+}++/**+ * The scrolling column. It follows the newest line while the reader is at+ * the bottom and stays put once they scroll up to read; a button brings them+ * back down.+ */+export function ThreadTimeline({ items, sessionId, bottomInset }: { items: TimelineItem[]; sessionId: string | null; bottomInset: number }) {+ const scroller = useRef<HTMLDivElement | null>(null);+ const pinned = useRef(true);+ const [away, setAway] = useState(false);++ // A newly opened thread starts at its newest message.+ useLayoutEffect(() => {+ pinned.current = true;+ setAway(false);+ const box = scroller.current;+ if (box) box.scrollTop = box.scrollHeight;+ }, [sessionId]);++ useLayoutEffect(() => {+ const box = scroller.current;+ if (box && pinned.current) box.scrollTop = box.scrollHeight;+ });++ useEffect(() => {+ const box = scroller.current;+ if (!box || typeof ResizeObserver === "undefined") return;+ // Content that grows without a re-render (an image loading) keeps the pin too.+ const observer = new ResizeObserver(() => { if (pinned.current) box.scrollTop = box.scrollHeight; });+ const content = box.firstElementChild;+ if (content) observer.observe(content);+ return () => observer.disconnect();+ }, []);++ return <div className="relative min-h-0 flex-1">+ <div ref={scroller} data-testid="thread-timeline"+ onScroll={(event) => {+ const box = event.currentTarget;+ const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 48;+ pinned.current = atBottom;+ setAway(!atBottom);+ }}+ className="h-full overflow-y-auto scrollbar-jarvis">+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-5 pt-6" style={{ paddingBottom: bottomInset + 24 }}>+ {items.map((item) => <ItemView key={item.id} item={item} />)}+ </div>+ </div>+ {away && <button type="button" aria-label="Scroll to the newest message"+ onClick={() => { const box = scroller.current; if (box) box.scrollTo({ top: box.scrollHeight, behavior: "smooth" }); }}+ style={{ bottom: bottomInset + 12 }}+ className="absolute left-1/2 z-10 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-float hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ArrowDown className="h-4 w-4" />+ </button>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsxnew file mode 100644index 0000000000..0d3c166602--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx@@ -0,0 +1,274 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { Check, Folder, FolderOpen, Loader2, Mic, MoreHorizontal, Pencil, Plus, SquarePen, Trash2, X } from "lucide-react";+import { AgentMark } from "@/components/agentic/AgentMark";+import { patchAgentChatSession, type AgentChatSession } from "@/lib/agentChatApi";+import type { IdeProject } from "@/lib/agenticIdeApi";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { useIdeThreadsStore } from "@/store/ideThreads";+import { IdeLayoutSwitch } from "./IdeLayoutSwitch";+import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "./ThreadPopover";+import { shortAge, threadStatus, threadTitle, threadsByProject, useThreadChatStore, type ThreadStatus } from "./threadModel";++const EXPANSION_KEY = "jarvis.ide.threadExpansion.v1";+/** Threads a project shows before "Show more". */+const FOLDED_COUNT = 6;+/** How often the list asks for fresh session rows while it is on screen. */+const POLL_MS = 4000;++function readExpansion(): Record<string, boolean> {+ try {+ const value: unknown = JSON.parse(localStorage.getItem(EXPANSION_KEY) ?? "{}");+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ return Object.fromEntries(Object.entries(value).filter(([, open]) => typeof open === "boolean")) as Record<string, boolean>;+ } catch { return {}; /* an optional preference: the defaults stay usable */ }+}++function saveExpansion(value: Record<string, boolean>): void {+ try { localStorage.setItem(EXPANSION_KEY, JSON.stringify(value)); }+ catch { /* storage blocked — the choice holds for this session only */ }+}++/** The quiet mark at a row's end: what the thread is doing, else whose it is. */+function StatusMark({ status }: { status: ThreadStatus }) {+ if (status === "approval") {+ return <span role="img" aria-label="Waiting for your approval" title="Waiting for your approval"+ className="h-2 w-2 shrink-0 rounded-full bg-warning" />;+ }+ if (status === "running") {+ return <Loader2 role="img" aria-label="Working" className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />;+ }+ if (status === "unseen") {+ return <span role="img" aria-label="New activity" title="New activity" className="h-2 w-2 shrink-0 rounded-full bg-accent" />;+ }+ return null;+}++/**+ * The sidebar while the IDE shows threads: every project with its threads,+ * each named by the title its coding CLI gave the conversation and marked+ * with that CLI's logo. A project row opens and folds; its "+" starts a new+ * thread in it.+ */+export function ThreadTree() {+ const projects = useIdeProjectsStore((state) => state.projects);+ const connectProject = useIdeProjectsStore((state) => state.connectProject);+ const toggleVoice = useIdeProjectsStore((state) => state.toggleVoice);+ const pushToast = useEventStore((state) => state.pushToast);+ const sessions = useThreadChatStore((state) => state.sessions);+ const catalog = useThreadChatStore((state) => state.catalog);+ const activeSessionId = useThreadChatStore((state) => state.activeSessionId);+ const selection = useIdeThreadsStore((state) => state.selection);+ const projectOf = useIdeThreadsStore((state) => state.projectOf);+ const seen = useIdeThreadsStore((state) => state.seen);+ const openThread = useIdeThreadsStore((state) => state.openThread);+ const newThread = useIdeThreadsStore((state) => state.newThread);+ const forgetThread = useIdeThreadsStore((state) => state.forgetThread);+ const [expansion, setExpansion] = useState(readExpansion);+ const [showAll, setShowAll] = useState<Record<string, boolean>>({});+ const [renaming, setRenaming] = useState<{ sessionId: string; title: string } | null>(null);+ const [menu, setMenu] = useState<{ sessionId: string; projectId: string } | null>(null);+ const [confirmDelete, setConfirmDelete] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const menuAnchor = useRef<HTMLElement | null>(null);++ useEffect(() => {+ const store = useThreadChatStore.getState();+ if (!store.catalog || store.catalogStale) void store.loadCatalog();+ void store.loadSessions();+ const timer = window.setInterval(() => { void useThreadChatStore.getState().loadSessions(); }, POLL_MS);+ return () => window.clearInterval(timer);+ }, []);++ const visible = useMemo(() => projects.filter((project) => !project.archived && !project.scratch), [projects]);+ const grouped = useMemo(() => threadsByProject(sessions, visible, projectOf), [sessions, visible, projectOf]);+ const agentOf = useMemo(() => {+ const map = new Map<string, { agent: string; label: string }>();+ for (const provider of catalog?.providers ?? []) {+ if (provider.agent) map.set(provider.id, { agent: provider.agent, label: provider.label });+ }+ return map;+ }, [catalog]);+ const openSessionId = selection.sessionId ?? activeSessionId;++ const setProjectOpen = (id: string, open: boolean) => setExpansion((previous) => {+ const next = { ...previous, [id]: open };+ saveExpansion(next);+ return next;+ });++ const rename = async (session: AgentChatSession, title: string) => {+ const clean = title.trim();+ setRenaming(null);+ if (!clean || clean === threadTitle(session)) return;+ setBusy(session.session_id);+ try {+ await patchAgentChatSession(session.session_id, { title: clean });+ await useThreadChatStore.getState().loadSessions();+ } catch (error) {+ pushToast("error", error instanceof Error ? error.message : String(error));+ } finally {+ setBusy(null);+ }+ };++ const remove = async (sessionId: string) => {+ setConfirmDelete(null);+ setBusy(sessionId);+ try {+ await useThreadChatStore.getState().removeSession(sessionId);+ forgetThread(sessionId);+ } finally {+ setBusy(null);+ }+ };++ const projectRow = (project: IdeProject) => {+ const threads = grouped.get(project.id) ?? [];+ const draftHere = selection.sessionId === null && selection.projectId === project.id;+ const open = expansion[project.id] ?? (threads.length > 0 || draftHere);+ const shown = showAll[project.id] ? threads : threads.slice(0, FOLDED_COUNT);+ const running = threads.filter((thread) => thread.running).length;+ return <div key={project.id} className="mb-px" data-testid={`thread-project-${project.id}`}>+ <div className="group relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted">+ <button type="button" aria-expanded={open} aria-label={`${open ? "Collapse" : "Expand"} ${project.name}`}+ onClick={() => setProjectOpen(project.id, !open)} title={project.path}+ className="flex min-h-8 min-w-0 flex-1 items-center gap-2.5 rounded-md px-2 text-left text-[15px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {open+ ? <FolderOpen aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" strokeWidth={1.75} />+ : <Folder aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" strokeWidth={1.75} />}+ <span className="min-w-0 flex-1 truncate">{project.name}</span>+ {!open && running > 0 && <Loader2 aria-label={`${running} working`} className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground group-hover:opacity-0" />}+ </button>+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-md bg-gradient-to-l from-muted from-60% to-transparent pl-5 pr-1 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">+ <button type="button" aria-label={`New thread in ${project.name}`} title="New thread"+ data-testid={`thread-new-${project.id}`}+ onClick={() => { setProjectOpen(project.id, true); newThread(project.id); }}+ className="rounded p-1 text-muted-foreground hover:bg-background/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <SquarePen className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>+ {open && <div className="mb-1 flex flex-col gap-px">+ {draftHere && <div aria-current="page"+ className="flex min-h-8 items-center gap-2 rounded-md bg-muted px-2 pl-8 text-[15px] text-muted-foreground">+ <span className="min-w-0 flex-1 truncate">New thread</span>+ </div>}+ {shown.map((session) => {+ const selected = session.session_id === openSessionId && selection.sessionId !== null;+ const status = threadStatus(session, seen, openSessionId);+ const mark = agentOf.get(session.provider);+ const menuOpen = menu?.sessionId === session.session_id;+ if (renaming?.sessionId === session.session_id) {+ return <form key={session.session_id} className="flex min-h-8 items-center gap-1 pl-6 pr-1"+ onSubmit={(event) => { event.preventDefault(); void rename(session, renaming.title); }}>+ <input autoFocus aria-label={`Rename ${threadTitle(session)}`} value={renaming.title} maxLength={120}+ onChange={(event) => setRenaming({ sessionId: session.session_id, title: event.target.value })}+ onKeyDown={(event) => { if (event.key === "Escape") { event.stopPropagation(); setRenaming(null); } }}+ onBlur={() => void rename(session, renaming.title)}+ className="min-w-0 flex-1 rounded border border-input bg-background px-2 py-1 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring" />+ <button type="submit" aria-label="Save name" className="rounded p-1 text-muted-foreground hover:text-foreground"><Check className="h-4 w-4" /></button>+ <button type="button" aria-label="Cancel renaming" onMouseDown={(event) => event.preventDefault()} onClick={() => setRenaming(null)}+ className="rounded p-1 text-muted-foreground hover:text-foreground"><X className="h-4 w-4" /></button>+ </form>;+ }+ return <div key={session.session_id} data-testid={`thread-row-${session.session_id}`}+ className={cn("group/thread relative flex min-h-8 items-center rounded-md transition-colors hover:bg-muted", (selected || menuOpen) && "bg-muted")}+ onContextMenu={(event) => {+ event.preventDefault();+ menuAnchor.current = event.currentTarget;+ setMenu({ sessionId: session.session_id, projectId: project.id });+ }}>+ <button type="button" aria-current={selected ? "page" : undefined}+ onClick={() => openThread(session.session_id, project.id)}+ onDoubleClick={() => setRenaming({ sessionId: session.session_id, title: threadTitle(session) })}+ title={threadTitle(session)}+ className={cn(+ "flex min-h-8 min-w-0 flex-1 items-center gap-2 rounded-md py-1 pl-8 pr-2 text-left text-[15px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "text-foreground-strong" : "text-foreground",+ )}>+ <span className="min-w-0 flex-1 truncate">{threadTitle(session)}</span>+ {busy === session.session_id+ ? <Loader2 aria-hidden className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />+ : <StatusMark status={status} />}+ <span className="flex shrink-0 items-center transition-opacity group-hover/thread:opacity-0 [@media(hover:none)]:opacity-0">+ {mark+ ? <AgentMark agent={mark.agent} label={mark.label} variant="plain" size="sm" />+ : <span className="text-xs tabular-nums text-muted-foreground">{shortAge(session.updated_ms)}</span>}+ </span>+ </button>+ <div className={cn(+ "absolute inset-y-0 right-0 flex items-center gap-1 rounded-r-md bg-gradient-to-l from-muted from-60% to-transparent pl-5 pr-1 transition-opacity",+ menuOpen ? "opacity-100" : "pointer-events-none opacity-0 group-hover/thread:pointer-events-auto group-hover/thread:opacity-100 group-focus-within/thread:pointer-events-auto group-focus-within/thread:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",+ )}>+ <span className="text-xs tabular-nums text-muted-foreground" title={new Date(session.updated_ms).toLocaleString()}>{shortAge(session.updated_ms)}</span>+ <button type="button" aria-label={`Thread actions for ${threadTitle(session)}`} aria-haspopup="menu" aria-expanded={menuOpen}+ onClick={(event) => {+ menuAnchor.current = event.currentTarget;+ setMenu(menuOpen ? null : { sessionId: session.session_id, projectId: project.id });+ }}+ className="rounded p-1 text-muted-foreground hover:bg-background/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <MoreHorizontal className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>;+ })}+ {threads.length > FOLDED_COUNT && <button type="button"+ onClick={() => setShowAll((current) => ({ ...current, [project.id]: !current[project.id] }))}+ className="flex min-h-7 items-center rounded-md pl-8 text-left text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {showAll[project.id] ? "Show less" : `Show ${threads.length - FOLDED_COUNT} more`}+ </button>}+ {threads.length === 0 && !draftHere && <button type="button" onClick={() => newThread(project.id)}+ className="flex min-h-7 items-center gap-2 rounded-md pl-8 text-left text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Plus aria-hidden className="h-3.5 w-3.5" />Start a thread+ </button>}+ </div>}+ </div>;+ };++ const menuSession = menu ? sessions.find((session) => session.session_id === menu.sessionId) ?? null : null;++ return <div data-testid="ide-thread-tree" className="flex-1 px-2 pb-3 pt-2">+ <div className="flex h-8 items-center justify-between gap-2 pl-2 pr-1 text-[15px] font-semibold text-foreground">+ <span>Threads</span>+ <div className="flex items-center gap-1">+ <IdeLayoutSwitch />+ <button type="button" aria-label="Jarvis Live" title="Jarvis Live" onClick={toggleVoice}+ className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Mic className="h-3.5 w-3.5" /></button>+ <button type="button" aria-label="Connect project" title="Connect project folder" onClick={connectProject}+ className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><Plus className="h-3.5 w-3.5" /></button>+ </div>+ </div>+ {visible.some((project) => project.pinned) && <>+ <div className="px-2 pb-1 pt-3 text-[13px] font-medium text-muted-foreground/80">Pinned</div>+ {visible.filter((project) => project.pinned).map(projectRow)}+ {visible.some((project) => !project.pinned) && <div className="px-2 pb-1 pt-4 text-[13px] font-medium text-muted-foreground/80">Other projects</div>}+ </>}+ {visible.filter((project) => !project.pinned).map(projectRow)}+ {visible.length === 0 && <p className="px-2 py-2 text-[13px] text-muted-foreground">Connect a folder to start a project.</p>}++ <ThreadPopover anchor={menuAnchor} open={menu !== null && menuSession !== null} onClose={() => { setMenu(null); setConfirmDelete(null); }}+ label="Thread actions" width={220}>+ {menu && menuSession && (confirmDelete === menu.sessionId+ ? <div className="p-2">+ <p className="text-sm text-foreground">Delete this thread?</p>+ <p className="mt-1 text-xs text-muted-foreground">Its conversation leaves the list. The coding agent's own history stays on disk.</p>+ <div className="mt-3 flex justify-end gap-2">+ <button type="button" onClick={() => setConfirmDelete(null)} className="rounded-md px-2.5 py-1 text-sm text-muted-foreground hover:bg-secondary">Cancel</button>+ <button type="button" onClick={() => { const id = menu.sessionId; setMenu(null); void remove(id); }}+ className="rounded-md bg-destructive px-2.5 py-1 text-sm text-destructive-foreground">Delete</button>+ </div>+ </div>+ : <div role="menu">+ <ThreadMenuItem icon={<Pencil className="h-3.5 w-3.5" />} label="Rename"+ onSelect={() => { setRenaming({ sessionId: menuSession.session_id, title: threadTitle(menuSession) }); setMenu(null); }} />+ <ThreadMenuItem icon={<SquarePen className="h-3.5 w-3.5" />} label="New thread in this project"+ onSelect={() => { newThread(menu.projectId); setMenu(null); }} />+ <ThreadMenuSeparator />+ <ThreadMenuItem icon={<Trash2 className="h-3.5 w-3.5" />} label="Delete" danger disabled={Boolean(menuSession.running)}+ onSelect={() => setConfirmDelete(menu.sessionId)} />+ </div>)}+ </ThreadPopover>+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsxnew file mode 100644index 0000000000..cd27740e6f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx@@ -0,0 +1,138 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AgentChatCatalog, AgentChatSession } from "@/lib/agentChatApi";+import type { IdeProject } from "@/lib/agenticIdeApi";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { useIdeThreadsStore } from "@/store/ideThreads";++const api = vi.hoisted(() => ({+ fetchAgentChatCatalog: vi.fn(),+ fetchAgentConnections: vi.fn(),+ fetchProviderHealth: vi.fn(),+ fetchAgentChatSessions: vi.fn(),+ createAgentChatSession: vi.fn(),+ sendAgentChatMessage: vi.fn(),+ patchAgentChatSession: vi.fn(),+}));+vi.mock("@/lib/agentChatApi", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/agentChatApi")>()), ...api }));+vi.mock("@/lib/gitApi", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/gitApi")>()),+ inspectGit: vi.fn().mockResolvedValue({ is_repo: false, branches: [], changes: [], remotes: [] }),+ prepareGit: vi.fn(),+}));+vi.mock("@/lib/chatLibraryApi", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/chatLibraryApi")>()),+ fetchProjectLaunchers: vi.fn().mockResolvedValue({ file_manager: true, editors: [{ id: "code", label: "VS Code" }], remote_url: null, remote_label: null }),+}));++import { ThreadView } from "./ThreadView";+import { ThreadTree } from "./ThreadTree";+import { useThreadChatStore } from "./threadModel";++class FakeSocket {+ static instances: FakeSocket[] = [];+ onopen: (() => void) | null = null;+ onmessage: ((msg: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ constructor(readonly url: string) { FakeSocket.instances.push(this); }+ close() { /* the test drives frames by hand */ }+}++const CATALOG: AgentChatCatalog = {+ default_cwd: "/home",+ shell: "bash",+ selection: null,+ providers: [{+ id: "claude-api", label: "Anthropic Claude", family: "anthropic", runner: "claude-cli", agent: "claude",+ models_source: "curated", curated_models: [{ id: "claude-opus-5-5", label: "Opus 5.5" }], default_model: "",+ keyless: false, native_resume: true, effort_levels: ["low", "high"], default_effort: "high",+ permission_modes: [{ id: "default", label: "Ask first", description: "" }], default_permission_mode: "default",+ cli_installed: true, typeahead: [],+ }],+} as AgentChatCatalog;++const project = { id: "p1", path: "/repo", name: "App", color: null, pinned: false, archived: false, scratch: false,+ created_at: 0, last_opened_at: 0, exists: true, chats: 0, workspaces: [] } as IdeProject;++function sessionRow(extra: Partial<AgentChatSession> = {}): AgentChatSession {+ return { session_id: "s1", title: "fix the login test", provider: "claude-api", model: "", effort: "high", cwd: "/repo",+ permission_mode: "default", surface: "agent", vendor_session: null, created_ms: 1, updated_ms: 2, message_count: 1, preview: "", ...extra };+}++beforeEach(() => {+ localStorage.clear();+ vi.stubGlobal("WebSocket", FakeSocket);+ FakeSocket.instances = [];+ api.fetchAgentChatCatalog.mockReset().mockResolvedValue(CATALOG);+ api.fetchAgentConnections.mockReset().mockResolvedValue([]);+ api.fetchProviderHealth.mockReset().mockResolvedValue([]);+ api.fetchAgentChatSessions.mockReset().mockResolvedValue([]);+ api.createAgentChatSession.mockReset().mockResolvedValue(sessionRow());+ api.sendAgentChatMessage.mockReset().mockResolvedValue({ turn_id: "t1" });+ api.patchAgentChatSession.mockReset().mockResolvedValue(sessionRow());+ useIdeProjectsStore.setState({ projects: [project], activeWorkspaceId: null });+ useIdeThreadsStore.setState({ layout: "threads", selection: { projectId: "p1", sessionId: null }, projectOf: {}, seen: {}, focusNonce: 0 });+ useThreadChatStore.getState().newChat();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("ThreadView", () => {+ it("starts a new thread in the project's folder with its first message", async () => {+ render(<ThreadView onScreen />);+ expect(screen.getByText(/What should we build in/)).toBeTruthy();+ expect(screen.getByTestId("thread-project-picker").textContent).toContain("App");+ await waitFor(() => expect(useThreadChatStore.getState().draft.provider).toBe("claude-api"));+ await waitFor(() => expect(useThreadChatStore.getState().draft.cwd).toBe("/repo"));++ const box = screen.getByTestId("thread-composer-input");+ fireEvent.change(box, { target: { value: "fix the login test" } });+ await act(async () => { fireEvent.keyDown(box, { key: "Enter" }); });++ await waitFor(() => expect(api.sendAgentChatMessage).toHaveBeenCalled());+ expect(api.createAgentChatSession).toHaveBeenCalledWith(expect.objectContaining({ provider: "claude-api", cwd: "/repo", surface: "agent" }));+ expect(api.sendAgentChatMessage.mock.calls[0][1]).toBe("fix the login test");+ await waitFor(() => expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" }));+ expect(useIdeThreadsStore.getState().projectOf).toEqual({ s1: "p1" });+ });++ it("draws the turn: the message, the work as one line, the answer and how long it took", async () => {+ useIdeThreadsStore.setState({ selection: { projectId: "p1", sessionId: "s1" } });+ api.fetchAgentChatSessions.mockResolvedValue([sessionRow()]);+ render(<ThreadView onScreen />);+ const store = useThreadChatStore.getState();+ act(() => {+ store.ingest({ seq: 1, ts_ms: 1000, kind: "user_message", payload: { text: "fix the login test" } });+ store.ingest({ seq: 2, ts_ms: 1000, kind: "turn_started", payload: { turn_id: "t1", provider: "claude-api", model: "", effort: "high", runner: "claude-cli" } });+ store.ingest({ seq: 3, ts_ms: 1100, kind: "tool_call", payload: { turn_id: "t1", call_id: "c1", name: "Bash", input: { command: "npm test" } } });+ store.ingest({ seq: 4, ts_ms: 1200, kind: "tool_result", payload: { turn_id: "t1", call_id: "c1", output: "ok", is_error: false, duration_ms: 100 } });+ store.ingest({ seq: 5, ts_ms: 1300, kind: "tool_call", payload: { turn_id: "t1", call_id: "c2", name: "Read", input: { file_path: "/repo/src/login.ts" } } });+ store.ingest({ seq: 6, ts_ms: 1400, kind: "tool_result", payload: { turn_id: "t1", call_id: "c2", output: "code", is_error: false, duration_ms: 50 } });+ store.ingest({ seq: 7, ts_ms: 1500, kind: "assistant_text", payload: { turn_id: "t1", message_id: "m1", text: "The test passes now." } });+ store.ingest({ seq: 8, ts_ms: 4000, kind: "turn_finished", payload: { turn_id: "t1", status: "done", duration_ms: 3000, usage: null, error: null } });+ });+ expect(screen.getByTestId("thread-user-message").textContent).toContain("fix the login test");+ expect(screen.getByText("The test passes now.")).toBeTruthy();+ expect(screen.getByTestId("thread-turn").getAttribute("data-status")).toBe("done");+ expect(screen.getByText(/Worked for/)).toBeTruthy();+ // Two calls fold to one line until opened.+ expect(screen.queryByText("npm test")).toBeNull();+ });+});++describe("ThreadTree", () => {+ it("lists a project's threads by the CLI's own title with the agent's mark", async () => {+ api.fetchAgentChatSessions.mockResolvedValue([sessionRow({ cli_title: "Fix login test" }), sessionRow({ session_id: "s2", cwd: "/elsewhere", title: "stray" })]);+ render(<ThreadTree />);+ await waitFor(() => expect(screen.getByText("Fix login test")).toBeTruthy());+ expect(screen.queryByText("stray")).toBeNull();+ fireEvent.click(screen.getByText("Fix login test"));+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" });+ fireEvent.click(screen.getByTestId("thread-new-p1"));+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsxnew file mode 100644index 0000000000..4eb5d1371c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx@@ -0,0 +1,237 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Check, ChevronDown, FolderPlus } from "lucide-react";+import { prepareGit } from "@/lib/gitApi";+import { useEventStore } from "@/store/events";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { useIdeThreadsStore } from "@/store/ideThreads";+import { ThreadBranchBar, type ThreadCheckout } from "./ThreadBranchBar";+import { ThreadComposer } from "./ThreadComposer";+import { ThreadDiffPanel } from "./ThreadDiffPanel";+import { ThreadHeader } from "./ThreadHeader";+import { ThreadMenuItem, ThreadPopover } from "./ThreadPopover";+import { ThreadTerminalDrawer, type DrawerTerminal } from "./ThreadTerminalDrawer";+import { ThreadTimeline } from "./ThreadTimeline";+import { actionInput, type ProjectAction } from "./projectActions";+import { projectIdFor, threadTitle, useThreadChatStore } from "./threadModel";++const DRAWER_HEIGHT_KEY = "jarvis.ide.threadDrawerHeight.v1";+const DIFF_OPEN_KEY = "jarvis.ide.threadDiffOpen.v1";++function storedNumber(key: string, fallback: number): number {+ try {+ const value = Number(localStorage.getItem(key));+ return Number.isFinite(value) && value > 0 ? value : fallback;+ } catch { return fallback; }+}++function storedFlag(key: string): boolean {+ try { return localStorage.getItem(key) === "1"; } catch { return false; }+}++function storeValue(key: string, value: string): void {+ try { localStorage.setItem(key, value); } catch { /* a convenience only */ }+}++let terminalSerial = 0;++/**+ * The IDE's thread layout: one conversation with a coding agent at a time.+ *+ * A thread is the agent's own CLI session driven through its binary, so its+ * tools, skills, MCP servers, permissions and login are the CLI's. The view+ * opens the thread picked in the sidebar, or a draft in a project whose first+ * message starts the thread — in the project's checkout or a fresh worktree.+ */+export function ThreadView({ onScreen }: { onScreen: boolean }) {+ const pushToast = useEventStore((state) => state.pushToast);+ const projects = useIdeProjectsStore((state) => state.projects);+ const activeWorkspaceId = useIdeProjectsStore((state) => state.activeWorkspaceId);+ const connectProject = useIdeProjectsStore((state) => state.connectProject);+ const selection = useIdeThreadsStore((state) => state.selection);+ const projectOf = useIdeThreadsStore((state) => state.projectOf);+ const focusNonce = useIdeThreadsStore((state) => state.focusNonce);+ const sessions = useThreadChatStore((state) => state.sessions);+ const activeSessionId = useThreadChatStore((state) => state.activeSessionId);+ const activeSession = useThreadChatStore((state) => state.activeSession);+ const timeline = useThreadChatStore((state) => state.timeline);+ const draft = useThreadChatStore((state) => state.draft);+ const lastError = useThreadChatStore((state) => state.lastError);+ const [checkout, setCheckout] = useState<ThreadCheckout>("current");+ const [base, setBase] = useState("");+ const [projectMenu, setProjectMenu] = useState(false);+ const [terminals, setTerminals] = useState<DrawerTerminal[]>([]);+ const [activeTerminal, setActiveTerminal] = useState("");+ const [drawerOpen, setDrawerOpen] = useState(false);+ const [drawerHeight, setDrawerHeight] = useState(() => storedNumber(DRAWER_HEIGHT_KEY, 280));+ const [diffOpen, setDiffOpen] = useState(() => storedFlag(DIFF_OPEN_KEY));+ const [composerHeight, setComposerHeight] = useState(160);+ const composerBox = useRef<HTMLDivElement | null>(null);+ const projectAnchor = useRef<HTMLButtonElement | null>(null);+ // The draft whose first message is on its way: its session belongs to this project.+ const startingIn = useRef<string | null>(null);++ const visible = useMemo(() => projects.filter((project) => !project.archived && !project.scratch), [projects]);+ const session = selection.sessionId+ ? (activeSession?.session_id === selection.sessionId ? activeSession : sessions.find((row) => row.session_id === selection.sessionId) ?? null)+ : null;+ const fallbackProject = visible.find((project) => project.workspaces.some((workspace) => workspace.id === activeWorkspaceId)) ?? visible[0] ?? null;+ const project = visible.find((entry) => entry.id === selection.projectId)+ ?? (session ? visible.find((entry) => entry.id === projectIdFor(session, visible, projectOf)) : undefined)+ ?? fallbackProject;+ const folder = session?.cwd || project?.path || "";+ const isDraft = selection.sessionId === null;++ // Open the picked thread, or a blank draft in the picked project.+ useEffect(() => {+ const store = useThreadChatStore.getState();+ if (selection.sessionId) {+ if (store.activeSessionId !== selection.sessionId) store.openSession(selection.sessionId);+ return;+ }+ if (startingIn.current) return; // the draft is becoming a session right now+ store.newChat();+ setCheckout("current");+ setBase("");+ }, [selection.sessionId]);++ // A draft runs in its project's folder.+ useEffect(() => {+ if (!isDraft || !project || activeSessionId || startingIn.current) return;+ if (useThreadChatStore.getState().draft.cwd !== project.path) void useThreadChatStore.getState().setDraft({ cwd: project.path });+ }, [isDraft, project, activeSessionId, draft.cwd]);++ // The first message created the session: it is this project's thread now.+ useEffect(() => {+ if (!activeSessionId || !isDraft || !startingIn.current) return;+ const projectId = startingIn.current;+ startingIn.current = null;+ useIdeThreadsStore.getState().adoptThread(activeSessionId, projectId);+ }, [activeSessionId, isDraft]);++ // Keep the open thread marked as read.+ useEffect(() => {+ const row = sessions.find((entry) => entry.session_id === selection.sessionId);+ if (row && onScreen) useIdeThreadsStore.getState().markSeen(row.session_id, row.updated_ms);+ }, [sessions, selection.sessionId, onScreen]);++ // How tall the composer is, so the conversation scrolls clear of it.+ useEffect(() => {+ const box = composerBox.current;+ if (!box || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => setComposerHeight(box.offsetHeight));+ observer.observe(box);+ return () => observer.disconnect();+ }, []);++ const prepareDraft = useCallback(async (): Promise<string | null> => {+ if (!project) {+ pushToast("error", "Connect a project folder first.");+ return null;+ }+ startingIn.current = project.id;+ if (checkout !== "worktree") return project.path;+ try {+ const prepared = await prepareGit(project.path, { mode: "new_worktree", branch: "", base });+ if (prepared.message) pushToast("success", prepared.message);+ return prepared.folder;+ } catch (error) {+ startingIn.current = null;+ throw error;+ }+ }, [project, checkout, base, pushToast]);++ // A failed first send leaves the draft a draft.+ useEffect(() => {+ if (isDraft && !activeSessionId && lastError) startingIn.current = null;+ }, [isDraft, activeSessionId, lastError]);++ const finishedTurns = useMemo(() => timeline.items.filter((item) => item.type === "turn" && item.status !== "running").length, [timeline.items]);+ const running = timeline.items.some((item) => item.type === "turn" && item.status === "running");++ const addTerminal = useCallback((title: string, input?: string) => {+ if (!folder) return;+ const id = `thread-term-${Date.now().toString(36)}-${++terminalSerial}`;+ setTerminals((current) => [...current, { id, title, folder, ...(input ? { input } : {}) }]);+ setActiveTerminal(id);+ setDrawerOpen(true);+ }, [folder]);++ const toggleTerminal = () => {+ if (drawerOpen) { setDrawerOpen(false); return; }+ if (terminals.length === 0) addTerminal("Terminal");+ else setDrawerOpen(true);+ };++ const runAction = (action: ProjectAction) => addTerminal(action.name, actionInput(action.command));++ const closeTerminal = (id: string) => {+ setTerminals((current) => {+ const next = current.filter((terminal) => terminal.id !== id);+ if (id === activeTerminal) setActiveTerminal(next[next.length - 1]?.id ?? "");+ if (next.length === 0) setDrawerOpen(false);+ return next;+ });+ };++ if (!project) {+ return <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center" data-testid="thread-view-empty">+ <FolderPlus className="h-8 w-8 text-muted-foreground/70" />+ <h1 className="text-lg font-medium">Connect a project</h1>+ <p className="max-w-md text-sm text-muted-foreground">Threads run a coding agent in a project folder. Connect one to start.</p>+ <button type="button" onClick={connectProject} className="mt-2 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-secondary">Connect folder</button>+ </div>;+ }++ const title = isDraft ? "New thread" : threadTitle(session);+ const threadKey = selection.sessionId ?? `draft:${project.id}`;+ const empty = isDraft && timeline.items.length === 0;++ return <div className="flex h-full min-h-0" data-testid="thread-view">+ <div className="flex min-w-0 flex-1 flex-col">+ <ThreadHeader projectId={project.id} projectName={project.name} folder={folder} title={title}+ sessionId={selection.sessionId} terminalOpen={drawerOpen} onToggleTerminal={toggleTerminal}+ diffOpen={diffOpen} onToggleDiff={() => { const next = !diffOpen; setDiffOpen(next); storeValue(DIFF_OPEN_KEY, next ? "1" : "0"); }}+ gitVersion={finishedTurns} onRunAction={runAction} />+ <div className="relative flex min-h-0 flex-1 flex-col">+ {empty+ ? <div className="flex min-h-0 flex-1 flex-col items-center justify-center px-5 pb-6">+ <h2 className="text-center text-2xl font-normal tracking-tight text-foreground">+ What should we build in{" "}+ <button ref={projectAnchor} type="button" aria-haspopup="menu" aria-expanded={projectMenu} onClick={() => setProjectMenu(!projectMenu)}+ className="inline-flex items-center gap-1 rounded-md font-semibold text-foreground-strong hover:bg-secondary/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ data-testid="thread-project-picker">+ {project.name}<ChevronDown aria-hidden className="h-4 w-4 text-muted-foreground" />+ </button>?+ </h2>+ <ThreadPopover anchor={projectAnchor} open={projectMenu} onClose={() => setProjectMenu(false)} label="Projects" width={260}>+ <div role="menu">+ {visible.map((entry) => <ThreadMenuItem key={entry.id} label={entry.name} selected={entry.id === project.id}+ hint={entry.id === project.id ? <Check className="h-3.5 w-3.5" /> : undefined}+ onSelect={() => { setProjectMenu(false); useIdeThreadsStore.getState().newThread(entry.id); }} />)}+ <ThreadMenuItem icon={<FolderPlus className="h-3.5 w-3.5" />} label="Connect another folder" onSelect={() => { setProjectMenu(false); connectProject(); }} />+ </div>+ </ThreadPopover>+ <div className="mt-6 w-full">+ <ThreadComposer threadKey={threadKey} prepareDraft={prepareDraft} autoFocusNonce={focusNonce + (onScreen ? 1 : 0)} />+ <ThreadBranchBar folder={folder} draft checkout={checkout} onCheckout={setCheckout} base={base} onBase={setBase} locked={false} />+ </div>+ </div>+ : <>+ <ThreadTimeline items={timeline.items} sessionId={selection.sessionId} bottomInset={composerHeight} />+ <div ref={composerBox} className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-background from-70% to-transparent px-5 pb-3 pt-6">+ <div className="pointer-events-auto">+ <ThreadComposer threadKey={threadKey} prepareDraft={prepareDraft} autoFocusNonce={focusNonce} />+ <ThreadBranchBar folder={folder} draft={isDraft} checkout={checkout} onCheckout={setCheckout} base={base} onBase={setBase} locked={running} />+ </div>+ </div>+ </>}+ </div>+ {drawerOpen && terminals.length > 0 && <ThreadTerminalDrawer terminals={terminals} active={activeTerminal} height={drawerHeight}+ onSelect={setActiveTerminal} onAdd={() => addTerminal("Terminal")} onCloseTab={closeTerminal} onClose={() => setDrawerOpen(false)}+ onResize={(next) => { setDrawerHeight(next); storeValue(DRAWER_HEIGHT_KEY, String(next)); }} />}+ </div>+ {diffOpen && <div className="w-[min(480px,40%)] shrink-0">+ <ThreadDiffPanel folder={folder} version={finishedTurns} onClose={() => { setDiffOpen(false); storeValue(DIFF_OPEN_KEY, "0"); }} />+ </div>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/projectActions.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/projectActions.tsnew file mode 100644index 0000000000..6ec3d943b1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/projectActions.ts@@ -0,0 +1,63 @@+/**+ * A project's actions: named shell commands ("Dev server" → `npm run dev`)+ * the thread header runs in the terminal drawer with one click.+ *+ * Kept per project in this browser's storage — a convenience a person sets up+ * once; storage that is blocked or cleared leaves the header with its plain+ * "Add action" button and nothing breaks.+ */++export interface ProjectAction {+ id: string;+ name: string;+ command: string;+}++const KEY = "jarvis.ide.projectActions.v1";++function readAll(): Record<string, ProjectAction[]> {+ try {+ const raw: unknown = JSON.parse(localStorage.getItem(KEY) ?? "{}");+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};+ const out: Record<string, ProjectAction[]> = {};+ for (const [project, list] of Object.entries(raw)) {+ if (!Array.isArray(list)) continue;+ out[project] = list.filter((row): row is ProjectAction =>+ Boolean(row) && typeof row.id === "string" && typeof row.name === "string" && typeof row.command === "string");+ }+ return out;+ } catch {+ return {};+ }+}++function writeAll(all: Record<string, ProjectAction[]>): void {+ try { localStorage.setItem(KEY, JSON.stringify(all)); }+ catch { /* storage blocked: the actions last for this session only */ }+}++export function readProjectActions(projectId: string): ProjectAction[] {+ return readAll()[projectId] ?? [];+}++/** Add or replace (same id) one action; returns the project's new list. */+export function saveProjectAction(projectId: string, action: ProjectAction): ProjectAction[] {+ const all = readAll();+ const list = all[projectId] ?? [];+ const at = list.findIndex((row) => row.id === action.id);+ const next = at >= 0 ? list.map((row, i) => (i === at ? action : row)) : [...list, action];+ writeAll({ ...all, [projectId]: next });+ return next;+}++export function deleteProjectAction(projectId: string, actionId: string): ProjectAction[] {+ const all = readAll();+ const next = (all[projectId] ?? []).filter((row) => row.id !== actionId);+ writeAll({ ...all, [projectId]: next });+ return next;+}++/** What the shell is sent to run `command`: the line plus Enter. */+export function actionInput(command: string): string {+ return `${command.replace(/\r?\n/g, " ").trim()}\r`;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.tsnew file mode 100644index 0000000000..c111b44e45--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vitest";+import type { AgentChatSession } from "@/lib/agentChatApi";+import type { IdeProject } from "@/lib/agenticIdeApi";+import { comparablePath, isInside, projectIdFor, shortAge, threadStatus, threadTitle, threadsByProject } from "./threadModel";++function project(id: string, path: string): IdeProject {+ return {+ id, path, name: id, color: null, pinned: false, archived: false, created_at: 0, last_opened_at: 0,+ exists: true, chats: 0, scratch: false, workspaces: [],+ } as IdeProject;+}++function session(id: string, cwd: string, extra: Partial<AgentChatSession> = {}): AgentChatSession {+ return {+ session_id: id, title: `title ${id}`, provider: "claude-api", model: "", effort: "", cwd, permission_mode: "",+ vendor_session: null, created_ms: 0, updated_ms: 0, message_count: 1, preview: "", ...extra,+ };+}++describe("thread paths", () => {+ it("compares Windows paths without case or separator drift", () => {+ expect(comparablePath("C:\\Users\\Me\\Repo\\")).toBe("c:/users/me/repo");+ expect(isInside("c:/users/me/repo/sub", "C:\\Users\\Me\\Repo")).toBe(true);+ });++ it("keeps POSIX paths case-sensitive and never matches a sibling prefix", () => {+ expect(isInside("/home/me/Repo", "/home/me/repo")).toBe(false);+ expect(isInside("/home/me/repo-two", "/home/me/repo")).toBe(false);+ expect(isInside("/home/me/repo", "/home/me/repo/")).toBe(true);+ });+});++describe("projectIdFor", () => {+ const projects = [project("outer", "/code"), project("inner", "/code/app")];++ it("picks the deepest project that holds the thread's folder", () => {+ expect(projectIdFor(session("a", "/code/app/src"), projects, {})).toBe("inner");+ expect(projectIdFor(session("b", "/code/lib"), projects, {})).toBe("outer");+ expect(projectIdFor(session("c", "/elsewhere"), projects, {})).toBeNull();+ });++ it("prefers the project a thread was started in (a worktree lives outside it)", () => {+ expect(projectIdFor(session("w", "/worktrees/app-fix"), projects, { w: "inner" })).toBe("inner");+ // A remembered project that is gone falls back to the folder.+ expect(projectIdFor(session("x", "/code/lib"), projects, { x: "deleted" })).toBe("outer");+ });++ it("groups threads per project, newest first", () => {+ const grouped = threadsByProject([+ session("old", "/code/app", { updated_ms: 1 }),+ session("new", "/code/app", { updated_ms: 5 }),+ session("stray", "/tmp"),+ ], projects, {});+ expect(grouped.get("inner")?.map((row) => row.session_id)).toEqual(["new", "old"]);+ expect([...grouped.keys()]).toEqual(["inner"]);+ });+});++describe("threadStatus", () => {+ it("puts a waiting approval before work and work before news", () => {+ const base = session("s", "/code", { updated_ms: 10 });+ expect(threadStatus({ ...base, running: true, pending_approvals: ["a"] }, {}, null)).toBe("approval");+ expect(threadStatus({ ...base, running: true }, {}, null)).toBe("running");+ expect(threadStatus(base, { s: 5 }, null)).toBe("unseen");+ expect(threadStatus(base, { s: 5 }, "s")).toBe("idle");+ // Never looked at in this browser: not news.+ expect(threadStatus(base, {}, null)).toBe("idle");+ });+});++describe("threadTitle", () => {+ it("uses the CLI's own title first, then the stored one", () => {+ expect(threadTitle({ title: "fix the login test please", cli_title: "Fix login test" })).toBe("Fix login test");+ expect(threadTitle({ title: "fix the login test please" })).toBe("fix the login test please");+ expect(threadTitle({ title: " " })).toBe("New thread");+ expect(threadTitle(null)).toBe("New thread");+ });+});++describe("shortAge", () => {+ it("says how long ago in a list's shorthand", () => {+ const now = 1_000_000_000;+ expect(shortAge(now - 10_000, now)).toBe("now");+ expect(shortAge(now - 5 * 60_000, now)).toBe("5m");+ expect(shortAge(now - 3 * 3_600_000, now)).toBe("3h");+ expect(shortAge(now - 2 * 86_400_000, now)).toBe("2d");+ expect(shortAge(now - 15 * 86_400_000, now)).toBe("2w");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.tsnew file mode 100644index 0000000000..435a6d7b15--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/threadModel.ts@@ -0,0 +1,116 @@+import type { AgentChatSession } from "@/lib/agentChatApi";+import type { IdeProject } from "@/lib/agenticIdeApi";+import { createAgentChatStore, type ProviderOption } from "@/store/agentChat";++/**+ * The pure half of the IDE's thread layout: which project a thread belongs+ * to, what it is called, and what state its row shows.+ *+ * A thread is one agent-chat session on the IDE's own surface (`agent`): a+ * coding CLI driven through its own binary, so its tools, skills, MCP servers+ * and login are the CLI's, and the conversation is the CLI's own session.+ */++/** The IDE threads' chat store — one socket, one draft, one session list. */+export const useThreadChatStore = createAgentChatStore("agent", "threads");++/** How a row in the thread list reads at a glance. */+export type ThreadStatus = "approval" | "running" | "unseen" | "idle";++/** What a thread is called in the list and its header. */+export function threadTitle(session: Pick<AgentChatSession, "title" | "cli_title"> | null | undefined): string {+ return session?.cli_title?.trim() || session?.title?.trim() || "New thread";+}++/** A path in one comparable spelling: forward slashes, no trailing slash, case folded on drive paths. */+export function comparablePath(path: string): string {+ let text = path.trim().replace(/\\/g, "/");+ while (text.length > 1 && text.endsWith("/") && !/^[A-Za-z]:\/$/.test(text)) text = text.slice(0, -1);+ // Windows paths are case-insensitive; POSIX paths are not and stay as written.+ return /^[A-Za-z]:\//.test(text) || text.startsWith("//") ? text.toLowerCase() : text;+}++/** True when `child` is `parent` or lies inside it. */+export function isInside(child: string, parent: string): boolean {+ const a = comparablePath(child);+ const b = comparablePath(parent);+ if (!a || !b) return false;+ return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`);+}++/**+ * The project a thread belongs to: the one it was started in when that is+ * remembered, else the deepest project folder holding the thread's folder.+ */+export function projectIdFor(+ session: Pick<AgentChatSession, "session_id" | "cwd">,+ projects: readonly IdeProject[],+ projectOf: Readonly<Record<string, string>>,+): string | null {+ const remembered = projectOf[session.session_id];+ if (remembered && projects.some((project) => project.id === remembered)) return remembered;+ let best: IdeProject | null = null;+ for (const project of projects) {+ if (!project.path || !isInside(session.cwd, project.path)) continue;+ if (!best || comparablePath(project.path).length > comparablePath(best.path).length) best = project;+ }+ return best?.id ?? null;+}++/** Every project's threads, newest first. Threads outside every project are left out. */+export function threadsByProject(+ sessions: readonly AgentChatSession[],+ projects: readonly IdeProject[],+ projectOf: Readonly<Record<string, string>>,+): Map<string, AgentChatSession[]> {+ const out = new Map<string, AgentChatSession[]>();+ for (const session of sessions) {+ const projectId = projectIdFor(session, projects, projectOf);+ if (!projectId) continue;+ const list = out.get(projectId);+ if (list) list.push(session);+ else out.set(projectId, [session]);+ }+ for (const list of out.values()) list.sort((a, b) => b.updated_ms - a.updated_ms);+ return out;+}++/** The row's state: a waiting approval first, then work, then news since the last look. */+export function threadStatus(+ session: Pick<AgentChatSession, "session_id" | "running" | "pending_approvals" | "updated_ms">,+ seen: Readonly<Record<string, number>>,+ openSessionId: string | null,+): ThreadStatus {+ if (session.pending_approvals && session.pending_approvals.length > 0) return "approval";+ if (session.running) return "running";+ if (session.session_id !== openSessionId && session.updated_ms > (seen[session.session_id] ?? Number.POSITIVE_INFINITY)) {+ return "unseen";+ }+ return "idle";+}++/** The CLIs a thread can run on: the catalog's coding-agent rows, installed ones first. */+export function threadAgents(options: readonly ProviderOption[]): ProviderOption[] {+ return options+ .filter((option) => Boolean(option.agent))+ .sort((a, b) => Number(b.connected) - Number(a.connected));+}++/** "now", "5m", "3h", "2d", "4w" — how long ago, the way a dense list says it. */+export function shortAge(ms: number, now = Date.now()): string {+ const seconds = Math.max(0, Math.round((now - ms) / 1000));+ if (seconds < 60) return "now";+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h`;+ const days = Math.floor(hours / 24);+ if (days < 7) return `${days}d`;+ return `${Math.floor(days / 7)}w`;+}++/** The last folder name of a path — what a branch-less checkout is called. */+export function folderLabel(path: string): string {+ const parts = path.split(/[\\/]/).filter(Boolean);+ return parts[parts.length - 1] ?? path;+}diff --git a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsxindex d6821d1590..bdd02d578a 100644--- a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx@@ -7,6 +7,7 @@* Conventions copied from PtyTerminal: xterm instance in a ref (never state, or* it rerenders per chunk), dispose() on unmount (WebGL context cap).*/+import { cn } from "@/lib/utils";import { useCallback, useEffect, useRef, useState } from "react";import { Terminal } from "@xterm/xterm";import { FitAddon } from "@xterm/addon-fit";@@ -44,6 +45,18 @@ interface WorkspaceTerminalProps {installName?: string;/** Plain terminals are pinned to the workspace chosen when the tab opens. */workspaceId?: string;+ /**+ * Or to a folder of their own — a thread's terminal drawer, whose folder may+ * be a worktree no workspace has open. Ignored when `workspaceId` is set.+ */+ folder?: string;+ /**+ * Typed into the shell once, the first time it is ready — a project action+ * ("npm run dev") opened in a fresh terminal. End it with "\r" to run it.+ */+ initialInput?: string;+ /** No header or frame: the host draws its own tabs around the terminal. */+ bare?: boolean;active?: boolean;appearance?: TerminalAppearance;/**@@ -75,6 +88,9 @@ export function WorkspaceTerminal({title,banner,workspaceId,+ folder,+ initialInput,+ bare = false,active = true,appearance: requestedAppearance,}: WorkspaceTerminalProps) {@@ -97,6 +113,9 @@ export function WorkspaceTerminal({// PTY down and restart the installer whenever the string changed identity.const bannerRef = useRef(banner);bannerRef.current = banner;+ // Same reason: the input is sent once at `ready`, never a reason to respawn.+ const initialInputRef = useRef(initialInput);+ initialInputRef.current = initialInput;useEffect(() => {const container = containerRef.current;@@ -175,6 +194,7 @@ export function WorkspaceTerminal({if (agentName) params.agent = agentName;else if (installName) params.install = installName;if (workspaceId) params.workspace_id = workspaceId;+ else if (folder) params.folder = folder;ws = new WebSocket(buildUrl(paneKey, params));ws.onopen = () => {@@ -197,9 +217,14 @@ export function WorkspaceTerminal({}if (msg.t === "o") term.write(msg.d ?? "");else if (msg.t === "ready") {+ const firstReady = !everLive;everLive = true;setStatus("live");if (activeRef.current) term.focus();+ const input = initialInputRef.current;+ if (firstReady && input && ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ t: "i", d: input }));+ }} else if (msg.t === "exit") {setStatus("exited");term.write(`\r\n\x1b[33m[process exited: ${msg.code ?? "?"}]\x1b[0m\r\n`);@@ -255,7 +280,7 @@ export function WorkspaceTerminal({term.dispose();termRef.current = null;};- }, [paneKey, agentName, installName, workspaceId]);+ }, [paneKey, agentName, installName, workspaceId, folder]);useEffect(() => {if (!active) return;@@ -293,10 +318,10 @@ export function WorkspaceTerminal({return (<div{...dragHandlers}- className="relative flex h-full w-full flex-col overflow-hidden rounded-lg border border-border"+ className={cn("relative flex h-full w-full flex-col overflow-hidden", !bare && "rounded-lg border border-border")}style={{ background: PANE_CHROME[appearance].shell }}>- <header className="flex items-center justify-between gap-2 border-b border-border bg-card/40 px-3 py-1.5">+ {!bare && <header className="flex items-center justify-between gap-2 border-b border-border bg-card/40 px-3 py-1.5"><div className="flex items-center gap-2 text-xs text-muted-foreground"><TerminalIcon className="h-3.5 w-3.5 text-primary" /><span className="font-mono">{title}</span>@@ -315,7 +340,7 @@ export function WorkspaceTerminal({<span className="text-muted-foreground">connecting…</span>)}</span>- </header>+ </header>}<div ref={containerRef} className="flex-1 overflow-hidden p-1" />{dragging && carrying === "skill" && <SkillDropCard skill={skillInFlight} target={title}blocked={Boolean(skillInFlight?.multiline) && !termRef.current?.modes.bracketedPasteMode} />}diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex 582e7d68eb..f9a7153b36 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -149,6 +149,12 @@ export interface AgentChatSession {preview: string;running?: boolean;pending_approvals?: string[];+ /**+ * The name the coding CLI gave this conversation itself (Claude Code's+ * session title, Codex's thread name) — set on the IDE's own sessions while+ * the stored title is still the first message's; absent otherwise.+ */+ cli_title?: string;}export const INTERNAL_DELIVERY_STATUSES = ["queued", "delivered", "failed"] as const;diff --git a/jarvis/ui/web/frontend/src/lib/gitApi.ts b/jarvis/ui/web/frontend/src/lib/gitApi.tsindex 35b3634824..c0902df891 100644--- a/jarvis/ui/web/frontend/src/lib/gitApi.ts+++ b/jarvis/ui/web/frontend/src/lib/gitApi.ts@@ -132,6 +132,47 @@ export async function inspectGit(folder: string, signal?: AbortSignal): Promise<return (await res.json()) as GitRepoInfo;}+/** A changed path under a folder, relative to it (`GET /changes`). */+export interface FolderChange {+ path: string;+ status: "modified" | "added" | "deleted" | "untracked" | "conflicted";+ added: number | null;+ removed: number | null;+ is_directory: boolean;+}++export interface FolderChanges {+ available: boolean;+ branch: string;+ files: FolderChange[];+ truncated: boolean;+ reason: string;+}++export interface FolderDiff {+ path: string;+ status: string;+ binary: boolean;+ added: number;+ removed: number;+ hunks: { header: string; lines: { kind: "add" | "del" | "ctx"; text: string; old_no: number | null; new_no: number | null }[] }[];+ truncated: boolean;+}++/** What changed under a folder that no workspace has open — a thread's checkout. */+export async function fetchFolderChanges(folder: string, signal?: AbortSignal): Promise<FolderChanges> {+ const res = await fetch(`${BASE}/changes?folder=${encodeURIComponent(folder)}`, { signal });+ if (!res.ok) throw await failure(res);+ return (await res.json()) as FolderChanges;+}++/** How one file under `folder` differs from the last commit. */+export async function fetchFolderDiff(folder: string, path: string, signal?: AbortSignal): Promise<FolderDiff> {+ const res = await fetch(`${BASE}/diff?folder=${encodeURIComponent(folder)}&path=${encodeURIComponent(path)}`, { signal });+ if (!res.ok) throw await failure(res);+ return (await res.json()) as FolderDiff;+}+export function prepareGit(folder: string, plan: GitPlan): Promise<GitPrepared> {return post<GitPrepared>("/prepare", { folder, mode: plan.mode, branch: plan.branch, base: plan.base });}diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.test.ts b/jarvis/ui/web/frontend/src/store/ideThreads.test.tsnew file mode 100644index 0000000000..348ee0e0ce--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/ideThreads.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it } from "vitest";+import { useIdeThreadsStore } from "./ideThreads";++describe("ideThreads store", () => {+ beforeEach(() => {+ localStorage.clear();+ useIdeThreadsStore.setState({ layout: "grid", selection: { projectId: "", sessionId: null }, projectOf: {}, seen: {}, focusNonce: 0 });+ });++ it("remembers the layout across a reload", () => {+ useIdeThreadsStore.getState().setLayout("threads");+ expect(useIdeThreadsStore.getState().layout).toBe("threads");+ expect(localStorage.getItem("jarvis.agenticIde.layout.v1")).toBe('"threads"');+ });++ it("opens a draft, then adopts the session its first message created", () => {+ const store = useIdeThreadsStore.getState();+ store.newThread("p1");+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null });+ expect(useIdeThreadsStore.getState().focusNonce).toBe(1);+ store.adoptThread("s1", "p1");+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" });+ expect(useIdeThreadsStore.getState().projectOf).toEqual({ s1: "p1" });+ });++ it("marks a thread seen only forward in time", () => {+ const store = useIdeThreadsStore.getState();+ store.markSeen("s1", 10);+ store.markSeen("s1", 5);+ expect(useIdeThreadsStore.getState().seen.s1).toBe(10);+ });++ it("forgets a deleted thread and leaves its project open on a draft", () => {+ const store = useIdeThreadsStore.getState();+ store.adoptThread("s1", "p1");+ store.markSeen("s1", 3);+ store.forgetThread("s1");+ const state = useIdeThreadsStore.getState();+ expect(state.projectOf).toEqual({});+ expect(state.seen).toEqual({});+ expect(state.selection).toEqual({ projectId: "p1", sessionId: null });+ });+});diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.ts b/jarvis/ui/web/frontend/src/store/ideThreads.tsnew file mode 100644index 0000000000..b057eab134--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/ideThreads.ts@@ -0,0 +1,153 @@+import { create } from "zustand";++/**+ * How the Agentic IDE is laid out, and which thread the thread layout shows.+ *+ * `grid` is the terminal wall: workspaces of panes. `threads` is one+ * conversation at a time — a coding agent (Claude Code, Codex, …) driven+ * through its own CLI, read as a chat. The app sidebar, the IDE view and the+ * thread view all read this; none of them can reach the others by props.+ *+ * The open thread is either an existing chat session (`sessionId`) or a draft+ * in one project (`sessionId: null`) whose first message creates the session.+ * Both survive a reload through localStorage, which may be blocked — every+ * read and write degrades to the defaults instead of throwing.+ */++export type IdeLayout = "grid" | "threads";++export const IDE_LAYOUTS: readonly IdeLayout[] = ["grid", "threads"];++export interface ThreadSelection {+ /** The project the thread belongs to; "" while no project is known yet. */+ projectId: string;+ /** The chat session on screen, or null for a new thread's draft. */+ sessionId: string | null;+}++const LAYOUT_KEY = "jarvis.agenticIde.layout.v1";+const SELECTION_KEY = "jarvis.agenticIde.threadSelection.v1";+const PROJECT_OF_KEY = "jarvis.agenticIde.threadProjects.v1";+const SEEN_KEY = "jarvis.agenticIde.threadSeen.v1";+/** Bounds on the two maps kept in storage — oldest entries go first. */+const MAX_REMEMBERED = 400;++function read<T>(key: string, parse: (raw: unknown) => T | null, fallback: T): T {+ try {+ const raw = localStorage.getItem(key);+ if (raw === null) return fallback;+ return parse(JSON.parse(raw)) ?? fallback;+ } catch {+ return fallback;+ }+}++function write(key: string, value: unknown): void {+ try {+ localStorage.setItem(key, JSON.stringify(value));+ } catch {+ /* a convenience only: the choice just does not survive this session */+ }+}++const parseLayout = (raw: unknown): IdeLayout | null =>+ typeof raw === "string" && (IDE_LAYOUTS as readonly string[]).includes(raw) ? (raw as IdeLayout) : null;++const parseSelection = (raw: unknown): ThreadSelection | null => {+ if (!raw || typeof raw !== "object") return null;+ const row = raw as Record<string, unknown>;+ const projectId = typeof row.projectId === "string" ? row.projectId : "";+ const sessionId = typeof row.sessionId === "string" && row.sessionId ? row.sessionId : null;+ return { projectId, sessionId };+};++const parseStringMap = (raw: unknown): Record<string, string> | null => {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;+ return Object.fromEntries(Object.entries(raw).filter(([, value]) => typeof value === "string")) as Record<string, string>;+};++const parseNumberMap = (raw: unknown): Record<string, number> | null => {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;+ return Object.fromEntries(Object.entries(raw).filter(([, value]) => typeof value === "number")) as Record<string, number>;+};++/** Drop the oldest keys once a map outgrows `MAX_REMEMBERED` (insertion order). */+function bounded<T>(map: Record<string, T>): Record<string, T> {+ const keys = Object.keys(map);+ if (keys.length <= MAX_REMEMBERED) return map;+ return Object.fromEntries(keys.slice(keys.length - MAX_REMEMBERED).map((key) => [key, map[key]]));+}++interface IdeThreadsState {+ layout: IdeLayout;+ selection: ThreadSelection;+ /**+ * Which project a thread was started in. A thread in a fresh worktree runs+ * in a folder outside the project's own, so its folder alone cannot say.+ */+ projectOf: Record<string, string>;+ /** When each thread was last looked at (its `updated_ms` then) — drives the "new" dot. */+ seen: Record<string, number>;+ /** Bumped to ask the thread view to focus its composer. */+ focusNonce: number;++ setLayout: (layout: IdeLayout) => void;+ /** Open an existing thread. */+ openThread: (sessionId: string, projectId: string) => void;+ /** Open an empty draft in a project; its first message starts the thread. */+ newThread: (projectId: string) => void;+ /** The draft became a session: remember where it belongs and show it. */+ adoptThread: (sessionId: string, projectId: string) => void;+ markSeen: (sessionId: string, updatedMs: number) => void;+ /** A thread was deleted: forget everything kept about it. */+ forgetThread: (sessionId: string) => void;+}++export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({+ layout: read(LAYOUT_KEY, parseLayout, "grid"),+ selection: read(SELECTION_KEY, parseSelection, { projectId: "", sessionId: null }),+ projectOf: read(PROJECT_OF_KEY, parseStringMap, {}),+ seen: read(SEEN_KEY, parseNumberMap, {}),+ focusNonce: 0,++ setLayout: (layout) => {+ if (get().layout === layout) return;+ write(LAYOUT_KEY, layout);+ set({ layout });+ },+ openThread: (sessionId, projectId) => {+ const selection = { projectId, sessionId };+ write(SELECTION_KEY, selection);+ set({ selection });+ },+ newThread: (projectId) => {+ const selection = { projectId, sessionId: null };+ write(SELECTION_KEY, selection);+ set((state) => ({ selection, focusNonce: state.focusNonce + 1 }));+ },+ adoptThread: (sessionId, projectId) => {+ const selection = { projectId, sessionId };+ const projectOf = projectId ? bounded({ ...get().projectOf, [sessionId]: projectId }) : get().projectOf;+ write(SELECTION_KEY, selection);+ write(PROJECT_OF_KEY, projectOf);+ set({ selection, projectOf });+ },+ markSeen: (sessionId, updatedMs) => {+ if ((get().seen[sessionId] ?? 0) >= updatedMs) return;+ const { [sessionId]: _previous, ...rest } = get().seen;+ const seen = bounded({ ...rest, [sessionId]: updatedMs });+ write(SEEN_KEY, seen);+ set({ seen });+ },+ forgetThread: (sessionId) => {+ const { [sessionId]: _project, ...projectOf } = get().projectOf;+ const { [sessionId]: _seen, ...seen } = get().seen;+ write(PROJECT_OF_KEY, projectOf);+ write(SEEN_KEY, seen);+ const selection = get().selection.sessionId === sessionId+ ? { projectId: get().selection.projectId, sessionId: null }+ : get().selection;+ write(SELECTION_KEY, selection);+ set({ projectOf, seen, selection });+ },+}));diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex db10c458a8..f9480c86a1 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -24,6 +24,8 @@ import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";import { useIdeProjectsStore } from "@/store/ideProjects";import { useIdeSkillsStore } from "@/store/ideSkills";+import { useIdeThreadsStore } from "@/store/ideThreads";+import { ThreadView } from "@/components/agentic/threads/ThreadView";import { openProject } from "@/lib/chatLibraryApi";import {activateWorkspace, addTerminal, closeTerminal, closeWorkspace, fetchIdeAgents, fetchIdeProjects, fetchIdeState, renameWorkspace,@@ -74,6 +76,9 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const setWorkspaces = useIdeChatStore((state) => state.setWorkspaces);const paneRequest = useIdeChatStore((state) => state.paneRequest);const setStagedPane = useIdeChatStore((state) => state.setStagedPane);+ // Grid of terminals, or one thread at a time (see store/ideThreads).+ const layout = useIdeThreadsStore((state) => state.layout);+ const threads = layout === "threads";const [state, setState] = useState<IdeState | null>(null);const [projects, setProjects] = useState<IdeProject[]>([]);const [agents, setAgents] = useState<AgentStatus[]>([]);@@ -308,6 +313,8 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {setProjects(listing.projects);publishProjects(listing.projects, listing.active_workspace_id);const found = listing.projects.find((entry) => entry.id === project.id);+ // In the thread layout a new project starts a thread, not a workspace.+ if (found && useIdeThreadsStore.getState().layout === "threads") { useIdeThreadsStore.getState().newThread(found.id); setProjectDialog(false); return; }if (found) { setWorkspaceProject(found); setWorkspaceAgents([installed[0]?.name ?? ""]); setWorkspaceGit(KEEP_CHECKOUT); setWorkspaceComputer(storedRunOn(found.id)); }setProjectDialog(false);};@@ -459,7 +466,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {// Ctrl+B, then a key (see components/agentic/ideHotkeys): the IDE's// key menu. Pane commands go to the grid that owns the pane; the rest are// the same calls the buttons and the sidebar make.- const hotkeysEnabled = onScreen && !dialogOpen && !optionsOpen && !gitOpen && !closeRequest;+ const hotkeysEnabled = onScreen && !threads && !dialogOpen && !optionsOpen && !gitOpen && !closeRequest;const hotkeyAgents = installed.map((agent) => ({ name: agent.name, label: agent.display_name }));const sendPaneCommand = (command: PaneCommand) => {if (!session || !selected) return;@@ -549,7 +556,11 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {<main className="min-h-0 flex-1"><IdeSidePanelFrame markInUse={paneStyle === "minimal"} appearance={appearance ?? undefined} onScreen={onScreen}>- {session ? <RetainedWorkspaceGrid session={session} onScreen={onScreen} workspaceIds={state.workspaces?.map((workspace) => workspace.id)} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}+ {threads && <ThreadView onScreen={onScreen} />}+ {/* The grid stays mounted behind the threads: its terminals keep running+ and come back exactly as they were when the layout switches back. */}+ <div hidden={threads} className="h-full min-h-0">+ {session ? <RetainedWorkspaceGrid session={session} onScreen={onScreen && !threads} workspaceIds={state.workspaces?.map((workspace) => workspace.id)} onChanged={(next) => setState((current) => current?.session?.id === next.id ? { ...current, session: next } : current)}onAdd={openAgentPicker} onClose={closeAgent} onSelect={setSelected} selected={selected} fontSize={fontSize} appearance={appearance} disabled={busy}onMutationStart={beginGridMutation} onMutationEnd={endGridMutation} paneStyle={paneStyle} workspaces={state.workspaces ?? []} />: <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">@@ -558,6 +569,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {<p className="max-w-md text-sm text-muted-foreground">{projects.some((project) => !project.scratch && !project.archived) ? "Select a workspace from Projects, or create one with + beside its project." : "Connect a folder to bring its coding agents and Jarvis into one workspace."}</p><button type="button" onClick={() => setProjectDialog(true)} className="mt-2 rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent">Connect folder</button></div>}+ </div></IdeSidePanelFrame></main>diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.pyindex 1df853163d..98521707d1 100644--- a/jarvis/ui/web/workspace_routes.py+++ b/jarvis/ui/web/workspace_routes.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport asyncioimport logging+from pathlib import Pathfrom fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, Field@@ -173,11 +174,17 @@ async def workspace_pty(ws: WebSocket, key: str) -> None:from jarvis.agentic_ide.session import get_registryworkspace_id = qp.get("workspace_id")+ folder = _terminal_folder(qp.get("folder"))workspace = get_registry().get(workspace_id) if workspace_id else None- if workspace is None:+ if workspace is not None:+ cwd = str(workspace.folder)+ elif folder is not None and not workspace_id:+ # A thread's terminal drawer: pinned to the thread's own folder,+ # which may be a worktree no workspace has open.+ cwd = str(folder)+ else:await ws.close(code=4404, reason="workspace not found")return- cwd = str(workspace.folder)argv = build_agent_argv(PLAIN_TERMINAL)elif agent:if agent not in known:@@ -266,6 +273,18 @@ async def workspace_pty(ws: WebSocket, key: str) -> None:invalidate_agent_detection()+def _terminal_folder(raw: str | None) -> Path | None:+ """An existing directory named by ``?folder=``, or None."""+ text = (raw or "").strip()+ if not text:+ return None+ try:+ path = Path(text).expanduser()+ return path.resolve() if path.is_absolute() and path.is_dir() else None+ except (OSError, ValueError):+ return None++def _safe_int(value: object, default: int) -> int:try:n = int(str(value))diff --git a/tests/unit/agentic_ide/test_thread_mode.py b/tests/unit/agentic_ide/test_thread_mode.pynew file mode 100644index 0000000000..c642ddf672--- /dev/null+++ b/tests/unit/agentic_ide/test_thread_mode.py@@ -0,0 +1,197 @@+"""The Agentic IDE's thread layout: the backend pieces it reads.++A thread is an agent-chat session on the IDE's own surface. Its list row is+named by the title the coding CLI gave the conversation itself (unless the+person renamed it), it reports waiting approvals, its diff panel reads the+thread's folder — a worktree no workspace has open included — and its+terminal drawer opens a shell in that folder.+"""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_chat.events import make_event+from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.agentic_ide import cli_title+from jarvis.ui.web import workspace_routes+from jarvis.ui.web.agent_chat_routes import router as chat_router+from jarvis.ui.web.agentic_ide_git_routes import router as git_router++[email protected](autouse=True)+def _fresh_titles(monkeypatch):+ monkeypatch.setattr(cli_title, "RECHECK_S", 0.0)+ cli_title.reset_for_tests()+ yield+ cli_title.reset_for_tests()+++def _write_jsonl(path: Path, rows: list[dict]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("a", encoding="utf-8", newline="\n") as handle:+ for row in rows:+ handle.write(json.dumps(row) + "\n")+++# ------------------------------------------------------------ CLI titles+++def test_a_thread_takes_claude_s_own_title_from_its_seat_s_folder(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(cli_title, "_account_home", lambda agent, account: tmp_path)+ sid = "6f1c2d1e-0000-4000-8000-000000000001"+ transcript = tmp_path / "projects" / "C--repo" / f"{sid}.jsonl"+ _write_jsonl(transcript, [{"type": "user", "message": "fix the login test"}])+ assert cli_title.session_title("claude", sid) == ""++ _write_jsonl(transcript, [{"type": "ai-title", "aiTitle": "Fix login test"}])+ assert cli_title.session_title("claude", sid) == "Fix login test"++ _write_jsonl(transcript, [{"type": "custom-title", "customTitle": "Login fix"}])+ assert cli_title.session_title("claude", sid) == "Login fix"+++def test_a_thread_takes_codex_s_thread_name(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(cli_title, "_account_home", lambda agent, account: tmp_path)+ _write_jsonl(+ tmp_path / "session_index.jsonl", [{"id": "thread-1", "thread_name": "Speed up the build"}]+ )+ assert cli_title.session_title("codex", "thread-1") == "Speed up the build"+++def test_no_title_for_other_clis_or_unsafe_ids(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(cli_title, "_account_home", lambda agent, account: tmp_path)+ assert cli_title.session_title("opencode", "abc") == ""+ assert cli_title.session_title("claude", "../escape") == ""+ assert cli_title.session_title("claude", "") == ""+++# ------------------------------------------------------------ session list+++def _chat_app(tmp_path: Path) -> tuple[FastAPI, AgentChatService]:+ service = AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ app = FastAPI()+ app.include_router(chat_router)+ app.state.agent_chat = service+ return app, service+++def test_the_thread_list_offers_the_cli_title_until_the_person_renames(+ tmp_path, monkeypatch+) -> None:+ monkeypatch.setattr(+ cli_title,+ "session_title",+ lambda agent, sid, account="": "Fix login test" if agent == "claude" else "",+ )+ app, service = _chat_app(tmp_path)+ session = service.store.create_session(+ provider="claude-api",+ model="",+ effort="",+ cwd=str(tmp_path),+ permission_mode="default",+ surface="agent",+ )+ service.store.append_event(+ session.session_id, make_event("user_message", {"text": "fix the login test please"})+ )+ service.store.update_session(+ session.session_id, vendor_session="6f1c2d1e-0000-4000-8000-000000000001"+ )++ with TestClient(app) as client:+ row = client.get("/api/agent-chat/sessions?surface=agent").json()["sessions"][0]+ assert row["title"] == "fix the login test please"+ assert row["cli_title"] == "Fix login test"+ assert row["pending_approvals"] == []++ client.patch(+ f"/api/agent-chat/sessions/{session.session_id}", json={"title": "My own name"}+ )+ row = client.get("/api/agent-chat/sessions?surface=agent").json()["sessions"][0]+ assert row["title"] == "My own name"+ assert row["cli_title"] == ""+++def test_the_front_page_list_is_left_alone(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(cli_title, "session_title", lambda *args, **kwargs: "never")+ app, service = _chat_app(tmp_path)+ service.store.create_session(+ provider="claude-api",+ model="",+ effort="",+ cwd=str(tmp_path),+ permission_mode="",+ surface="jarvis",+ )+ monkeypatch.setattr("jarvis.ui.web.agent_chat_routes._title_jarvis_chats", lambda *args: None)+ with TestClient(app) as client:+ row = client.get("/api/agent-chat/sessions?surface=jarvis").json()["sessions"][0]+ assert "cli_title" not in row+++# ------------------------------------------------------------ folder diff+++def _git(args: list[str], cwd: Path) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)+++def repo(tmp_path: Path) -> Path:+ folder = tmp_path / "repo"+ folder.mkdir()+ _git(["init", "-q"], folder)+ _git(["config", "user.email", "[email protected]"], folder)+ _git(["config", "user.name", "Test"], folder)+ (folder / "app.py").write_text("one\ntwo\n", encoding="utf-8")+ _git(["add", "app.py"], folder)+ _git(["commit", "-q", "-m", "init"], folder)+ return folder+++def test_a_thread_s_diff_panel_reads_its_own_folder(repo: Path) -> None:+ (repo / "app.py").write_text("one\nthree\n", encoding="utf-8")+ (repo / "new.txt").write_text("hello\n", encoding="utf-8")+ app = FastAPI()+ app.include_router(git_router)+ with TestClient(app) as client:+ changes = client.get("/api/agentic-ide/git/changes", params={"folder": str(repo)}).json()+ assert changes["available"] is True+ assert {item["path"]: item["status"] for item in changes["files"]} == {+ "app.py": "modified",+ "new.txt": "untracked",+ }++ diff = client.get(+ "/api/agentic-ide/git/diff", params={"folder": str(repo), "path": "app.py"}+ ).json()+ kinds = [(line["kind"], line["text"]) for hunk in diff["hunks"] for line in hunk["lines"]]+ assert ("del", "two") in kinds and ("add", "three") in kinds++ outside = client.get(+ "/api/agentic-ide/git/diff", params={"folder": str(repo), "path": "../escape.txt"}+ )+ assert outside.status_code == 400+++# ------------------------------------------------------------ terminal drawer+++def test_the_drawer_terminal_folder_must_be_an_existing_absolute_directory(tmp_path: Path) -> None:+ assert workspace_routes._terminal_folder(str(tmp_path)) == tmp_path.resolve()+ assert workspace_routes._terminal_folder("relative/path") is None+ assert workspace_routes._terminal_folder(str(tmp_path / "missing")) is None+ assert workspace_routes._terminal_folder("") is None+ assert workspace_routes._terminal_folder(None) is None