Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): harden the thread layout after review

rubenluetke10-beepf79595145291
diff --git a/jarvis/agentic_ide/cli_title.py b/jarvis/agentic_ide/cli_title.py
index 7d8e2f4ca0..4031561c8d 100644
--- a/jarvis/agentic_ide/cli_title.py
+++ b/jarvis/agentic_ide/cli_title.py
@@ -30,6 +30,7 @@ import json
import re
import threading
import time
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -86,6 +87,13 @@ class _CodexIndex:
_records: dict[tuple[str, str], _Record] = {}
+#: Chat threads keep their own cache: a long thread list must not evict the
+#: panes' entries, nor the panes the threads'.
+_thread_records: dict[tuple[str, str], _Record] = {}
+#: Thread titles are read here, never on the request that lists the threads.
+_reader = ThreadPoolExecutor(max_workers=2, thread_name_prefix="cli-title")
+#: Bound on the thread cache — far above any real thread list.
+MAX_THREAD_ENTRIES = 4096
_codex_indexes: dict[str, _CodexIndex] = {}
#: Several panes' reads run on executor threads and share one index per home.
_codex_lock = threading.Lock()
@@ -145,7 +153,7 @@ 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 "")
- return _cached_title((pane, session_id), agent, session_id, _home(term))
+ return _cached_title(_records, MAX_ENTRIES, (pane, session_id), agent, session_id, _home(term))
def session_title(agent: str, session_id: str, account_id: str = "") -> str:
@@ -153,7 +161,9 @@ def session_title(agent: str, session_id: str, account_id: str = "") -> str:
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.
+ terminal and therefore no window title. Same records; the read runs on a
+ worker thread, so a list of many threads answers from the cache at once
+ and picks a new title up on its next read.
"""
try:
agent = (agent or "").strip().lower()
@@ -163,19 +173,32 @@ def session_title(agent: str, session_id: str, account_id: str = "") -> str:
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))
+ key = ("thread", session_id)
+ title = _cached_title(
+ _thread_records, MAX_THREAD_ENTRIES, key, agent, session_id, home, background=True
+ )
+ return _clip(title)
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:
+def _cached_title(
+ records: dict[tuple[str, str], _Record],
+ limit: int,
+ key: tuple[str, str],
+ agent: str,
+ session_id: str,
+ home: Path | None,
+ *,
+ background: bool = False,
+) -> str:
"""The title cached under ``key``, refreshed from the CLI's record on a slow clock."""
- entry = _records.get(key)
+ entry = records.get(key)
if entry is None:
- if len(_records) >= MAX_ENTRIES:
- _records.pop(next(iter(_records)))
- entry = _records[key] = _Record()
+ if len(records) >= limit:
+ records.pop(next(iter(records)))
+ entry = records[key] = _Record()
now = time.monotonic()
if entry.inflight or (entry.checked_at and now - entry.checked_at < RECHECK_S):
return entry.title
@@ -193,6 +216,9 @@ def _cached_title(key: tuple[str, str], agent: str, session_id: str, home: Path
entry.checked_at = time.monotonic()
entry.inflight = False
+ if background:
+ _reader.submit(_read)
+ return entry.title
try:
loop = asyncio.get_running_loop()
except RuntimeError:
@@ -318,6 +344,7 @@ def forget(key: str) -> None:
def reset_for_tests() -> None:
_records.clear()
+ _thread_records.clear()
_codex_indexes.clear()
@@ -326,6 +353,7 @@ __all__ = [
"clean_window_title",
"forget",
"reset_for_tests",
+ "session_title",
"title_for",
"window_title",
]
diff --git a/jarvis/agentic_ide/thread_folders.py b/jarvis/agentic_ide/thread_folders.py
new file mode 100644
index 0000000000..7751ac6b99
--- /dev/null
+++ b/jarvis/agentic_ide/thread_folders.py
@@ -0,0 +1,54 @@
+"""Which folders a thread's diff panel and terminal drawer may read.
+
+A thread runs in its project's folder or in a worktree of it, and the IDE
+creates worktrees inside the repository (``<repo>/.worktrees/<branch>``). So
+the folder routes answer for a folder inside a connected project or an open
+workspace, and for nothing else on the machine.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from loguru import logger
+
+
+def _resolved(path: str | Path) -> Path | None:
+ try:
+ return Path(path).expanduser().resolve()
+ except (OSError, ValueError, RuntimeError):
+ return None
+
+
+def _inside(child: Path, parent: Path) -> bool:
+ a = os.path.normcase(str(child))
+ b = os.path.normcase(str(parent))
+ return a == b or a.startswith(b.rstrip("\\/") + os.sep)
+
+
+def _known_roots() -> list[Path]:
+ roots: list[str] = []
+ try:
+ from jarvis.agentic_ide.library import list_projects
+
+ roots += [project.path for project in list_projects(include_archived=True) if project.path]
+ except Exception as exc: # noqa: BLE001 - an unreadable library leaves the workspaces
+ logger.debug("Agentic IDE: project list unreadable for a folder check: {}", exc)
+ try:
+ from jarvis.agentic_ide.session import get_registry
+
+ roots += [str(session.folder) for session in get_registry().sessions() if session.folder]
+ except Exception as exc: # noqa: BLE001 - no registry (a bare test app) leaves the projects
+ logger.debug("Agentic IDE: workspace list unreadable for a folder check: {}", exc)
+ return [path for path in (_resolved(root) for root in roots) if path is not None]
+
+
+def allowed_thread_folder(folder: str | Path) -> Path | None:
+ """``folder`` resolved, when it is an existing directory inside a known root."""
+ path = _resolved(folder)
+ if path is None or not path.is_absolute() or not path.is_dir():
+ return None
+ if any(_inside(path, root) for root in _known_roots()):
+ return path
+ return None
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
index 34972ba681..ef1a144167 100644
--- a/jarvis/ui/web/agentic_ide_git_routes.py
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -28,6 +28,7 @@ UI can offer the follow-up it has for that code (``dirty`` → "remove anyway?")
from __future__ import annotations
from dataclasses import asdict
+from pathlib import Path
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
@@ -36,6 +37,7 @@ from jarvis.agentic_ide import git_changes, git_ops, git_overview, github_link,
from jarvis.agentic_ide.git_ops import GitError, PrepareMode
from jarvis.agentic_ide.session import account_home, get_registry
from jarvis.agentic_ide.session_branches import PaneBranchRecord
+from jarvis.agentic_ide.thread_folders import allowed_thread_folder
router = APIRouter(prefix="/api/agentic-ide/git", tags=["agentic-ide-git"])
@@ -84,8 +86,20 @@ def inspect_folder(folder: str = Query(..., min_length=1)) -> dict:
@router.get("/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))
+ Changes tab, for a folder no workspace has open (a thread's worktree).
+
+ Only a folder inside a connected project or an open workspace is read.
+ """
+ return asdict(git_changes.workspace_changes(_thread_folder(folder)))
+
+
+def _thread_folder(folder: str) -> Path:
+ path = allowed_thread_folder(folder)
+ if path is None:
+ raise HTTPException(
+ status_code=403, detail="This folder is not part of a connected project."
+ )
+ return path
@router.get("/diff", summary="How one file under a folder differs from the last commit")
@@ -93,7 +107,7 @@ 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))
+ return asdict(git_changes.file_diff(_thread_folder(folder), path))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
index d95cf7e3ab..09097c7ed1 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadComposer.tsx
@@ -19,6 +19,8 @@ interface QueuedMessage {
/** Draft text per thread, so switching threads never loses a half-written message. */
const drafts = new Map<string, string>();
+/** Queued follow-ups per thread, so switching threads never drops one. */
+const queues = new Map<string, QueuedMessage[]>();
/** The open question card of the newest turn, if any. */
function openQuestion(timeline: Timeline): { block: ToolBlock; question: QuestionState } | null {
@@ -140,7 +142,19 @@ export function ThreadComposer({
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 [queue, setQueueState] = useState<QueuedMessage[]>(() => queues.get(threadKey) ?? []);
+ // After Stop the queue waits: the person halted the agent, it must not start the next job.
+ const [paused, setPaused] = useState(false);
+ const queueKey = useRef(threadKey);
+ queueKey.current = threadKey;
+ const setQueue = useCallback((update: (current: QueuedMessage[]) => QueuedMessage[]) => {
+ setQueueState((current) => {
+ const next = update(current);
+ if (next.length) queues.set(queueKey.current, next);
+ else queues.delete(queueKey.current);
+ return next;
+ });
+ }, []);
const [problem, setProblem] = useState("");
const [starting, setStarting] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
@@ -173,7 +187,8 @@ export function ThreadComposer({
// Another thread: its own half-written text, its own queue.
useEffect(() => {
setValueState(drafts.get(threadKey) ?? "");
- setQueue([]);
+ setQueueState(queues.get(threadKey) ?? []);
+ setPaused(false);
setProblem("");
}, [threadKey]);
@@ -222,11 +237,20 @@ export function ThreadComposer({
// 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]);
+ if (paused || running || busy || starting || queue.length === 0 || !activeSessionId) return;
+ const [next] = queue;
+ const key = threadKey;
+ setQueue((current) => current.filter((row) => row.id !== next.id));
+ void dispatch(next.text, next.attachments).then((sent) => {
+ if (sent) return;
+ // Not delivered: back to the front of ITS thread's line, and wait for the person.
+ queues.set(key, [next, ...(queues.get(key) ?? [])]);
+ if (queueKey.current === key) {
+ setQueueState(queues.get(key) ?? []);
+ setPaused(true);
+ }
+ });
+ }, [paused, running, busy, starting, queue, activeSessionId, dispatch, setQueue, threadKey]);
const submit = async () => {
const text = value.trim();
@@ -240,6 +264,7 @@ export function ThreadComposer({
setValue("");
files.clear();
setProblem("");
+ setPaused(false);
if (running || busy) {
setQueue((current) => [...current, { id: ++queueId.current, text, attachments }]);
return;
@@ -268,6 +293,10 @@ export function ThreadComposer({
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">
+ {paused && !running && <div className="flex items-center justify-between gap-2 px-1 text-xs text-muted-foreground">
+ <span>Queue paused after the agent stopped.</span>
+ <button type="button" onClick={() => setPaused(false)} className="rounded px-1.5 py-0.5 text-foreground hover:bg-secondary">Send next</button>
+ </div>}
{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>
@@ -323,7 +352,7 @@ export function ThreadComposer({
</button>
{running && !canSend
? <button type="button" aria-label="Stop the agent" title="Stop" data-testid="thread-stop"
- onClick={() => void useThreadChatStore.getState().cancel()}
+ onClick={() => { setPaused(true); 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>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx
index bef465371b..0be5db5cf6 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadDiffPanel.tsx
@@ -48,8 +48,11 @@ export function ThreadDiffPanel({ folder, version, onClose }: { folder: string;
return () => controller.abort();
}, [folder, version, nonce]);
+ // Another thread's folder: nothing of the last one may show under its name.
useEffect(() => {
setOpenPath(null);
+ setChanges(null);
+ setShowAll(false);
}, [folder]);
useEffect(() => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx
index 2db84b5756..e12eb798f1 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTerminalDrawer.tsx
@@ -18,9 +18,14 @@ 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.
+ *
+ * Every shell stays mounted while the person moves between threads — a dev
+ * server keeps running — but only the open thread's folder has its tabs shown.
*/
export function ThreadTerminalDrawer({
terminals,
+ folder,
+ open,
active,
height,
onSelect,
@@ -30,6 +35,9 @@ export function ThreadTerminalDrawer({
onResize,
}: {
terminals: DrawerTerminal[];
+ /** The open thread's folder: only its shells are shown. */
+ folder: string;
+ open: boolean;
active: string;
height: number;
onSelect: (id: string) => void;
@@ -50,17 +58,19 @@ export function ThreadTerminalDrawer({
onResize(Math.max(MIN_HEIGHT, Math.min(next, Math.round(window.innerHeight * 0.75))));
}, [onResize]);
const onPointerUp = useCallback(() => { drag.current = null; }, []);
+ const shown = terminals.filter((terminal) => terminal.folder === folder);
+ const current = shown.some((terminal) => terminal.id === active) ? active : shown[shown.length - 1]?.id ?? "";
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">
+ className={cn("relative shrink-0 flex-col border-t border-border bg-background", open && shown.length > 0 ? "flex" : "hidden")}>
<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}
+ {shown.map((terminal) => <div key={terminal.id} role="tab" aria-selected={terminal.id === current}
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")}>
+ terminal.id === current ? "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>
@@ -74,9 +84,9 @@ export function ThreadTerminalDrawer({
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">
+ {terminals.map((terminal) => <div key={terminal.id} hidden={terminal.id !== current} 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} />
+ title={terminal.title} bare active={open && terminal.id === current} />
</div>)}
</div>
</section>;
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.tsx
index cd27740e6f..f0cd03bd29 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx
@@ -100,6 +100,25 @@ describe("ThreadView", () => {
expect(useIdeThreadsStore.getState().projectOf).toEqual({ s1: "p1" });
});
+ it("files a thread started in a draft under its project when the person moved on meanwhile", async () => {
+ let finishCreate: (row: AgentChatSession) => void = () => {};
+ api.createAgentChatSession.mockReturnValue(new Promise<AgentChatSession>((resolve) => { finishCreate = resolve; }));
+ render(<ThreadView onScreen />);
+ await waitFor(() => expect(useThreadChatStore.getState().draft.cwd).toBe("/repo"));
+ const box = screen.getByTestId("thread-composer-input");
+ fireEvent.change(box, { target: { value: "start something" } });
+ await act(async () => { fireEvent.keyDown(box, { key: "Enter" }); });
+ await waitFor(() => expect(api.createAgentChatSession).toHaveBeenCalled());
+
+ // The person opens another thread before the first one exists.
+ act(() => useIdeThreadsStore.getState().openThread("other", "p1"));
+ await act(async () => { finishCreate(sessionRow({ session_id: "s-new" })); });
+
+ await waitFor(() => expect(useIdeThreadsStore.getState().projectOf).toEqual({ "s-new": "p1" }));
+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "other" });
+ await waitFor(() => expect(useThreadChatStore.getState().activeSessionId).toBe("other"));
+ });
+
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()]);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
index 0128d84966..9f356316cf 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx
@@ -81,18 +81,37 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
const folder = session?.cwd || project?.path || "";
const isDraft = selection.sessionId === null;
- // Open the picked thread, or a blank draft in the picked project.
+ // Keep the store on what the sidebar picked. A draft's first message
+ // creates its session: that is this project's thread now — unless the
+ // person moved on while it was being created; then it only remembers where
+ // it belongs, and the thread they picked is what shows.
useEffect(() => {
const store = useThreadChatStore.getState();
+ const threads = useIdeThreadsStore.getState();
+ const pending = startingIn.current;
+ const created = pending && store.activeSessionId && store.activeSessionId !== selection.sessionId ? store.activeSessionId : null;
+ if (pending && created) {
+ startingIn.current = null;
+ if (!selection.sessionId && selection.projectId === pending) {
+ threads.adoptThread(created, pending);
+ return;
+ }
+ threads.rememberProject(created, pending);
+ }
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();
+ if (startingIn.current) return; // the draft's first message is on its way
+ if (store.activeSessionId || store.timeline.items.length > 0) store.newChat();
+ }, [selection.sessionId, selection.projectId, activeSessionId]);
+
+ // A new draft starts in its project's own checkout.
+ useEffect(() => {
+ if (!isDraft) return;
setCheckout("current");
setBase("");
- }, [selection.sessionId]);
+ }, [isDraft, selection.projectId]);
// A draft runs in its project's folder.
useEffect(() => {
@@ -100,14 +119,6 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
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);
@@ -158,7 +169,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
const toggleTerminal = () => {
if (drawerOpen) { setDrawerOpen(false); return; }
- if (terminals.length === 0) addTerminal("Terminal");
+ if (!terminals.some((terminal) => terminal.folder === folder)) addTerminal("Terminal");
else setDrawerOpen(true);
};
@@ -168,7 +179,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
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);
+ if (!next.some((terminal) => terminal.folder === folder)) setDrawerOpen(false);
return next;
});
};
@@ -192,7 +203,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
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}
+ sessionId={selection.sessionId} terminalOpen={drawerOpen && terminals.some((terminal) => terminal.folder === folder)} 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">
@@ -229,7 +240,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {
</div>
</>}
</div>
- {drawerOpen && terminals.length > 0 && <ThreadTerminalDrawer terminals={terminals} active={activeTerminal} height={drawerHeight}
+ {terminals.length > 0 && <ThreadTerminalDrawer terminals={terminals} folder={folder} open={drawerOpen} 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>
diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.ts b/jarvis/ui/web/frontend/src/store/ideThreads.ts
index b057eab134..6ac794ce81 100644
--- a/jarvis/ui/web/frontend/src/store/ideThreads.ts
+++ b/jarvis/ui/web/frontend/src/store/ideThreads.ts
@@ -98,6 +98,8 @@ interface IdeThreadsState {
newThread: (projectId: string) => void;
/** The draft became a session: remember where it belongs and show it. */
adoptThread: (sessionId: string, projectId: string) => void;
+ /** A session started in `projectId` while another thread was picked: file it, show nothing new. */
+ rememberProject: (sessionId: string, projectId: string) => void;
markSeen: (sessionId: string, updatedMs: number) => void;
/** A thread was deleted: forget everything kept about it. */
forgetThread: (sessionId: string) => void;
@@ -132,6 +134,11 @@ export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({
write(PROJECT_OF_KEY, projectOf);
set({ selection, projectOf });
},
+ rememberProject: (sessionId, projectId) => {
+ const projectOf = bounded({ ...get().projectOf, [sessionId]: projectId });
+ write(PROJECT_OF_KEY, projectOf);
+ set({ projectOf });
+ },
markSeen: (sessionId, updatedMs) => {
if ((get().seen[sessionId] ?? 0) >= updatedMs) return;
const { [sessionId]: _previous, ...rest } = get().seen;
diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.py
index 98521707d1..34b97d0fae 100644
--- a/jarvis/ui/web/workspace_routes.py
+++ b/jarvis/ui/web/workspace_routes.py
@@ -274,15 +274,14 @@ async def workspace_pty(ws: WebSocket, key: str) -> None:
def _terminal_folder(raw: str | None) -> Path | None:
- """An existing directory named by ``?folder=``, or None."""
+ """The thread folder named by ``?folder=``: an existing directory inside a
+ connected project or an open workspace, else 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
+ from jarvis.agentic_ide.thread_folders import allowed_thread_folder
+
+ return allowed_thread_folder(text)
def _safe_int(value: object, default: int) -> int:
diff --git a/tests/unit/agentic_ide/test_thread_mode.py b/tests/unit/agentic_ide/test_thread_mode.py
index c642ddf672..106e047f67 100644
--- a/tests/unit/agentic_ide/test_thread_mode.py
+++ b/tests/unit/agentic_ide/test_thread_mode.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import subprocess
+import time
from pathlib import Path
import pytest
@@ -20,7 +21,7 @@ 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.agentic_ide import cli_title, thread_folders
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
@@ -41,6 +42,16 @@ def _write_jsonl(path: Path, rows: list[dict]) -> None:
handle.write(json.dumps(row) + "\n")
+def _settled(agent: str, sid: str, expected: str) -> str:
+ """The thread title once the background read caught up (it never blocks the list)."""
+ deadline = time.monotonic() + 3.0
+ title = cli_title.session_title(agent, sid)
+ while title != expected and time.monotonic() < deadline:
+ time.sleep(0.02)
+ title = cli_title.session_title(agent, sid)
+ return title
+
+
# ------------------------------------------------------------ CLI titles
@@ -49,13 +60,13 @@ def test_a_thread_takes_claude_s_own_title_from_its_seat_s_folder(tmp_path, monk
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) == ""
+ assert _settled("claude", sid, "") == ""
_write_jsonl(transcript, [{"type": "ai-title", "aiTitle": "Fix login test"}])
- assert cli_title.session_title("claude", sid) == "Fix login test"
+ assert _settled("claude", sid, "Fix login test") == "Fix login test"
_write_jsonl(transcript, [{"type": "custom-title", "customTitle": "Login fix"}])
- assert cli_title.session_title("claude", sid) == "Login fix"
+ assert _settled("claude", sid, "Login fix") == "Login fix"
def test_a_thread_takes_codex_s_thread_name(tmp_path, monkeypatch) -> None:
@@ -63,7 +74,8 @@ def test_a_thread_takes_codex_s_thread_name(tmp_path, monkeypatch) -> None:
_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"
+ # The first read answers from the (empty) cache at once; the record lands next.
+ assert _settled("codex", "thread-1", "Speed up the build") == "Speed up the build"
def test_no_title_for_other_clis_or_unsafe_ids(tmp_path, monkeypatch) -> None:
@@ -161,7 +173,8 @@ def repo(tmp_path: Path) -> Path:
return folder
-def test_a_thread_s_diff_panel_reads_its_own_folder(repo: Path) -> None:
+def test_a_thread_s_diff_panel_reads_its_own_folder(repo: Path, monkeypatch) -> None:
+ monkeypatch.setattr(thread_folders, "_known_roots", lambda: [repo.resolve()])
(repo / "app.py").write_text("one\nthree\n", encoding="utf-8")
(repo / "new.txt").write_text("hello\n", encoding="utf-8")
app = FastAPI()
@@ -186,11 +199,32 @@ def test_a_thread_s_diff_panel_reads_its_own_folder(repo: Path) -> None:
assert outside.status_code == 400
+def test_the_folder_routes_read_only_connected_projects(repo: Path, tmp_path: Path, monkeypatch):
+ project = tmp_path / "project"
+ project.mkdir()
+ monkeypatch.setattr(thread_folders, "_known_roots", lambda: [project.resolve()])
+ app = FastAPI()
+ app.include_router(git_router)
+ with TestClient(app) as client:
+ changes = client.get("/api/agentic-ide/git/changes", params={"folder": str(repo)})
+ assert changes.status_code == 403
+ diff = client.get(
+ "/api/agentic-ide/git/diff", params={"folder": str(repo), "path": "app.py"}
+ )
+ assert diff.status_code == 403
+
+
# ------------------------------------------------------------ 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()
+def test_the_drawer_terminal_opens_only_inside_a_connected_project(tmp_path: Path, monkeypatch):
+ project = tmp_path / "project"
+ (project / ".worktrees" / "fix").mkdir(parents=True)
+ monkeypatch.setattr(thread_folders, "_known_roots", lambda: [project.resolve()])
+ assert workspace_routes._terminal_folder(str(project)) == project.resolve()
+ worktree = project / ".worktrees" / "fix"
+ assert workspace_routes._terminal_folder(str(worktree)) == worktree.resolve()
+ assert workspace_routes._terminal_folder(str(tmp_path)) is None
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