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(ide): fork a coding agent's chat, optionally into its own git worktree
rubenluetke10-beepf6a3f5004e9b
diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.pyindex dd12c33295..446c2df4d4 100644--- a/jarvis/agentic_ide/agent_sessions.py+++ b/jarvis/agentic_ide/agent_sessions.py@@ -129,6 +129,10 @@ class _Adapter:discover: Callable[[str, float, Collection[str], Path | None], ResumeHandle | None] | None# Is there actually a conversation behind an id? See `has_conversation`.exists: Callable[[ResumeHandle, Path | None], bool]+ # Extra argv that starts a NEW conversation carrying a copy of an existing+ # one, plus the handle the copy will be reachable by (None = discovered+ # later, like a fresh start). None for a CLI with no fork of its own.+ fork: Callable[[str], tuple[tuple[str, ...], ResumeHandle | None]] | None = Nonedef _claude_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:@@ -151,6 +155,19 @@ def _grok_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:)+def _claude_fork(source_id: str) -> tuple[tuple[str, ...], ResumeHandle | None]:+ # `--fork-session` copies the resumed conversation under a new id, and it is+ # the one combination in which Claude Code also accepts `--session-id` — so+ # the copy's id is assigned here rather than searched for afterwards. The+ # copy is filed under the CURRENT folder's project, which is what lets a+ # fork continue inside a git worktree of the original checkout.+ session_id = str(uuid4())+ return (+ ("--resume", source_id, "--fork-session", "--session-id", session_id),+ ResumeHandle(kind="claude_session", id=session_id, captured_at=time.time()),+ )++def _codex_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:# Nothing can be passed: the id is Codex's to choose and ours to find later.return ((), None)@@ -168,6 +185,7 @@ _ADAPTERS: dict[str, _Adapter] = {resume=lambda session_id: ("--resume", session_id),discover=None,exists=lambda handle, home: _claude_conversation_exists(handle, home),+ fork=_claude_fork,),"codex": _Adapter(kind="codex_rollout",@@ -179,6 +197,9 @@ _ADAPTERS: dict[str, _Adapter] = {# next to the file-format knowledge it needs.discover=lambda cwd, started, taken, home: _discover_codex(cwd, started, taken, home),exists=lambda handle, home: _codex_conversation_exists(handle, home),+ # `codex fork <id>` writes a new rollout; its id is discovered like any+ # other Codex session (folder + time, minus the ids already taken).+ fork=lambda session_id: (("fork", session_id), None),),"opencode": _Adapter(kind="opencode_session",@@ -189,6 +210,7 @@ _ADAPTERS: dict[str, _Adapter] = {resume=lambda session_id: ("--session", session_id),discover=lambda cwd, started, taken, home: _discover_opencode(cwd, started, taken, home),exists=lambda handle, home: _opencode_conversation_exists(handle, home),+ fork=lambda session_id: (("--session", session_id, "--fork"), None),),"kimi": _Adapter(kind="kimi_session",@@ -266,6 +288,30 @@ def resume_argv(agent: str, handle: ResumeHandle | None) -> tuple[str, ...] | Noreturn adapter.resume(handle.id)+def can_fork(agent: str) -> bool:+ """True when this coding CLI can copy one of its conversations into a new one."""+ adapter = _adapter_for(agent)+ return adapter is not None and adapter.fork is not None+++def fork_argv(+ agent: str, handle: ResumeHandle | None+) -> tuple[tuple[str, ...], ResumeHandle | None] | None:+ """Extra argv that starts a copy of ``handle``'s conversation, or None.++ The second element is the copy's own handle when the CLI lets us assign+ it, else None (the handle is discovered afterwards, as for a fresh start).+ None overall means the same as for :func:`resume_argv`: this CLI, this+ handle or its kind cannot be forked, so the caller starts fresh.+ """+ if handle is None:+ return None+ adapter = _adapter_for(agent)+ if adapter is None or adapter.fork is None or adapter.kind != handle.kind:+ return None+ return adapter.fork(handle.id)++def has_conversation(agent: str, handle: ResumeHandle | None, home: Path | None = None) -> bool:"""Is there actually something behind this handle, or only a reserved id?diff --git a/jarvis/agentic_ide/fork.py b/jarvis/agentic_ide/fork.pynew file mode 100644index 0000000000..960206b48f--- /dev/null+++ b/jarvis/agentic_ide/fork.py@@ -0,0 +1,222 @@+"""Forking a pane: a second agent that starts from a copy of the first one's chat.++Two shapes, one gesture:++* **Chat fork** — the copy runs in the same folder as the original. Useful to+ try a different direction without losing the one already taken.+* **Worktree fork** — the copy runs in a fresh ``git worktree`` on its own+ branch, so the two agents can edit files at the same time without touching+ each other's work.++This module owns the git half: suggesting a branch name that reads like the+pane it came from, and creating the worktree. The conversation half — which+argv makes a coding CLI copy its own conversation — lives in+:mod:`.agent_sessions` next to the other per-CLI knowledge, and the pane itself+is opened by ``Registry.fork_terminal``.++Where worktrees go: ``<repo>/.worktrees/<name>``. Inside the project, so the+user finds it beside the code it belongs to, and listed in the repository's+LOCAL ``.git/info/exclude`` so it never shows up as untracked files — nothing in+the committed ``.gitignore`` is changed on the user's behalf.++Blocking (``git`` subprocesses and filesystem work) — callers run these in a+worker thread. Cross-platform: plain ``git`` on PATH, ``pathlib`` paths, UTF-8.+"""++from __future__ import annotations++import os+import re+import subprocess+from dataclasses import dataclass+from pathlib import Path++from loguru import logger++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++# The folder under the repository root that holds forked worktrees.+WORKTREE_DIR = ".worktrees"++# A branch name longer than this stops reading like a label. The slug is cut at+# a word boundary below it.+_MAX_SLUG = 40++_GIT_TIMEOUT_S = 60+++class ForkError(RuntimeError):+ """A fork that cannot be made, worded for the person who asked for it."""+++@dataclass(frozen=True, slots=True)+class Worktree:+ """A freshly created worktree and where the forked pane should run in it."""++ branch: str+ root: Path+ # The pane's working folder: the worktree root, or the same sub-folder of+ # it that the workspace had open in the original checkout.+ folder: Path+++def _git(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:+ try:+ return subprocess.run(+ ["git", *args],+ cwd=str(cwd),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=_GIT_TIMEOUT_S,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except FileNotFoundError as exc:+ raise ForkError("Git is not installed, so a worktree cannot be created.") from exc+ except subprocess.TimeoutExpired as exc:+ raise ForkError("Git did not answer in time while creating the worktree.") from exc+++def repo_root(folder: str | Path) -> Path | None:+ """The top of the git checkout ``folder`` is in, or None if it is not one."""+ path = Path(folder).expanduser()+ if not path.is_dir():+ return None+ try:+ result = _git(["rev-parse", "--show-toplevel"], path)+ except ForkError:+ return None+ if result.returncode != 0:+ return None+ top = result.stdout.strip()+ return Path(top) if top else None+++def _slug(text: str) -> str:+ """Lowercase words joined by dashes, safe inside a git branch name."""+ words = re.findall(r"[a-z0-9]+", text.lower())+ slug = ""+ for word in words:+ candidate = f"{slug}-{word}" if slug else word+ if len(candidate) > _MAX_SLUG:+ break+ slug = candidate+ return slug+++def _branch_exists(root: Path, branch: str) -> bool:+ result = _git(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], root)+ return result.returncode == 0+++def _dir_name(branch: str) -> str:+ # A branch may be "fork/t1"; the folder is one level, never nested.+ return branch.replace("/", "-")+++def _taken(root: Path, branch: str) -> bool:+ return _branch_exists(root, branch) or (root / WORKTREE_DIR / _dir_name(branch)).exists()+++def base_name(pane_name: str, headline: str = "") -> str:+ """The name a fork of this pane is offered: call-sign plus what it works on.++ "T3" working on "Fix the login test" becomes ``t3-fix-the-login-test``; a+ pane with nothing to go on yet becomes ``t3-fork``. Lowercase and dashed,+ because that is how branch names are conventionally written.+ """+ sign = _slug(pane_name) or "pane"+ topic = _slug(headline)+ if topic and topic != sign:+ return f"{sign}-{topic}"+ return f"{sign}-fork"+++def suggest_name(folder: str | Path, pane_name: str, headline: str = "") -> str:+ """A branch/worktree name for a fork of this pane that is still free."""+ wanted = base_name(pane_name, headline)+ root = repo_root(folder)+ if root is None:+ return wanted+ candidate = wanted+ number = 2+ while _taken(root, candidate) and number < 100:+ candidate = f"{wanted}-{number}"+ number += 1+ return candidate+++def normalize_name(name: str) -> str:+ """The typed name as a branch name: trimmed, inner whitespace to dashes."""+ return re.sub(r"\s+", "-", (name or "").strip())+++def _exclude_worktree_dir(root: Path) -> None:+ """List ``.worktrees/`` in the repository's LOCAL exclude file, once."""+ result = _git(["rev-parse", "--git-path", "info/exclude"], root)+ if result.returncode != 0 or not result.stdout.strip():+ return+ exclude = Path(result.stdout.strip())+ if not exclude.is_absolute():+ exclude = root / exclude+ line = f"/{WORKTREE_DIR}/"+ try:+ existing = exclude.read_text(encoding="utf-8") if exclude.exists() else ""+ if line in existing.splitlines():+ return+ exclude.parent.mkdir(parents=True, exist_ok=True)+ prefix = "" if not existing or existing.endswith("\n") else "\n"+ with exclude.open("a", encoding="utf-8") as handle:+ handle.write(f"{prefix}{line}\n")+ except OSError as exc:+ # Only cosmetic: the worktree works, git status just lists the folder.+ logger.warning("Agentic IDE: could not exclude {} in {}: {}", line, exclude, exc)+++def create_worktree(folder: str | Path, name: str) -> Worktree:+ """Create ``<repo>/.worktrees/<name>`` on a new branch ``name`` off HEAD.++ Only committed work is in the new checkout — git worktrees start from a+ commit, and uncommitted changes stay in the original folder. Raises+ :class:`ForkError` with a sentence fit for the UI on every failure.+ """+ source = Path(folder).expanduser()+ root = repo_root(source)+ if root is None:+ raise ForkError(f"{source.name or source} is not a git repository, so it has no worktrees.")+ branch = normalize_name(name)+ if not branch:+ raise ForkError("The worktree needs a name.")+ check = _git(["check-ref-format", "--branch", branch], root)+ if check.returncode != 0:+ raise ForkError(f"{branch!r} is not a valid git branch name.")+ if _branch_exists(root, branch):+ raise ForkError(f"A branch called {branch!r} already exists — pick another name.")+ target = root / WORKTREE_DIR / _dir_name(branch)+ if target.exists():+ raise ForkError(f"The folder {target} already exists — pick another name.")+ head = _git(["rev-parse", "--verify", "--quiet", "HEAD"], root)+ if head.returncode != 0:+ raise ForkError("This repository has no commit yet, so there is nothing to branch from.")++ _exclude_worktree_dir(root)+ target.parent.mkdir(parents=True, exist_ok=True)+ result = _git(["worktree", "add", "-b", branch, str(target), "HEAD"], root)+ if result.returncode != 0:+ detail = (result.stderr or result.stdout).strip().splitlines()+ reason = detail[-1] if detail else f"git exited with {result.returncode}"+ raise ForkError(f"Git could not create the worktree: {reason}")++ # Same place inside the project as the workspace the pane came from.+ try:+ relative = Path(os.path.relpath(source.resolve(), root.resolve()))+ except ValueError:+ relative = Path(".")+ inside = str(relative) not in ("", ".") and relative.parts[0] != ".."+ pane_folder = target / relative if inside else target+ if not pane_folder.is_dir():+ pane_folder = target+ logger.info("Agentic IDE: created worktree {} on branch {}", target, branch)+ return Worktree(branch=branch, root=target, folder=pane_folder)diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex 6812285f26..b9156a02fc 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -97,6 +97,15 @@ class SnapshotTerminal:model: str = ""effort: str = ""permission_mode: str = ""+ # Where this pane runs when it is not the workspace folder — a git worktree+ # a fork was opened in — and that worktree's branch. Empty on older+ # snapshots and on every ordinary pane: the workspace folder, as before.+ folder: str = ""+ branch: str = ""+ # The conversation a forked pane has yet to copy. Cleared once its first+ # process started; kept here so a fork that never got to start before a+ # restart still starts as the copy it was opened as.+ fork_from: ResumeHandle | None = Nonedef to_dict(self) -> dict[str, Any]:return {@@ -115,6 +124,9 @@ class SnapshotTerminal:"model": self.model,"effort": self.effort,"permission_mode": self.permission_mode,+ "folder": self.folder,+ "branch": self.branch,+ "fork_from": self.fork_from.to_dict() if self.fork_from else None,}@staticmethod@@ -145,6 +157,9 @@ class SnapshotTerminal:model=str(data.get("model") or "").strip(),effort=str(data.get("effort") or "").strip(),permission_mode=str(data.get("permission_mode") or "").strip(),+ folder=str(data.get("folder") or "").strip(),+ branch=str(data.get("branch") or "").strip(),+ fork_from=ResumeHandle.from_dict(data.get("fork_from")),)diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex aed467fc00..d96a6d8241 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -81,12 +81,14 @@ from loguru import loggerfrom jarvis.workspace import agents as workspace_agentsfrom jarvis.workspace import launch_picks-from . import layout_tree, library, opening, prompt_history, recap_engine, resume_store+from . import fork, layout_tree, library, opening, prompt_history, recap_engine, resume_storefrom .activity import NO_READING, Reading, has_work_behind_it, observedfrom .agent_sessions import (ResumeHandle,+ can_fork,can_resume,discover,+ fork_argv,has_conversation,launch_extra,resume_argv,@@ -968,6 +970,17 @@ class Terminal:#: the timeline can tell a pick the chat just typed in from the older#: value the CLI's record still carries until its next reply.picked_at: dict[str, float] = field(default_factory=dict)+ # Where this pane's agent runs, when that is NOT the workspace folder: the+ # git worktree a fork was opened in (see `Registry.fork_terminal`). Empty+ # means the workspace folder, which is every pane that is not such a fork.+ # `branch` is that worktree's branch, shown in the pane header.+ folder: str = ""+ branch: str = ""+ # The conversation this pane is a COPY of, until its first process has+ # copied it. Spent by `attach` on the first spawn (the copy then has its+ # own handle in `resume`), so a restart afterwards resumes the copy rather+ # than forking the original a second time.+ fork_from: ResumeHandle | None = Nonestatus: Status = "pending"pty_id: str | None = None# The geometry the PTY ACTUALLY holds, as last handed to `setwinsize`.@@ -1327,6 +1340,12 @@ class Terminal:"archived": self.archived,"account": self.account,"account_label": account_label(self.account),+ # Set only for a pane running in a git worktree of its own.+ "folder": self.folder,+ "branch": self.branch,+ # Can this pane be forked with its conversation? False for a CLI+ # without a fork of its own — the fork then starts a fresh chat.+ "can_fork": can_fork(self.agent),}def to_row(self) -> dict[str, Any]:@@ -1417,8 +1436,15 @@ class Terminal:model=self.model,effort=self.effort,permission_mode=self.permission_mode,+ folder=self.folder,+ branch=self.branch,+ fork_from=self.fork_from,)+ def cwd(self, workspace_folder: str) -> str:+ """The folder this pane's agent runs in: its own worktree, else the workspace's."""+ return self.folder or workspace_folder+@dataclass(slots=True)class Session:@@ -2752,6 +2778,12 @@ class Registry:model=entry.model,effort=entry.effort,permission_mode=entry.permission_mode,+ # A worktree deleted in the meantime would leave the agent with+ # no folder to start in; the pane then falls back to the+ # workspace folder rather than failing the reopen.+ folder=entry.folder if entry.folder and Path(entry.folder).is_dir() else "",+ branch=entry.branch if entry.folder and Path(entry.folder).is_dir() else "",+ fork_from=entry.fork_from,)terminals = [_restored(index, entry) for index, entry in enumerate(space.terminals)]@@ -3598,6 +3630,23 @@ class Registry:)term.resume = Nonecontinuing = None+ # A forked pane's FIRST process starts as a copy of the conversation it+ # was forked from (see `Registry.fork_terminal`). Spent here, once: the+ # copy gets its own handle, and every later start resumes THAT rather+ # than forking the original again. A source without a conversation on+ # disk — never prompted, or pruned since — leaves nothing to copy, and+ # the pane starts fresh like any other.+ forking: tuple[tuple[str, ...], ResumeHandle | None] | None = None+ if continuing is None and term.fork_from is not None:+ source = term.fork_from+ term.fork_from = None+ if await asyncio.to_thread(has_conversation, term.agent, source, home):+ forking = fork_argv(term.agent, source)+ if forking is None:+ logger.info(+ "Agentic IDE: {} has no conversation to fork — starting fresh",+ term.name,+ )# What the pane was OPENED on, put back on the command line. A resume# gets them too: the CLI reads a conversation back, never the model or# the permission stance it ran under, so a restored pane without these@@ -3617,6 +3666,14 @@ class Registry:if continuing is not None:argv = (*argv, *continuing)term.resumed = True+ elif forking is not None:+ extra, minted = forking+ argv = (*argv, *extra)+ # A copy of an existing conversation — the same "continued, not+ # empty" claim a resume makes, and the same early-exit recovery+ # (`_closed`) if the CLI refuses the fork: the pane restarts fresh.+ term.resumed = True+ term.resume = mintedelse:if term.resume is None and term.prompts_sent and can_resume(term.agent):# A pane that was WORKED IN and still has no conversation id is@@ -3758,12 +3815,14 @@ class Registry:# a socket frame the pane painted over a moment later.try:if redirected_home is None:- env = await asyncio.to_thread(self._prepare_spawn, term, session.folder)+ env = await asyncio.to_thread(self._prepare_spawn, term, term.cwd(session.folder))else:account_key = os.path.normcase(str(redirected_home))account_gate = self._account_prepare_locks.setdefault(account_key, asyncio.Lock())async with account_gate:- env = await asyncio.to_thread(self._prepare_spawn, term, session.folder)+ env = await asyncio.to_thread(+ self._prepare_spawn, term, term.cwd(session.folder)+ )except SessionError as exc:term.status = "error"term.error = str(exc)@@ -3803,7 +3862,7 @@ class Registry:pty_session = await manager.spawn(shell_argv=argv,shell_id=f"agentic-ide:{term.key}",- cwd=session.folder,+ cwd=term.cwd(session.folder),cols=cols,rows=rows,on_output=_output,@@ -3902,7 +3961,7 @@ class Registry:if term.resume is None and can_resume(term.agent):# A CLI that cannot be told its session id (Codex): find out which# one it just created, shortly from now.- self._schedule_lookup(session, term, session.folder, term.started_at)+ self._schedule_lookup(session, term, term.cwd(session.folder), term.started_at)if term.continue_when_ready:# Somebody pressed "Continue" while this pane was still waiting for# a cold-start slot. The wish outlives the wait — see@@ -4127,7 +4186,9 @@ class Registry:returnif term.lookup_at and time.monotonic() - term.lookup_at < LOOKUP_COOLDOWN_S:return- self._schedule_lookup(owner, term, owner.folder, term.started_at, CONVERSATION_DELAYS_S)+ self._schedule_lookup(+ owner, term, term.cwd(owner.folder), term.started_at, CONVERSATION_DELAYS_S+ )def write(self, key: str, data: str, workspace_id: str | None = None) -> bool:"""Raw keystrokes from the pane's own xterm (not the injection path)."""@@ -4763,6 +4824,92 @@ class Registry:)return term+ def fork_suggestion(self, wanted: str, workspace_id: str | None = None) -> dict[str, Any]:+ """What the fork dialog offers for pane ``wanted``, before anything is made.++ Blocking (a few ``git`` calls) — callers run it in a worker thread.+ """+ found = self._locate(wanted, workspace_id)+ if found is None:+ raise self._unknown_terminal(wanted)+ session, term = found+ base = term.cwd(session.folder)+ return {+ "name": fork.suggest_name(base, term.name, recap_engine.known_headline(term)),+ "in_repo": fork.repo_root(base) is not None,+ "can_fork": can_fork(term.agent),+ "has_conversation": term.resume is not None,+ }++ async def fork_terminal(+ self,+ wanted: str,+ *,+ workspace_id: str | None = None,+ worktree: bool = False,+ name: str | None = None,+ direction: str = "right",+ ) -> Terminal:+ """Open a new pane that starts from a copy of pane ``wanted``'s chat.++ The new pane runs the same CLI on the same account (its conversation+ lives in that account's history) with the same picks, beside the+ original. Its first process copies the conversation through the CLI's+ own fork (:func:`.agent_sessions.fork_argv`); a CLI without one, or a+ pane with nothing said yet, gives a fresh chat instead.++ ``worktree=True`` first creates a git worktree on a new branch called+ ``name`` (:func:`.fork.create_worktree`) and runs the new pane there,+ so the two agents can change files without touching each other's work.+ """+ found = self._locate(wanted, workspace_id)+ if found is None:+ raise self._unknown_terminal(wanted)+ session, source = found+ if not accepts_prompts(source.agent):+ raise SessionError(f"{source.name} is a plain terminal — it has no chat to fork.")+ # Checked before a worktree is created, so a full workspace does not+ # leave an orphaned branch behind.+ if len(session.terminals) >= MAX_TERMINALS:+ raise SessionError(+ f"This workspace already has the maximum of {MAX_TERMINALS} terminals."+ )+ folder = ""+ branch = ""+ if worktree:+ base = source.cwd(session.folder)+ wanted_name = (name or "").strip() or await asyncio.to_thread(+ fork.suggest_name, base, source.name, recap_engine.known_headline(source)+ )+ try:+ created = await asyncio.to_thread(fork.create_worktree, base, wanted_name)+ except fork.ForkError as exc:+ raise SessionError(str(exc)) from exc+ folder, branch = str(created.folder), created.branch+ term = await self.add_terminal(+ workspace_id=session.id,+ agent=source.agent,+ anchor=source.name,+ direction=direction,+ account=source.account,+ model=source.model,+ effort=source.effort,+ permission_mode=source.permission_mode,+ )+ # No await between the pane's creation and these, so no viewer can+ # attach (and spawn) before the pane knows it is a fork.+ term.folder = folder+ term.branch = branch+ term.fork_from = source.resume+ await self._persist()+ logger.info(+ "Agentic IDE: forked {} into {}{}",+ source.name,+ term.name,+ f" on worktree branch {branch}" if branch else "",+ )+ return term+async def add_terminals(self,count: int,diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex f961e93c53..9461db0c0f 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -267,6 +267,22 @@ class StartSessionRequest(BaseModel):)+class ForkTerminalRequest(BaseModel):+ workspace_id: str | None = Field(default=None, description="Workspace the pane is in.")+ worktree: bool = Field(+ default=False,+ description=(+ "False copies the chat into a new pane in the same folder; true first "+ "creates a git worktree on a new branch and runs the copy there."+ ),+ )+ name: str | None = Field(+ default=None,+ description="Branch and worktree name (worktree forks only); suggested when omitted.",+ )+ direction: str = Field(default="right", description="Where the fork opens beside the pane.")++class AddTerminalRequest(BaseModel):workspace_id: str | None = Field(default=None, description="Workspace to add the session to.")agent: str | None = Field(@@ -2659,6 +2675,42 @@ async def add_terminal(req: AddTerminalRequest) -> dict:return {"ok": True, "terminal": term.to_dict(), "state": get_registry().state()}[email protected]("/terminals/{name}/fork", summary="What a fork of a terminal would be called")+async def fork_suggestion(name: str, workspace_id: str | None = None) -> dict:+ """The worktree name the fork dialog pre-fills, and whether a fork can copy the chat.++ ``in_repo`` is false outside a git checkout — the dialog then offers only+ the chat fork. ``can_fork`` is false for a CLI without a fork of its own,+ whose "fork" is a fresh chat of the same CLI.+ """+ try:+ suggestion = await asyncio.to_thread(get_registry().fork_suggestion, name, workspace_id)+ except SessionError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ return {"ok": True, **suggestion}++[email protected]("/terminals/{name}/fork", summary="Fork a terminal's chat into a new terminal")+async def fork_terminal(name: str, req: ForkTerminalRequest) -> dict:+ """Open a new pane that continues a copy of this pane's conversation.++ Same CLI, account, model, effort and permission stance, opened beside the+ original. With ``worktree`` the copy runs in a new git worktree on branch+ ``name``, so both agents can edit files without colliding.+ """+ try:+ term = await get_registry().fork_terminal(+ name,+ workspace_id=req.workspace_id,+ worktree=req.worktree,+ name=req.name,+ direction=req.direction,+ )+ except SessionError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"ok": True, "terminal": term.to_dict(), "state": get_registry().state()}++@router.post("/terminals/batch", summary="Open several terminals at once")async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:"""Open ``count`` more terminals in the running workspace.diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 528236ec16..fa4ee05aff 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -435,6 +435,10 @@ interface AgenticTerminalProps {displayName: string;/** Compact workspace chrome is opt-in; legacy grids retain their existing header. */headerMode?: "legacy" | "compact";+ /** Compact header only: opens the fork dialog for this pane. */+ onFork?: () => void;+ /** Compact header only: the worktree branch this pane runs on, if any. */+ branch?: string;/** Registry identity and optional custom logo for the compact header. */agent?: string;agentLogoUrl?: string;@@ -563,6 +567,8 @@ export function AgenticTerminal({workspaceId,displayName,headerMode = "legacy",+ onFork,+ branch,agent,agentLogoUrl,recap,@@ -2368,6 +2374,8 @@ export function AgenticTerminal({onOpenConversation={() => setHistoryOpen(true)}onOpenChat={onOpenChat}onRestart={onRestart}+ onFork={onFork}+ branch={branch}/> : <PaneHeaderworkspaceId={workspaceId}status={visibleStatus}diff --git a/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.test.tsxnew file mode 100644index 0000000000..e211c1386e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.test.tsx@@ -0,0 +1,51 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { ForkPaneDialog } from "./ForkPaneDialog";++const SOURCE = { name: "T3", agent: "claude", displayName: "Claude Code", workspaceId: "w1" };++function suggest(body: Record<string, unknown>) {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({+ ok: true, name: "t3-fix-the-login-test", in_repo: true, can_fork: true, has_conversation: true, ...body,+ }), { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++it("forks the chat by default, without asking for a name", async () => {+ const fetchMock = suggest({});+ const onConfirm = vi.fn();+ render(<ForkPaneDialog source={SOURCE} busy={false} onCancel={vi.fn()} onConfirm={onConfirm} />);+ expect(screen.getByRole("dialog", { name: "Fork T3" })).toBeTruthy();+ await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/api/agentic-ide/terminals/T3/fork?workspace_id=w1"));+ expect(screen.queryByTestId("fork-branch-name")).toBeNull();+ fireEvent.click(screen.getByTestId("fork-confirm"));+ expect(onConfirm).toHaveBeenCalledWith({ mode: "chat", branch: "t3-fix-the-login-test" });+});++it("pre-fills a worktree name that matches the pane, and lets it be changed", async () => {+ suggest({});+ const onConfirm = vi.fn();+ render(<ForkPaneDialog source={SOURCE} busy={false} onCancel={vi.fn()} onConfirm={onConfirm} />);+ fireEvent.click(screen.getByTestId("fork-mode-worktree"));+ const input = await screen.findByTestId("fork-branch-name") as HTMLInputElement;+ await waitFor(() => expect(input.value).toBe("t3-fix-the-login-test"));+ fireEvent.change(input, { target: { value: " t3-other-idea " } });+ fireEvent.click(screen.getByRole("button", { name: "Fork into worktree" }));+ expect(onConfirm).toHaveBeenCalledWith({ mode: "worktree", branch: "t3-other-idea" });+});++it("offers no worktree outside a git repository and says why", async () => {+ suggest({ in_repo: false });+ render(<ForkPaneDialog source={SOURCE} busy={false} onCancel={vi.fn()} onConfirm={vi.fn()} />);+ await screen.findByText(/Needs a git repository/);+ expect((screen.getByTestId("fork-mode-worktree") as HTMLButtonElement).disabled).toBe(true);+});++it("says so when the CLI cannot copy its conversation", async () => {+ suggest({ can_fork: false });+ render(<ForkPaneDialog source={{ ...SOURCE, displayName: "Kimi Code" }} busy={false} onCancel={vi.fn()} onConfirm={vi.fn()} />);+ await screen.findByText(/Kimi Code cannot copy its conversation/);+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.tsxnew file mode 100644index 0000000000..05c9d26a8b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/ForkPaneDialog.tsx@@ -0,0 +1,159 @@+import { useEffect, useRef, useState } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { FolderGit2, GitFork, Loader2, MessagesSquare } from "lucide-react";+import { AgentMark } from "./AgentMark";+import { fetchForkSuggestion, type ForkSuggestion } from "@/lib/agenticIdeApi";+import { cn } from "@/lib/utils";++/** The pane a fork is being made of. */+export interface ForkSource {+ name: string;+ agent: string;+ displayName: string;+ workspaceId?: string;+}++export type ForkMode = "chat" | "worktree";++interface Props {+ source: ForkSource | null;+ busy: boolean;+ onCancel: () => void;+ onConfirm: (choice: { mode: ForkMode; branch: string }) => void;+}++/**+ * Fork a pane: a new agent beside it that continues a copy of its chat —+ * either in the same folder, or in a fresh git worktree on its own branch.+ * The worktree name is pre-filled with a free name derived from the pane+ * (call-sign plus what it is working on), and stays editable.+ */+export function ForkPaneDialog({ source, busy, onCancel, onConfirm }: Props) {+ const [mode, setMode] = useState<ForkMode>("chat");+ const [branch, setBranch] = useState("");+ const [info, setInfo] = useState<ForkSuggestion | null>(null);+ const [loadError, setLoadError] = useState("");+ const nameRef = useRef<HTMLInputElement>(null);+ const sourceName = source?.name;+ const sourceWorkspace = source?.workspaceId;++ useEffect(() => {+ setMode("chat");+ setBranch("");+ setInfo(null);+ setLoadError("");+ if (!sourceName) return;+ let live = true;+ fetchForkSuggestion(sourceName, sourceWorkspace)+ .then((next) => {+ if (!live) return;+ setInfo(next);+ setBranch(next.name);+ })+ .catch((error: unknown) => {+ if (live) setLoadError(error instanceof Error ? error.message : String(error));+ });+ return () => { live = false; };+ }, [sourceName, sourceWorkspace]);++ useEffect(() => {+ if (mode === "worktree") nameRef.current?.select();+ }, [mode]);++ const worktreeOff = info !== null && !info.in_repo;+ const trimmed = branch.trim();+ const canSubmit = !busy && (mode === "chat" || (trimmed !== "" && !worktreeOff && info !== null));+ const submit = () => { if (canSubmit) onConfirm({ mode, branch: trimmed }); };++ const options: { mode: ForkMode; title: string; body: string; Icon: typeof GitFork; disabled: boolean }[] = [+ {+ mode: "chat",+ title: "Fork chat",+ body: "A new agent opens beside this one and continues a copy of the conversation, in the same folder.",+ Icon: MessagesSquare,+ disabled: false,+ },+ {+ mode: "worktree",+ title: "Fork into a worktree",+ body: worktreeOff+ ? "Needs a git repository — this folder is not one."+ : "Same copy of the conversation, but in its own git worktree and branch, so both agents can change files without getting in each other's way.",+ Icon: FolderGit2,+ disabled: worktreeOff,+ },+ ];++ return <Dialog.Root open={source !== null} onOpenChange={(open) => { if (!open && !busy) onCancel(); }}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-background/70 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0" />+ <Dialog.Content data-testid="fork-pane-dialog"+ className="fixed left-1/2 top-1/2 z-[90] w-[min(460px,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-2xl data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95">+ <form onSubmit={(event) => { event.preventDefault(); submit(); }}>+ <div className="flex items-start gap-4">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">+ <GitFork className="h-[18px] w-[18px]" aria-hidden />+ </div>+ <div className="min-w-0 flex-1">+ <Dialog.Title className="truncate text-base font-semibold">Fork {source?.name}</Dialog.Title>+ <Dialog.Description className="mt-1.5 text-sm leading-relaxed text-muted-foreground">+ Start a second agent from where this one is. The original keeps running unchanged.+ </Dialog.Description>+ </div>+ </div>++ {source && <div className="mt-4 flex items-center gap-2.5 rounded-xl border border-border bg-muted/40 px-3 py-2.5">+ <AgentMark agent={source.agent} label={source.displayName} variant="plain" size="sm" />+ <span className="truncate text-sm font-medium">{source.displayName}</span>+ <span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground">{source.name}</span>+ </div>}++ <div role="radiogroup" aria-label="How to fork" className="mt-4 grid gap-2">+ {options.map((option) => {+ const checked = mode === option.mode;+ return <button key={option.mode} type="button" role="radio" aria-checked={checked}+ data-testid={`fork-mode-${option.mode}`} disabled={option.disabled || busy}+ onClick={() => setMode(option.mode)}+ className={cn(+ "flex items-start gap-3 rounded-xl border px-3 py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",+ checked ? "border-primary bg-primary/5" : "border-border hover:bg-muted/60",+ )}>+ <option.Icon className={cn("mt-0.5 h-4 w-4 shrink-0", checked ? "text-primary" : "text-muted-foreground")} aria-hidden />+ <span className="min-w-0">+ <span className="block text-sm font-medium">{option.title}</span>+ <span className="mt-0.5 block text-xs leading-relaxed text-muted-foreground">{option.body}</span>+ </span>+ </button>;+ })}+ </div>++ {mode === "worktree" && <div className="mt-4">+ <label htmlFor="fork-branch-name" className="text-xs font-medium text-muted-foreground">Worktree and branch name</label>+ <input id="fork-branch-name" ref={nameRef} data-testid="fork-branch-name" value={branch} disabled={busy || info === null}+ onChange={(event) => setBranch(event.target.value)} spellCheck={false} autoComplete="off" maxLength={80}+ placeholder={info === null ? "Finding a name…" : undefined}+ className="mt-1.5 w-full rounded-lg border border-border bg-background px-3 py-2 font-mono text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60" />+ <p className="mt-1.5 text-xs leading-relaxed text-muted-foreground">+ Created from the last commit. Changes that are not committed yet stay in the current folder.+ </p>+ </div>}++ {info && !info.can_fork && <p className="mt-4 text-xs leading-relaxed text-muted-foreground">+ {source?.displayName} cannot copy its conversation, so the fork starts with a fresh chat.+ </p>}+ {loadError && <p role="alert" className="mt-4 text-xs text-destructive">{loadError}</p>}++ <div className="mt-6 flex justify-end gap-2">+ <button type="button" disabled={busy} onClick={onCancel}+ className="rounded-lg border border-border px-3.5 py-2 text-sm font-medium hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-40">+ Cancel</button>+ <button type="submit" data-testid="fork-confirm" disabled={!canSubmit}+ className="flex items-center gap-1.5 rounded-lg bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover disabled:opacity-50">+ {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}+ {mode === "worktree" ? "Fork into worktree" : "Fork chat"}</button>+ </div>+ </form>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsxindex 511fdfc3a7..0f59e21c8e 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalGrid.tsx@@ -1,9 +1,10 @@import { useCallback, useEffect, useRef, useState } from "react";import { AgenticTerminal } from "./AgenticTerminal";import { AgentMark } from "./AgentMark";+import { ForkPaneDialog, type ForkMode, type ForkSource } from "./ForkPaneDialog";import type { PaneSplitDirection } from "./WorkspaceTerminalHeader";import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";-import { moveTerminal, renameTerminal, type PaneMovePosition } from "@/lib/agenticIdeApi";+import { forkTerminal, moveTerminal, renameTerminal, type PaneMovePosition } from "@/lib/agenticIdeApi";import { useThemeValue } from "@/hooks/useTheme";import { useEventStore } from "@/store/events";import { useIdeSidePanelStore } from "@/store/ideSidePanel";@@ -49,6 +50,8 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSeconst [maximized, setMaximized] = useState<string | null>(null);const [restarts, setRestarts] = useState<Record<string, number>>({});const [announcement, setAnnouncement] = useState("");+ const [forking, setForking] = useState<ForkSource | null>(null);+ const [forkBusy, setForkBusy] = useState(false);const dragCleanup = useRef<(() => void) | null>(null);const saveInFlight = useRef(false);const mounted = useRef(true);@@ -187,6 +190,29 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe} catch (error) { pushToast("error", (error as Error).message); return false; }finally { latest.current.onMutationEnd?.(); }};+ // A fork opens beside its source; the new pane becomes the selected one,+ // because it was opened to be worked with next.+ const fork = async ({ mode, branch }: { mode: ForkMode; branch: string }) => {+ if (!forking) return;+ const owner = latest.current.session;+ setForkBusy(true);+ latest.current.onMutationStart?.();+ try {+ const { session: next, terminal } = await forkTerminal(forking.name, {+ workspaceId: owner.id, worktree: mode === "worktree", branch: mode === "worktree" ? branch : undefined,+ });+ if (!mounted.current) return;+ setForking(null);+ if (next.id !== latest.current.session.id) return;+ latest.current.onChanged(next);+ latest.current.onSelect(terminal.name);+ setAnnouncement(terminal.branch ? `${forking.name} forked into ${terminal.name} on branch ${terminal.branch}.` : `${forking.name} forked into ${terminal.name}.`);+ } catch (error) { pushToast("error", (error as Error).message); }+ finally {+ latest.current.onMutationEnd?.();+ if (mounted.current) setForkBusy(false);+ }+ };const dragged = drag ? session.terminals.find((terminal) => idOf(terminal) === drag.id) : null;// A pane picked from the side panel may sit off-screen on a narrow grid.@@ -243,7 +269,9 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSeonClose={() => onClose(terminal)} onAttachError={(message) => pushToast("error", message)}onRename={(name) => rename(terminal, name)}restartToken={restarts[id] ?? 0} onRestart={() => setRestarts((current) => ({ ...current, [id]: (current[id] ?? 0) + 1 }))}- splitDisabled={tiles.length >= maxPanes} onSplit={(direction) => onAdd(terminal.name, direction)} />+ splitDisabled={tiles.length >= maxPanes} onSplit={(direction) => onAdd(terminal.name, direction)}+ branch={terminal.branch || undefined}+ onFork={terminal.accepts_prompts === false ? undefined : () => setForking({ name: terminal.name, agent: terminal.agent, displayName: terminal.display_name, workspaceId: session.id })} />{drag?.target?.id === id && <div aria-hidden="true" data-testid="dock-preview" data-position={drag.target.position}className={cn("pointer-events-none absolute z-20 flex items-center justify-center rounded-xl border-2 p-2", drag.target.allowed ? "border-ring/70 bg-accent/[0.15]" : "border-destructive bg-background/80",drag.target.position === "left" ? "inset-y-1 left-1 w-1/2" : drag.target.position === "right" ? "inset-y-1 right-1 w-1/2" : drag.target.position === "above" ? "inset-x-1 top-1 h-1/2" : drag.target.position === "below" ? "inset-x-1 bottom-1 h-1/2" : "inset-1")}>@@ -257,5 +285,6 @@ export function WorkspaceTerminalGrid({ session, onChanged, onAdd, onClose, onSe<AgentMark agent={dragged.agent} label={dragged.display_name} variant="plain" />{dragged.name}</div>}<span className="sr-only" role="status">{announcement}</span>+ <ForkPaneDialog source={forking} busy={forkBusy} onCancel={() => setForking(null)} onConfirm={(choice) => void fork(choice)} /></div>;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsxindex f2fb4be53c..b102bc85af 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.test.tsx@@ -10,6 +10,17 @@ function pressPointer(target: Element, button = 0) {}describe("compact workspace terminal header", () => {+ it("offers a fork button and menu entry, and shows a worktree fork's branch", () => {+ const fork = vi.fn();+ render(<WorkspaceTerminalHeader {...BASE} onFork={fork} branch="dana-fix-login" />);+ fireEvent.click(screen.getByRole("button", { name: "Fork Dana" }));+ expect(fork).toHaveBeenCalledTimes(1);+ expect(screen.getByTestId("pane-branch-Dana").textContent).toBe("dana-fix-login");+ fireEvent.click(screen.getByRole("button", { name: "More actions for Dana" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Fork…" }));+ expect(fork).toHaveBeenCalledTimes(2);+ });+it("uses the name and accurate status without a verbose toolbar", () => {render(<WorkspaceTerminalHeader {...BASE} onOpenConversation={() => {}} />);const header = screen.getByTestId("workspace-terminal-header-Dana");diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsxindex 361079a855..8dc3fefdf3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx@@ -1,6 +1,6 @@import { useEffect, useId, useLayoutEffect, useRef, useState, type ComponentType, type CSSProperties, type MouseEvent, type PointerEvent, type SVGProps } from "react";import { createPortal } from "react-dom";-import { Check, Maximize2, Minimize2, MoreHorizontal, Plus, X } from "lucide-react";+import { Check, GitBranch, GitFork, Maximize2, Minimize2, MoreHorizontal, Plus, X } from "lucide-react";import { AgentMark } from "./AgentMark";import { usePaneTitle } from "@/store/paneRecaps";import { PromptHistoryButton } from "./PromptHistoryButton";@@ -30,6 +30,10 @@ interface Props {onOpenConversation?: () => void;onOpenChat?: () => void;onRestart?: () => void;+ /** Opens the fork dialog: a new agent continuing a copy of this pane's chat. */+ onFork?: () => void;+ /** The git worktree branch this pane runs on, when it is a worktree fork. */+ branch?: string;}type MenuIcon = ComponentType<SVGProps<SVGSVGElement>>;@@ -48,7 +52,7 @@ const ACTION_CLASS = "flex h-7 w-7 shrink-0 items-center justify-center roundedexport function WorkspaceTerminalHeader({name, workspaceId, promptCount = 0, agent, agentLogoUrl, displayName, status, appearance, arranging = false,maximized = false, addDisabled = false, onArrangeStart, onActivate, onToggleMaximize,- onAdd, onClose, onRename, onOpenConversation, onOpenChat, onRestart,+ onAdd, onClose, onRename, onOpenConversation, onOpenChat, onRestart, onFork, branch,}: Props) {const brand = PANE_BRAND[appearance];// The pane's goal in a few words, in place of its call-sign; the call-sign@@ -147,6 +151,10 @@ export function WorkspaceTerminalHeader({<AgentMark agent={agent} label={displayName} logoUrl={agentLogoUrl} variant="plain" size="sm"className="!text-[color:var(--pane-ink)] [&>.bg-foreground]:!bg-[color:var(--pane-ink)]" /><span data-testid={`pane-title-${name}`} title={title ? `${title} (${name})` : name} className="truncate">{title || name}</span>+ {branch && <span data-testid={`pane-branch-${name}`} title={`Runs in its own git worktree on branch ${branch}`}+ className="flex min-w-0 max-w-[45%] shrink items-center gap-1 rounded bg-[color:var(--pane-chip)] px-1.5 py-0.5 font-mono text-[11px] font-normal text-[color:var(--pane-ink-muted)]">+ <GitBranch className="h-3 w-3 shrink-0" aria-hidden="true" /><span className="truncate">{branch}</span>+ </span>}</button> : <form data-header-control="true" className="flex min-w-0 flex-1 items-center gap-1"onSubmit={(event) => { event.preventDefault(); void commitRename(); }}><input autoFocus aria-label={`Name for ${name}`} value={draft} maxLength={40} disabled={saving}@@ -166,6 +174,8 @@ export function WorkspaceTerminalHeader({className={ACTION_CLASS}><MoreHorizontal className="h-4 w-4" /></button><button type="button" aria-label={`${maximized ? "Restore" : "Maximize"} ${name}`} disabled={!onToggleMaximize}onClick={onToggleMaximize} className={ACTION_CLASS}>{maximized ? <Minimize2 className="h-3.5 w-3.5" /> : <Maximize2 className="h-3.5 w-3.5" />}</button>+ {onFork && <button type="button" data-testid={`pane-fork-${name}`} aria-label={`Fork ${name}`} title={`Fork ${name}`}+ disabled={addDisabled} onClick={onFork} className={ACTION_CLASS}><GitFork className="h-3.5 w-3.5" /></button>}<button type="button" aria-label={`Add agent beside ${name}`} disabled={addDisabled || !onAdd}onClick={() => onAdd?.("right")} className={ACTION_CLASS}><Plus className="h-4 w-4" /></button><button type="button" aria-label={`Close ${name}`} disabled={!onClose} onClick={onClose} className={ACTION_CLASS}><X className="h-4 w-4" /></button>@@ -191,6 +201,7 @@ export function WorkspaceTerminalHeader({}}>{([onRename && { label: "Rename", run: () => { setDraft(name); setRenameError(""); } },+ onFork && !addDisabled && { label: "Fork…", Icon: GitFork, run: onFork },...(onAdd && !addDisabled ? SPLIT_ITEMS.map((item, index) => ({label: `${item.label}…`, Icon: item.Icon, separated: index === 0, run: () => onAdd(item.direction),})) : []),diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex ad398e9885..7135190ef2 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -227,6 +227,12 @@ export interface TerminalState {account?: string | null;/** Its display name, so the pane header can show it without a second lookup. */account_label?: string | null;+ /** Set only for a pane running in a git worktree of its own (a worktree fork). */+ folder?: string;+ /** That worktree's branch, shown in the pane header. */+ branch?: string;+ /** Can a fork of this pane copy its chat? False: the fork starts a fresh chat. */+ can_fork?: boolean;/*** What this pane is doing, in one clause — the pane header's label.*@@ -1524,6 +1530,58 @@ export async function renameTerminal(return body.state.session;}+/** What the fork dialog pre-fills for a pane, and what a fork of it can do. */+export interface ForkSuggestion {+ /** A free branch/worktree name that reads like the pane, e.g. "t3-fix-login". */+ name: string;+ /** False outside a git checkout: only the chat fork is possible. */+ in_repo: boolean;+ /** False for a CLI without its own fork: the fork starts a fresh chat. */+ can_fork: boolean;+ /** Whether the pane holds a conversation handle at all yet. */+ has_conversation: boolean;+}++export async function fetchForkSuggestion(+ name: string,+ workspaceId?: string,+): Promise<ForkSuggestion> {+ const query = workspaceId ? `?workspace_id=${encodeURIComponent(workspaceId)}` : "";+ const res = await fetch(+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/fork${query}`,+ );+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as ForkSuggestion;+}++/**+ * Open a new pane beside `name` that continues a copy of its chat. With+ * `worktree`, the copy runs in a new git worktree on branch `branch`.+ * Returns the updated workspace and the new pane's call-sign.+ */+export async function forkTerminal(+ name: string,+ options: { workspaceId?: string; worktree: boolean; branch?: string },+): Promise<{ session: SessionState; terminal: TerminalState }> {+ const res = await fetch(+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/fork`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ workspace_id: options.workspaceId,+ worktree: options.worktree,+ name: options.branch,+ }),+ },+ );+ if (!res.ok) throw new Error(await detail(res));+ const body = (await res.json()) as { state: IdeState; terminal: TerminalState };+ if (!body.state.session)+ throw new Error("The workspace closed while forking a terminal.");+ return { session: body.state.session, terminal: body.terminal };+}+/** Stop one terminal's agent and remove its pane. Returns the updated workspace. */export async function closeTerminal(name: string,diff --git a/tests/unit/agentic_ide/test_pane_fork.py b/tests/unit/agentic_ide/test_pane_fork.pynew file mode 100644index 0000000000..9ea89bfec1--- /dev/null+++ b/tests/unit/agentic_ide/test_pane_fork.py@@ -0,0 +1,181 @@+"""Forking a pane: a new pane that starts from a copy of another pane's chat.++Pins three things: the fork's FIRST process gets the CLI's own fork argv (and+only the first — a restart resumes the copy), a worktree fork runs in a fresh+git worktree on its own branch, and the suggested name reads like the pane.+"""++from __future__ import annotations++import asyncio+import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.agentic_ide import agent_sessions, fork, resume_store+from jarvis.agentic_ide import session as ide+from jarvis.agentic_ide.agent_sessions import ResumeHandle+from tests.fakes.fake_pty_manager import FakePtyManager++needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")+++def fake_pty() -> FakePtyManager:+ return FakePtyManager()+++def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> ide.Registry:+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ return ide.Registry(pty_manager=fake_pty)+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++def _git_repo(path: Path) -> Path:+ path.mkdir(parents=True, exist_ok=True)+ run = {"cwd": path, "check": True, "capture_output": True}+ subprocess.run(["git", "init", "-q", "-b", "main"], **run)+ (path / "README.md").write_text("hello\n", encoding="utf-8")+ subprocess.run(["git", "add", "README.md"], **run)+ subprocess.run(+ ["git", "-c", "user.name=t", "-c", "[email protected]", "commit", "-qm", "init"],+ **run,+ )+ return path+++# ------------------------------------------------------------------ argv+def test_claude_fork_assigns_the_copy_its_own_id() -> None:+ source = ResumeHandle(kind="claude_session", id="old-id", captured_at=1.0)+ argv, minted = agent_sessions.fork_argv("claude", source)+ assert argv[:3] == ("--resume", "old-id", "--fork-session")+ assert minted is not None and minted.id != "old-id"+ assert argv[3:] == ("--session-id", minted.id)+++def test_codex_fork_is_a_subcommand_and_discovered_later() -> None:+ source = ResumeHandle(kind="codex_rollout", id="abc", captured_at=1.0)+ assert agent_sessions.fork_argv("codex", source) == (("fork", "abc"), None)+++def test_a_handle_of_the_wrong_kind_is_never_forked() -> None:+ source = ResumeHandle(kind="codex_rollout", id="abc", captured_at=1.0)+ assert agent_sessions.fork_argv("claude", source) is None+ assert agent_sessions.fork_argv("claude", None) is None+++# ------------------------------------------------------------------ chat fork+async def test_a_chat_fork_starts_as_a_copy_then_resumes_the_copy(+ registry: ide.Registry,+ fake_pty: FakePtyManager,+ tmp_path: Path,+ existing_conversation,+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ source = registry.session.find("T1")+ source.resume = ResumeHandle(kind="claude_session", id="source-id", captured_at=1.0)+ existing_conversation("source-id")++ forked = await registry.fork_terminal("T1")+ assert forked.agent == "claude" and forked.account == source.account+ assert forked.folder == "" and forked.branch == ""++ await registry.attach(forked.name, 80, 24, _noop, _noop_exit)+ argv = fake_pty.spawns[-1]["argv"]+ assert ("--resume", "source-id", "--fork-session") == argv[-5:-2]+ assert forked.resume is not None and forked.resume.id == argv[-1]+ assert forked.fork_from is None, "the fork is spent by the first process"++ # A restart continues the COPY, never forks the original a second time.+ existing_conversation(forked.resume.id)+ await fake_pty.die(forked.pty_id, 0)+ await registry.attach(forked.name, 80, 24, _noop, _noop_exit)+ assert fake_pty.spawns[-1]["argv"][-2:] == ("--resume", forked.resume.id)+++async def test_a_fork_of_a_pane_with_no_conversation_starts_fresh(+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ registry.session.find("T1").resume = ResumeHandle(+ kind="claude_session", id="never-spoken-to", captured_at=1.0+ )+ forked = await registry.fork_terminal("T1")+ await registry.attach(forked.name, 80, 24, _noop, _noop_exit)+ argv = fake_pty.spawns[-1]["argv"]+ assert "--fork-session" not in argv and "--session-id" in argv+ assert forked.resumed is False+++# ------------------------------------------------------------------ worktree fork+@needs_git+async def test_a_worktree_fork_runs_in_a_new_worktree_on_its_own_branch(+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ repo = _git_repo(tmp_path / "repo")+ await registry.start(str(repo), [{"agent": "claude", "name": "T1"}])++ forked = await registry.fork_terminal("T1", worktree=True, name="t1-try other")+ assert forked.branch == "t1-try-other"+ worktree = repo / fork.WORKTREE_DIR / "t1-try-other"+ assert Path(forked.folder) == worktree and (worktree / "README.md").is_file()++ await registry.attach(forked.name, 80, 24, _noop, _noop_exit)+ assert Path(fake_pty.spawns[-1]["cwd"]) == worktree+ # The worktree folder never shows up as untracked files in the original.+ status = await asyncio.to_thread(+ subprocess.run,+ ["git", "status", "--porcelain"],+ cwd=repo,+ capture_output=True,+ text=True,+ check=True,+ )+ assert status.stdout.strip() == ""++ # And the pane comes back in its worktree after a restart.+ snap = resume_store.SnapshotTerminal.from_dict(forked.to_snapshot().to_dict())+ assert snap is not None and snap.folder == forked.folder and snap.branch == "t1-try-other"+++@needs_git+async def test_a_taken_branch_name_is_refused_before_any_pane_opens(+ registry: ide.Registry, tmp_path: Path+) -> None:+ repo = _git_repo(tmp_path / "repo")+ await registry.start(str(repo), [{"agent": "claude", "name": "T1"}])+ with pytest.raises(ide.SessionError, match="already exists"):+ await registry.fork_terminal("T1", worktree=True, name="main")+ assert len(registry.session.terminals) == 1+++async def test_a_worktree_fork_outside_git_says_why(registry: ide.Registry, tmp_path: Path) -> None:+ folder = tmp_path / "plain"+ folder.mkdir()+ await registry.start(str(folder), [{"agent": "claude", "name": "T1"}])+ with pytest.raises(ide.SessionError, match="not a git repository"):+ await registry.fork_terminal("T1", worktree=True, name="x")+++# ------------------------------------------------------------------ naming+def test_the_suggested_name_reads_like_the_pane() -> None:+ assert fork.base_name("T3", "Fix the login test") == "t3-fix-the-login-test"+ assert fork.base_name("T3", "") == "t3-fork"+ assert fork.base_name("Frontend", "Frontend") == "frontend-fork"+++@needs_git+def test_the_suggestion_skips_names_already_taken(tmp_path: Path) -> None:+ repo = _git_repo(tmp_path / "repo")+ fork.create_worktree(repo, "t1-fork")+ assert fork.suggest_name(repo, "T1") == "t1-fork-2"