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(ide): show session changes an agent made in its own worktrees (#870)

Ruben Lütke1ec1345da02d
diff --git a/dodaios/agentic_ide/pane_changes.py b/dodaios/agentic_ide/pane_changes.py
index 187656b50c..3c323f8172 100644
--- a/dodaios/agentic_ide/pane_changes.py
+++ b/dodaios/agentic_ide/pane_changes.py
@@ -443,6 +443,88 @@ def generated_paths(folder: str | Path, paths: set[str]) -> set[str]:
return found
+def _worktree_roots(root: Path) -> list[Path]:
+ """Every checkout of the repository ``root`` belongs to, per ``git worktree list``."""
+ result = _git(["worktree", "list", "--porcelain"], root)
+ if result is None or result.returncode != 0:
+ return []
+ roots: list[Path] = []
+ for line in result.stdout.splitlines():
+ if line.startswith("worktree "):
+ roots.append(Path(line[len("worktree ") :].strip()).resolve(strict=False))
+ return roots
+
+
+def _path_forms(path: Path) -> list[str]:
+ """How a shell command may spell ``path``: ``C:\\a\\b``, ``C:/a/b``, ``/c/a/b``; lowercase."""
+ text = str(path)
+ slashed = text.replace("\\", "/")
+ forms = {text.lower(), slashed.lower()}
+ if len(slashed) > 2 and slashed[1] == ":":
+ forms.add(f"/{slashed[0]}{slashed[2:]}".lower())
+ return sorted(forms)
+
+
+def _inside(path: Path, root: Path) -> bool:
+ return path.is_relative_to(root)
+
+
+def agent_worktrees(
+ folder: str | Path, events: list[dict[str, Any]], record_folder: str | Path | None = None
+) -> list[tuple[str, Path]]:
+ """``(worktree name, folder)`` of the other checkouts the agent worked in, busiest first.
+
+ An agent may start in the shared folder and then do its work in worktrees
+ of its own (``git worktree add``). Its edits and commits then live there,
+ and the shared folder shows none of them. A checkout counts when the
+ agent's editing tools wrote into it or its shell commands name it. Each
+ answer is the worktree's counterpart of ``folder`` (a workspace below the
+ repository root keeps its place).
+ """
+ root = Path(folder).expanduser().resolve(strict=False)
+ _is_repo, prefix, _reason = _repo_prefix(root)
+ trees = _worktree_roots(root)
+ if len(trees) < 2:
+ return []
+ deepest_first = sorted(trees, key=lambda tree: len(tree.parts), reverse=True)
+ here = next((tree for tree in deepest_first if _inside(root, tree)), None)
+ others = [tree for tree in trees if tree != here]
+ base = Path(record_folder or root).expanduser()
+ scores: dict[Path, int] = dict.fromkeys(others, 0)
+ for raw in change_authors.write_spans(events):
+ candidate = Path(raw.strip().strip('"'))
+ if not candidate.is_absolute():
+ candidate = base / candidate
+ candidate = candidate.resolve(strict=False)
+ # The deepest checkout holding the file owns it: a worktree may sit inside the folder.
+ owner = max(
+ (tree for tree in trees if _inside(candidate, tree)),
+ key=lambda tree: len(tree.parts),
+ default=None,
+ )
+ if owner is not None and owner in scores:
+ scores[owner] += 1
+ forms = {tree: _path_forms(tree) for tree in others}
+ for event in events:
+ payload = event.get("payload") or {}
+ if event.get("kind") != "tool_call":
+ continue
+ if not _SHELL_TOOL.search(str(payload.get("name") or "")):
+ continue
+ text = _command_text(payload.get("input")).lower()
+ if not text:
+ continue
+ for tree in others:
+ if any(form in text for form in forms[tree]):
+ scores[tree] += 1
+ found: list[tuple[str, Path]] = []
+ for tree in sorted(others, key=lambda tree: (-scores[tree], str(tree))):
+ target = tree / prefix if prefix else tree
+ if scores[tree] > 0 and target.is_dir():
+ found.append((tree.name, target))
+ return found
+
+
def pane_work(
folder: str | Path, events: list[dict[str, Any]], record_folder: str | Path | None = None
) -> PaneWork:
@@ -478,6 +560,7 @@ __all__ = [
"PaneListing",
"PaneWork",
"agent_commit_refs",
+ "agent_worktrees",
"commit_files",
"generated_paths",
"pane_changes",
diff --git a/dodaios/ui/web/agentic_ide_routes.py b/dodaios/ui/web/agentic_ide_routes.py
index 01084957e0..df7777a2bd 100644
--- a/dodaios/ui/web/agentic_ide_routes.py
+++ b/dodaios/ui/web/agentic_ide_routes.py
@@ -63,7 +63,7 @@ import os
import re
import time
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import asdict
+from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Annotated, Any, Literal, get_args
@@ -1003,6 +1003,11 @@ class PaneChangedFileItem(ChangedFileItem):
diff: PaneFileDiffItem | None = Field(
default=None, description="Its diff against the base; null when it is read on demand."
)
+ checkout: str = Field(
+ default="",
+ description="The worktree the agent made and changed it in; empty: the pane folder.",
+ )
+ base: str = Field(default="", description="The commit this file is compared with.")
class PaneChangesResponse(BaseModel):
@@ -1865,28 +1870,101 @@ def _pane_of(workspace_id: str, name: str) -> tuple[Any, Any]:
return session, term
-def _read_pane_changes(
- folder: str, record: change_authors.PaneRecord | None
-) -> tuple[pane_changes.PaneWork, str | None, int, pane_changes.PaneListing]:
- """(the agent's work, the base it is compared with, generated files left out, listing)."""
- events: list[dict[str, Any]] = []
- if record is not None:
- try:
- events = (
- agent_transcript.read_events(record.agent, record.session_id, home=record.home)
- or []
- )
- except Exception as exc: # a record the CLI rewrote mid-read: an empty review this time
- log.info("Pane changes: %s record unreadable: %s", record.pane, exc)
- work = pane_changes.pane_work(folder, events, record.folder if record else None)
+def _pane_events(record: change_authors.PaneRecord | None) -> list[dict[str, Any]]:
+ if record is None:
+ return []
+ try:
+ return agent_transcript.read_events(record.agent, record.session_id, home=record.home) or []
+ except Exception as exc: # a record the CLI rewrote mid-read: an empty review this time
+ log.info("Pane changes: %s record unreadable: %s", record.pane, exc)
+ return []
+
+
+#: The worktrees each pane's agent made and worked in:
+#: ``{(workspace, pane): (monotonic s, [(name, folder), ...])}``.
+_agent_checkouts: dict[tuple[str, str], tuple[float, list[tuple[str, str]]]] = {}
+_AGENT_CHECKOUTS_TTL_S = 600.0
+
+
+def _agent_checkouts_of(
+ workspace_id: str,
+ session: Any,
+ term: Any,
+ events: list[dict[str, Any]] | None = None,
+) -> list[tuple[str, str]]:
+ """``(name, folder)`` of the worktrees a pane's agent made and worked in.
+
+ An agent may start in the shared folder and then work in worktrees it made
+ itself; the shared folder shows none of that work. A pane on a worktree of
+ its own is read there alone.
+ """
+ if term.folder:
+ return []
+ key = (workspace_id, term.name)
+ record = _pane_record(session, term)
+ if events is None:
+ cached = _agent_checkouts.get(key)
+ if cached is not None and time.monotonic() - cached[0] < _AGENT_CHECKOUTS_TTL_S:
+ return cached[1]
+ events = _pane_events(record)
+ found = pane_changes.agent_worktrees(
+ session.folder, events, record.folder if record else None
+ )
+ checkouts = [(name, str(folder)) for name, folder in found]
+ _agent_checkouts[key] = (time.monotonic(), checkouts)
+ return checkouts
+
+
+def _checkout_folder(workspace_id: str, session: Any, term: Any, checkout: str) -> str:
+ """The folder one review file lives in: the pane's own, or a worktree its agent made."""
+ if not checkout:
+ return str(term.folder or session.folder)
+ for name, folder in _agent_checkouts_of(workspace_id, session, term):
+ if name == checkout:
+ return folder
+ raise HTTPException(status_code=404, detail="This pane's agent did not work in that worktree.")
+
+
+@dataclass(slots=True)
+class _CheckoutReading:
+ """One checkout's share of a pane's review."""
+
+ checkout: str
+ work: pane_changes.PaneWork
+ base: str | None
+ generated: set[str]
+ listing: pane_changes.PaneListing
+
+
+def _read_checkout(
+ checkout: str, folder: str, events: list[dict[str, Any]], record_folder: str | None
+) -> _CheckoutReading:
+ work = pane_changes.pane_work(folder, events, record_folder)
with ThreadPoolExecutor(max_workers=2) as pool:
generated_job = pool.submit(pane_changes.generated_paths, folder, set(work.files))
base_job = pool.submit(pane_changes.session_base, folder, work.since_ms)
generated, base = generated_job.result(), base_job.result()
wanted = set(work.files) - generated
if not wanted or not base:
- return work, base if wanted else None, len(generated), pane_changes.PaneListing()
- return work, base, len(generated), pane_changes.pane_changes(folder, wanted, base)
+ empty = pane_changes.PaneListing()
+ return _CheckoutReading(checkout, work, base if wanted else None, generated, empty)
+ listing = pane_changes.pane_changes(folder, wanted, base)
+ return _CheckoutReading(checkout, work, base, generated, listing)
+
+
+def _read_pane_changes(workspace_id: str, session: Any, term: Any) -> list[_CheckoutReading]:
+ """The pane's folder first, then every worktree its agent made and worked in."""
+ record = _pane_record(session, term)
+ events = _pane_events(record)
+ record_folder = record.folder if record else None
+ checkouts = [("", str(term.folder or session.folder))]
+ checkouts += _agent_checkouts_of(workspace_id, session, term, events)
+ with ThreadPoolExecutor(max_workers=max(1, min(4, len(checkouts)))) as pool:
+ jobs = [
+ pool.submit(_read_checkout, name, folder, events, record_folder)
+ for name, folder in checkouts
+ ]
+ return [job.result() for job in jobs]
def _diff_item(diff: git_changes.FileDiff | None) -> PaneFileDiffItem | None:
@@ -1908,45 +1986,51 @@ async def get_pane_changes(workspace_id: str, name: str) -> PaneChangesResponse:
The files are the ones its agent's own record names as written; each is
compared with the code before the agent's first write (``base``), so work
it already committed shows as well as work still pending. A pane on its
- own worktree is read in that worktree. A pane whose record cannot be read
- answers an empty list.
+ own worktree is read in that worktree, and so is a worktree its agent made
+ and worked in. A pane whose record cannot be read answers an empty list.
"""
session, term = _pane_of(workspace_id, name)
folder = term.folder or session.folder
# The repository check and the record's reading run side by side.
- changes, (work, base, generated, listing) = await asyncio.gather(
+ changes, readings = await asyncio.gather(
asyncio.to_thread(git_changes.workspace_changes, folder, set()),
- asyncio.to_thread(_read_pane_changes, folder, _pane_record(session, term)),
+ asyncio.to_thread(_read_pane_changes, workspace_id, session, term),
)
if not changes.available:
return PaneChangesResponse(
workspace_id=workspace_id, available=False, reason=changes.reason
)
+ files = [
+ PaneChangedFileItem(
+ **asdict(item),
+ authors=[
+ ChangeAuthorItem(
+ pane=term.name,
+ history_id=term.history_id,
+ agent=term.agent,
+ display_name=term.display_name,
+ last_edit_ms=reading.work.files.get(item.path, 0),
+ )
+ ],
+ committed=item.path not in reading.listing.pending,
+ diff=_diff_item(reading.listing.diffs.get(item.path)),
+ checkout=reading.checkout,
+ base=reading.base or "",
+ )
+ for reading in readings
+ for item in reading.listing.files
+ ]
+ starts = [reading.work.since_ms for reading in readings if reading.work.since_ms > 0]
+ generated = {path for reading in readings for path in reading.generated}
return PaneChangesResponse(
workspace_id=workspace_id,
available=True,
branch=changes.branch,
- files=[
- PaneChangedFileItem(
- **asdict(item),
- authors=[
- ChangeAuthorItem(
- pane=term.name,
- history_id=term.history_id,
- agent=term.agent,
- display_name=term.display_name,
- last_edit_ms=work.files.get(item.path, 0),
- )
- ],
- committed=item.path not in listing.pending,
- diff=_diff_item(listing.diffs.get(item.path)),
- )
- for item in listing.files
- ],
- truncated=listing.truncated,
- base=base or "",
- since_ms=work.since_ms,
- generated=generated,
+ files=files,
+ truncated=any(reading.listing.truncated for reading in readings),
+ base=readings[0].base or "",
+ since_ms=min(starts, default=0),
+ generated=len(generated),
)
@@ -1956,11 +2040,14 @@ async def get_pane_changes(workspace_id: str, name: str) -> PaneChangesResponse:
summary="How one file a pane's agent changed differs from the code before it",
)
async def get_pane_file_diff(
- workspace_id: str, name: str, path: str, base: str
+ workspace_id: str, name: str, path: str, base: str, checkout: str = ""
) -> WorkspaceFileDiffResponse:
- """One file of the pane's review, against the ``base`` its list answered."""
+ """One file of the pane's review, against the ``base`` its list answered.
+
+ ``checkout`` names the worktree the file lives in, as the list said.
+ """
session, term = _pane_of(workspace_id, name)
- folder = term.folder or session.folder
+ folder = await asyncio.to_thread(_checkout_folder, workspace_id, session, term, checkout)
try:
diff = await asyncio.to_thread(pane_changes.pane_file_diff, folder, path, base)
except ValueError as exc:
diff --git a/dodaios/ui/web/agentic_ide_scm_routes.py b/dodaios/ui/web/agentic_ide_scm_routes.py
index bdad25b409..d30dbe7a9f 100644
--- a/dodaios/ui/web/agentic_ide_scm_routes.py
+++ b/dodaios/ui/web/agentic_ide_scm_routes.py
@@ -551,10 +551,12 @@ def session_file(
pane: str = Query(..., min_length=1),
path: str = Query(..., min_length=1),
base: str = Query(..., min_length=7, max_length=64),
+ checkout: str = Query(default="", max_length=200),
) -> dict:
"""The file at the commit before the session's first change, and as it is now.
- The pane's own worktree is read when it has one, like its review list.
+ The pane's own worktree is read when it has one, or the worktree its
+ agent made and worked in, like its review list.
"""
session = get_registry().get(workspace_id)
if session is None:
@@ -562,7 +564,10 @@ def session_file(
term = next((entry for entry in session.terminals if entry.name == pane), None)
if term is None:
raise HTTPException(status_code=404, detail="Terminal not found.")
+ from .agentic_ide_routes import _checkout_folder
+
+ folder = _checkout_folder(workspace_id, session, term, checkout)
try:
- return scm.session_file_diff(term.folder or session.folder, path, base)
+ return scm.session_file_diff(folder, path, base)
except GitError as exc:
raise _fail(exc) from exc
diff --git a/dodaios/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx b/dodaios/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
index 6b80bcd7f2..c79f88d7e9 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
@@ -24,6 +24,7 @@ import {
cachedPaneChanges,
loadPaneChanges,
fetchPaneFileDiff,
+ reviewFileKey,
type ChangeScope,
type PaneChanges,
type PaneChangesTarget,
@@ -113,7 +114,7 @@ export function PaneChangesDialog({
const show = (changes: PaneChanges) => {
setList({ kind: "ready", changes });
setDiffs(Object.fromEntries(changes.files.filter((file) => !file.is_directory).map((file) => [
- file.path,
+ reviewFileKey(file),
file.diff ? ({ kind: "ready", diff: { workspace_id: workspaceId, path: file.path, ...file.diff } } as DiffState) : ({ kind: "loading" } as DiffState),
])));
};
@@ -133,16 +134,16 @@ export function PaneChangesDialog({
}
if (cancelled) return;
if (changes !== cached) show(changes);
- const queue = changes.files.filter((file) => !file.is_directory && !file.diff).map((file) => file.path);
+ const queue = changes.files.filter((file) => !file.is_directory && !file.diff);
const worker = async () => {
- for (let path = queue.shift(); path !== undefined && !cancelled; path = queue.shift()) {
+ for (let file = queue.shift(); file !== undefined && !cancelled; file = queue.shift()) {
let next: DiffState;
try {
- next = { kind: "ready", diff: await fetchPaneFileDiff(target, path, changes.base) };
+ next = { kind: "ready", diff: await fetchPaneFileDiff(target, file.path, file.base || changes.base, file.checkout) };
} catch (error) {
next = { kind: "error", message: error instanceof Error ? error.message : String(error) };
}
- const done = path;
+ const done = reviewFileKey(file);
if (!cancelled) setDiffs((current) => ({ ...current, [done]: next }));
}
};
@@ -179,7 +180,7 @@ export function PaneChangesDialog({
// A worktree's files are relative to that worktree, not to the workspace the
// editor opens files in, so only the shared folder offers "Open in editor".
const canOpen = !folder;
- const openable = (file: ReviewFile) => canOpen && !file.is_directory && file.status !== "deleted";
+ const openable = (file: ReviewFile) => canOpen && !file.checkout && !file.is_directory && file.status !== "deleted";
// The editor's diff compares against the same base as this review, so work
// the agent already committed is still marked there.
const openInEditor = (file: ReviewFile) => {
@@ -329,11 +330,11 @@ export function PaneChangesDialog({
>
<ul data-testid="pane-changes-list">
{files.map((file) => (
- <li key={file.path}>
+ <li key={reviewFileKey(file)}>
<button
type="button"
- onClick={() => (openable(file) ? openInEditor(file) : jumpTo(file.path))}
- title={openable(file) ? `${file.path} — ${t("pane_review.open_editor")}` : file.path}
+ onClick={() => (openable(file) ? openInEditor(file) : jumpTo(reviewFileKey(file)))}
+ title={openable(file) ? `${file.path} — ${t("pane_review.open_editor")}` : reviewFileKey(file)}
data-testid="pane-changes-list-item"
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none"
>
@@ -342,8 +343,10 @@ export function PaneChangesDialog({
<span className={cn("truncate text-foreground", file.status === "deleted" && "line-through decoration-destructive/60")}>
{baseName(file.path)}
</span>
- {parentPath(file.path) && (
- <span className="truncate text-[11px] text-muted-foreground">{parentPath(file.path)}</span>
+ {(file.checkout || parentPath(file.path)) && (
+ <span className="truncate text-[11px] text-muted-foreground">
+ {[file.checkout, parentPath(file.path)].filter(Boolean).join(" · ")}
+ </span>
)}
</span>
<span
@@ -363,15 +366,15 @@ export function PaneChangesDialog({
<div className="min-w-0 flex-1 space-y-3 overflow-y-auto p-4 scrollbar-jarvis" data-testid="pane-changes-diffs">
{files.map((file) => (
<FileCard
- key={file.path}
+ key={reviewFileKey(file)}
file={file}
- diff={diffs[file.path]}
- collapsed={collapsed.has(file.path)}
- onToggle={() => toggle(file.path)}
+ diff={diffs[reviewFileKey(file)]}
+ collapsed={collapsed.has(reviewFileKey(file))}
+ onToggle={() => toggle(reviewFileKey(file))}
onOpen={openable(file) ? () => openInEditor(file) : undefined}
cardRef={(node) => {
- if (node) cards.current.set(file.path, node);
- else cards.current.delete(file.path);
+ if (node) cards.current.set(reviewFileKey(file), node);
+ else cards.current.delete(reviewFileKey(file));
}}
/>
))}
@@ -425,12 +428,12 @@ function FileCard({
disabled={!onOpen}
onClick={onOpen}
data-testid="pane-changes-file-name"
- title={onOpen ? `${file.path} — ${t("pane_review.open_editor")}` : file.path}
+ title={onOpen ? `${file.path} — ${t("pane_review.open_editor")}` : reviewFileKey(file)}
className="group/name flex min-w-0 flex-1 items-baseline gap-1.5 rounded text-left font-mono text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-default"
>
- {parentPath(file.path) && (
+ {(file.checkout || parentPath(file.path)) && (
<span dir="rtl" className="min-w-0 shrink-[999] truncate text-left text-muted-foreground">
- <bdi dir="ltr">{parentPath(file.path)}/</bdi>
+ <bdi dir="ltr">{[file.checkout && `[${file.checkout}]`, parentPath(file.path)].filter(Boolean).join(" ")}/</bdi>
</span>
)}
<span className={cn(
diff --git a/dodaios/ui/web/frontend/src/components/agentic/paneChangesApi.ts b/dodaios/ui/web/frontend/src/components/agentic/paneChangesApi.ts
index 2fbb7b44c3..909ed8a5f3 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/paneChangesApi.ts
+++ b/dodaios/ui/web/frontend/src/components/agentic/paneChangesApi.ts
@@ -36,8 +36,18 @@ export interface ReviewFile extends ChangedFile {
committed?: boolean;
/** Its diff, sent with the list so the review paints at once; absent = read on demand. */
diff?: InlineDiff | null;
+ /**
+ * The worktree the agent made and changed it in (its folder's name); empty or
+ * absent for the pane's own folder. Such a file cannot be opened or staged here.
+ */
+ checkout?: string;
+ /** The commit this file is compared with; absent = the list's `base`. */
+ base?: string;
}
+/** One listed file's identity: the same path may be changed in two worktrees. */
+export const reviewFileKey = (file: ReviewFile): string => (file.checkout ? `${file.checkout}:${file.path}` : file.path);
+
export interface PaneChanges {
available: boolean;
/** Why `available` is false, in one plain sentence from the backend. */
@@ -218,8 +228,11 @@ export function clearPaneChangesCache(): void {
}
/** One file's diff: against `base` when the pane route gave one, else against the last commit. */
-export function fetchPaneFileDiff(target: PaneChangesTarget, path: string, base = ""): Promise<FileDiff> {
- if (base) return read<FileDiff>(`${paneUrl(target, "diff")}?${new URLSearchParams({ path, base }).toString()}`);
+export function fetchPaneFileDiff(target: PaneChangesTarget, path: string, base = "", checkout = ""): Promise<FileDiff> {
+ if (base) {
+ const query = new URLSearchParams(checkout ? { path, base, checkout } : { path, base });
+ return read<FileDiff>(`${paneUrl(target, "diff")}?${query.toString()}`);
+ }
if (target.folder) {
return read<FileDiff>(
`/api/agentic-ide/git/diff?${new URLSearchParams({ folder: target.folder, path }).toString()}`,
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/SessionChanges.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/SessionChanges.tsx
index 55c8d8712b..c3bc455e9f 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/SessionChanges.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/SessionChanges.tsx
@@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";
import { useCodeEditorStore } from "@/store/codeEditor";
import { useEventStore } from "@/store/events";
import { FileTypeIcon } from "../../explorer/FileTypeIcon";
-import { loadPaneChanges, type PaneChanges, type ReviewFile } from "../../../paneChangesApi";
+import { loadPaneChanges, reviewFileKey, type PaneChanges, type ReviewFile } from "../../../paneChangesApi";
import { agoLabel } from "../gitBadges";
import { Codicon, Twistie } from "./Codicon";
import type { DiffSource } from "./DiffDialog";
@@ -86,7 +86,9 @@ export function SessionChanges({
const pending = useMemo(() => new Set(status.changes.map((file) => file.path)), [status.changes]);
const files = (changes?.files ?? []).filter((file) => !file.is_directory);
const repoPath = (file: ReviewFile) => `${changes?.ownCheckout ? "" : status.prefix}${file.path}`;
- const actionable = (file: ReviewFile) => !changes?.ownCheckout && pending.has(repoPath(file));
+ // A file in a worktree the agent made lives outside this folder: it can only be viewed.
+ const elsewhere = (file: ReviewFile) => Boolean(changes?.ownCheckout || file.checkout);
+ const actionable = (file: ReviewFile) => !elsewhere(file) && pending.has(repoPath(file));
const openDiff = (file: ReviewFile) => {
if (!changes?.base) {
@@ -95,11 +97,11 @@ export function SessionChanges({
useCodeEditorStore.getState().openFile(workspaceId, file.path, { mode: "diff" });
return;
}
- const base = changes.base;
+ const base = file.base || changes.base;
// A file in the shared folder opens in the editor's diff, like any other
- // change, compared with the code before the session's first edit. A pane's
- // own worktree and a deleted file have nothing the editor could open.
- if (!changes.ownCheckout && file.status !== "deleted") {
+ // change, compared with the code before the session's first edit. A
+ // worktree's file and a deleted file have nothing the editor could open.
+ if (!elsewhere(file) && file.status !== "deleted") {
useCodeEditorStore.getState().openFile(workspaceId, file.path, {
mode: "diff",
base: { ref: base, label: fill(t("ide_side_panel.git.scm.session_diff_badge"), { pane: session.pane }) },
@@ -107,9 +109,9 @@ export function SessionChanges({
return;
}
onDiff({
- title: `${baseName(file.path)} (${session.pane})`,
+ title: `${baseName(file.path)} (${file.checkout || session.pane})`,
path: file.path,
- load: () => scmApi.sessionFile(workspaceId, session.pane, file.path, base),
+ load: () => scmApi.sessionFile(workspaceId, session.pane, file.path, base, file.checkout ?? ""),
});
};
@@ -185,13 +187,16 @@ export function SessionChanges({
{files.map((file) => {
const letter = LETTER[file.status] ?? "M";
const tone = letterTone(letter);
- const description = [dirName(file.path), file.committed ? t("ide_side_panel.git.scm.session_committed") : ""].filter(Boolean).join(" · ");
+ const description = [file.checkout ?? "", dirName(file.path), file.committed ? t("ide_side_panel.git.scm.session_committed") : ""]
+ .filter(Boolean)
+ .join(" · ");
return (
<div
- key={file.path}
+ key={reviewFileKey(file)}
role="treeitem"
data-testid="scm-session-file"
data-path={file.path}
+ data-checkout={file.checkout || undefined}
data-letter={letter}
onClick={() => openDiff(file)}
style={{ height: ROW, paddingLeft: 16 }}
@@ -204,7 +209,7 @@ export function SessionChanges({
{description && <span className="ml-[0.5em] min-w-0 truncate text-[0.9em] opacity-70">{description}</span>}
</span>
<span className="scm-actions shrink-0 items-center gap-[2px] pl-1">
- {letter !== "D" && !changes?.ownCheckout && (
+ {letter !== "D" && !elsewhere(file) && (
<button
type="button"
aria-label={t("ide_side_panel.git.scm.open_file")}
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts
index d8b71b2e63..5ee7a00f55 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts
@@ -191,8 +191,8 @@ export const scmApi = {
commit: (workspace_id: string, commit: string) => get<CommitDetails>("/commit", { workspace_id, commit }),
commitFile: (workspace_id: string, commit: string, path: string, original = "") =>
get<CommitFileDiff>("/commit/file", { workspace_id, commit, path, original }),
- sessionFile: (workspace_id: string, pane: string, path: string, base: string) =>
- get<{ path: string; before: string | null; after: string | null; binary: boolean }>("/session-file", { workspace_id, pane, path, base }),
+ sessionFile: (workspace_id: string, pane: string, path: string, base: string, checkout = "") =>
+ get<{ path: string; before: string | null; after: string | null; binary: boolean }>("/session-file", { workspace_id, pane, path, base, checkout }),
followMain: () => get<FollowMain>("/follow-main", {}),
setFollowMain: (enabled: boolean) => put<FollowMain>("/follow-main", { enabled }),
clearFollowLock: () => post<FollowMain>("/follow-main/clear-lock", {}),
diff --git a/tests/unit/web/test_agentic_ide_pane_changes_route.py b/tests/unit/web/test_agentic_ide_pane_changes_route.py
index 8f9cdaa85e..5a02508525 100644
--- a/tests/unit/web/test_agentic_ide_pane_changes_route.py
+++ b/tests/unit/web/test_agentic_ide_pane_changes_route.py
@@ -216,3 +216,69 @@ async def test_unknown_workspace_or_pane_is_a_404(workspace: SimpleNamespace) ->
with pytest.raises(HTTPException) as missing_workspace:
await routes.get_pane_changes("nope", "T1")
assert missing_workspace.value.status_code == 404
+
+
+async def test_work_in_a_worktree_the_agent_made_is_read_there(
+ repo: Path, workspace: SimpleNamespace, tmp_path_factory: pytest.TempPathFactory
+) -> None:
+ # The agent started in the shared folder, made its own worktree, and did
+ # all its editing and committing there. The shared folder shows none of it.
+ tree = tmp_path_factory.mktemp("trees") / "feature"
+ _git(repo, "worktree", "add", "-q", "-b", "feature", str(tree))
+ (tree / "mine.py").write_text("two\n", encoding="utf-8")
+ _git(tree, "commit", "-q", "-am", "feat: in the worktree", at=NOW - 10)
+ (tree / "new.py").write_text("fresh\n", encoding="utf-8")
+ workspace.records["s1"] = (
+ _write(str(tree / "mine.py"), "c1")
+ + _write(str(tree / "new.py"), "c3")
+ + _shell("c9", f'cd "{tree.as_posix()}" && git commit -am "feat: in the worktree"', "")
+ )
+ routes._agent_checkouts.clear()
+
+ answer = await routes.get_pane_changes("w1", "T1")
+
+ assert [(f.checkout, f.path, f.committed) for f in answer.files] == [
+ ("feature", "mine.py", True),
+ ("feature", "new.py", False),
+ ]
+ mine = answer.files[0]
+ diff = await routes.get_pane_file_diff("w1", "T1", "mine.py", mine.base, mine.checkout)
+ assert [(line.kind, line.text) for hunk in diff.hunks for line in hunk.lines] == [
+ ("del", "one"),
+ ("add", "two"),
+ ]
+ # The shared folder's copy is untouched: without the worktree there is no change.
+ shared = await routes.get_pane_file_diff("w1", "T1", "mine.py", mine.base)
+ assert shared.hunks == []
+ with pytest.raises(HTTPException) as unknown:
+ await routes.get_pane_file_diff("w1", "T1", "mine.py", mine.base, "elsewhere")
+ assert unknown.value.status_code == 404
+ # A pane whose agent stayed in the shared folder still reads only there.
+ other = await routes.get_pane_changes("w1", "T2")
+ assert all(not f.checkout for f in other.files)
+
+
+async def test_work_in_two_worktrees_and_the_shared_folder_is_all_listed(
+ repo: Path, workspace: SimpleNamespace, tmp_path_factory: pytest.TempPathFactory
+) -> None:
+ trees = tmp_path_factory.mktemp("trees")
+ first, second = trees / "first", trees / "second"
+ _git(repo, "worktree", "add", "-q", "-b", "first", str(first))
+ _git(repo, "worktree", "add", "-q", "-b", "second", str(second))
+ (first / "mine.py").write_text("first\n", encoding="utf-8")
+ (second / "mine.py").write_text("second\n", encoding="utf-8")
+ (repo / "theirs.py").write_text("shared\n", encoding="utf-8")
+ workspace.records["s1"] = (
+ _write(str(first / "mine.py"), "c1")
+ + _write(str(second / "mine.py"), "c2")
+ + _write(str(repo / "theirs.py"), "c3")
+ )
+ routes._agent_checkouts.clear()
+
+ answer = await routes.get_pane_changes("w1", "T1")
+
+ assert sorted((f.checkout, f.path) for f in answer.files) == [
+ ("", "theirs.py"),
+ ("first", "mine.py"),
+ ("second", "mine.py"),
+ ]