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.

feat(agentic-ide): open a reviewed file in the editor by clicking it

rubenluetke10-beepf1abc09acd96
diff --git a/jarvis/agentic_ide/git_changes.py b/jarvis/agentic_ide/git_changes.py
index 27e2bc6803..2efc9687bf 100644
--- a/jarvis/agentic_ide/git_changes.py
+++ b/jarvis/agentic_ide/git_changes.py
@@ -18,6 +18,7 @@ that has git at all, and every call is bounded:
from __future__ import annotations
+import re
import subprocess
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
@@ -319,15 +320,25 @@ def _parse_unified(text: str) -> tuple[list[DiffHunk], int, int, bool, bool]:
return hunks, added, removed, False, truncated
-def head_text(folder: str | Path, path: str) -> str | None:
- """One file's text as of the last commit; None when git has no copy of it."""
+#: A commit id a caller may name instead of HEAD.
+_COMMIT_ID = re.compile(r"^[0-9a-f]{7,64}$")
+
+
+def head_text(folder: str | Path, path: str, ref: str = "") -> str | None:
+ """One file's text as of the last commit, or of commit ``ref``; None when git has no copy.
+
+ ``ref`` is a commit id (a pane review compares against the code before an
+ agent's first change); anything else is refused.
+ """
rel = normalize_workspace_path(folder, path)
root = Path(folder).expanduser()
+ if ref and not _COMMIT_ID.match(ref):
+ raise ValueError("That is not a commit id.")
if not _has_head(root):
return None
# "./" makes git read the path relative to the workspace folder, which may
# sit below the repository root.
- result = _git(["show", f"HEAD:./{rel}"], root)
+ result = _git(["show", f"{ref or 'HEAD'}:./{rel}"], root)
if result is None or result.returncode != 0:
return None
# The editor shows a BOM file's text without its BOM; so must the diff.
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 29565b2f68..dafbd8ddcf 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -2265,14 +2265,17 @@ async def save_workspace_text_file(
"/workspaces/{workspace_id}/head-text",
summary="A workspace file's text at the last commit",
)
-async def get_workspace_head_text(workspace_id: str, path: str) -> dict[str, object]:
+async def get_workspace_head_text(
+ workspace_id: str, path: str, ref: str = ""
+) -> dict[str, object]:
"""The committed text the editor's diff view compares against.
+ ``ref`` names another commit than HEAD — the base of a pane's review.
``text`` is null for a file git does not know (new, or not a repository).
"""
folder = _workspace_folder(workspace_id)
try:
- text = await asyncio.to_thread(git_changes.head_text, folder, path)
+ text = await asyncio.to_thread(git_changes.head_text, folder, path, ref)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"workspace_id": workspace_id, "path": path.replace("\\", "/"), "text": text}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
index 80ef0caf41..2ebb84f33e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.test.tsx
@@ -72,7 +72,7 @@ beforeEach(() => {
: url.includes("/changes") ? CHANGES : {};
return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
}));
- useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, visible: false, reveal: null, closed: [] });
+ useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, visible: false, reveal: null, closed: [], diffBases: {} });
});
afterEach(() => {
@@ -171,6 +171,19 @@ describe("PaneChangesDialog", () => {
expect(useCodeEditorStore.getState().tabs.map((tab) => tab.path)).toEqual(["src/app.ts"]);
});
+ it("opens a file in the editor when its name or its row in the list is clicked, diffed against the review base", async () => {
+ const onOpenChange = vi.fn();
+ render(<PaneChangesDialog open onOpenChange={onOpenChange} workspaceId="w1" pane="T1" />);
+ fireEvent.click(await screen.findByTestId("pane-changes-file-name"));
+ const state = useCodeEditorStore.getState();
+ expect(state.tabs.map((tab) => [tab.path, tab.mode])).toEqual([["src/app.ts", "diff"]]);
+ expect(Object.values(state.diffBases)).toEqual([{ ref: "abc1234", label: "Changes by T1" }]);
+ useCodeEditorStore.setState({ tabs: [], active: {}, files: {}, diffBases: {} });
+ fireEvent.click(screen.getByTestId("pane-changes-list-item"));
+ expect(useCodeEditorStore.getState().tabs.map((tab) => tab.path)).toEqual(["src/app.ts"]);
+ expect(onOpenChange).toHaveBeenCalledTimes(2);
+ });
+
it("folds a file's diff away", async () => {
render(<PaneChangesDialog open onOpenChange={() => {}} workspaceId="w1" pane="T1" />);
expect(await screen.findByText("new src/app.ts")).toBeTruthy();
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
index ee187e1c85..04e595463e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneChangesDialog.tsx
@@ -167,6 +167,17 @@ 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";
+ // 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) => {
+ onOpenChange(false);
+ openFile(workspaceId, file.path, {
+ mode: "diff",
+ preview: false,
+ base: changes?.base ? { ref: changes.base, label: fill(t("pane_review.editor_badge"), { pane: title }) } : undefined,
+ });
+ };
return (
<Dialog.Root open={open} onOpenChange={onOpenChange}>
@@ -196,7 +207,7 @@ export function PaneChangesDialog({
<div className="mb-1 flex items-center gap-2">
<FileDiff className="h-4 w-4 shrink-0 text-primary" aria-hidden="true" />
<Dialog.Title className="truncate font-display text-base font-semibold tracking-tight text-foreground">
- {fill(t("pane_review.title"), { name: title })}
+ {fill(t("pane_review.title"), { pane: title })}
</Dialog.Title>
</div>
<Dialog.Description className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs leading-relaxed text-muted-foreground">
@@ -309,8 +320,9 @@ export function PaneChangesDialog({
<li key={file.path}>
<button
type="button"
- onClick={() => jumpTo(file.path)}
- title={file.path}
+ onClick={() => (openable(file) ? openInEditor(file) : jumpTo(file.path))}
+ title={openable(file) ? `${file.path} — ${t("pane_review.open_editor")}` : file.path}
+ 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"
>
<FileTypeIcon path={file.path} />
@@ -344,12 +356,7 @@ export function PaneChangesDialog({
diff={diffs[file.path]}
collapsed={collapsed.has(file.path)}
onToggle={() => toggle(file.path)}
- onOpen={canOpen && !file.is_directory && file.status !== "deleted"
- ? () => {
- onOpenChange(false);
- openFile(workspaceId, file.path, { mode: "diff", preview: false });
- }
- : undefined}
+ onOpen={openable(file) ? () => openInEditor(file) : undefined}
cardRef={(node) => {
if (node) cards.current.set(file.path, node);
else cards.current.delete(file.path);
@@ -401,16 +408,26 @@ function FileCard({
<ChevronDown className={cn("h-4 w-4 transition-transform", collapsed && "-rotate-90")} aria-hidden="true" />
</button>
<FileTypeIcon path={file.path} />
- <span className="flex min-w-0 flex-1 items-baseline gap-1.5 font-mono text-xs" title={file.path}>
+ <button
+ type="button"
+ disabled={!onOpen}
+ onClick={onOpen}
+ data-testid="pane-changes-file-name"
+ title={onOpen ? `${file.path} — ${t("pane_review.open_editor")}` : file.path}
+ 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) && (
<span dir="rtl" className="min-w-0 shrink-[999] truncate text-left text-muted-foreground">
<bdi dir="ltr">{parentPath(file.path)}/</bdi>
</span>
)}
- <span className={cn("min-w-0 shrink-0 truncate text-foreground", file.status === "deleted" && "line-through decoration-destructive/60")}>
+ <span className={cn(
+ "min-w-0 shrink-0 truncate text-foreground group-enabled/name:group-hover/name:underline",
+ file.status === "deleted" && "line-through decoration-destructive/60",
+ )}>
{baseName(file.path)}
</span>
- </span>
+ </button>
<span className={cn("shrink-0 text-[11px] font-medium", STATUS_TONE[file.status])}>
{t(`pane_review.status.${file.status}`)}
</span>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
index ca205c969e..11d63a8f08 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
@@ -76,6 +76,7 @@ export function CodeEditorStage({
const visible = useCodeEditorStore((state) => state.visible);
const quickOpen = useCodeEditorStore((state) => state.quickOpen);
const files = useCodeEditorStore((state) => state.files);
+ const diffBases = useCodeEditorStore((state) => state.diffBases);
const [pending, setPending] = useState<PendingClose | null>(null);
const [menu, setMenu] = useState<EditorTab | null>(null);
// Tabs whose Markdown, HTML or SVG is shown rendered (Ctrl+Shift+V).
@@ -325,7 +326,7 @@ export function CodeEditorStage({
<span className={cn("truncate", index === segments.length - 1 && "text-foreground")}>{segment}</span>
</span>
))}
- {activeTab.mode === "diff" && <span className="ml-1.5 shrink-0 rounded bg-secondary px-1.5 py-px text-[11px]">{t("code_editor.diff_badge")}</span>}
+ {activeTab.mode === "diff" && <span className="ml-1.5 shrink-0 rounded bg-secondary px-1.5 py-px text-[11px]">{diffBases[activeTab.fileKey]?.label ?? t("code_editor.diff_badge")}</span>}
</nav>
{activeTab.mode === "edit" && activeFile?.status === "ready" && renderKindOf(activeTab.path) && (
<ActionButton
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
index c385311127..50ffc2101f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/EditorSurface.tsx
@@ -167,6 +167,7 @@ export default function EditorSurface({
}, [tab.key, tab.fileKey, tab.mode, ready]);
// Diff tabs: the committed text on the left, the live (editable) buffer on the right.
+ const diffBaseRef = useCodeEditorStore((state) => state.diffBases[tab.fileKey]?.ref ?? "");
useEffect(() => {
if (tab.mode !== "diff" || !ready) return;
let alive = true;
@@ -197,7 +198,7 @@ export default function EditorSurface({
alive = false;
for (const watcher of watchers) watcher.dispose();
};
- }, [tab.key, tab.fileKey, tab.mode, ready]);
+ }, [tab.key, tab.fileKey, tab.mode, ready, diffBaseRef]);
// "Open at line": a Ctrl+click on `file.py:42` in a terminal, or Quick Open's `name:42`.
useEffect(() => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
index 8768c527fb..626cb29860 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
@@ -112,9 +112,10 @@ export async function saveTextFile(workspaceId: string, request: SaveRequest): P
return (await res.json()) as TextFile;
}
-/** The file's text at the last commit; null for a file git does not know. */
-export async function fetchHeadText(workspaceId: string, path: string): Promise<string | null> {
- const answer = await send<{ text: string | null }>(`${base(workspaceId)}/head-text?${query(path)}`);
+/** The file's text at the last commit, or at commit `ref`; null for a file git does not know. */
+export async function fetchHeadText(workspaceId: string, path: string, ref = ""): Promise<string | null> {
+ const params = new URLSearchParams(ref ? { path, ref } : { path }).toString();
+ const answer = await send<{ text: string | null }>(`${base(workspaceId)}/head-text?${params}`);
return answer.text;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
index 1935df1231..885fbe8ee8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
@@ -339,7 +339,7 @@ export function loadHead(fileKey: string): Promise<Monaco.editor.ITextModel | nu
if (!file || !api) return null;
let text: string | null = null;
try {
- text = await fetchHeadText(file.workspaceId, file.path);
+ text = await fetchHeadText(file.workspaceId, file.path, store().diffBases[fileKey]?.ref);
} catch (error) {
toast((error as Error).message);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json
index c45ef1689f..bdcb24b95f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/de.json
@@ -1,6 +1,6 @@
{
"pane_review": {
- "title": "Änderungen prüfen: {name}",
+ "title": "Änderungen prüfen: {pane}",
"description_pane": "Jede Datei, die dieser Agent geändert hat, committet oder nicht, verglichen mit dem Code vor seiner ersten Änderung.",
"description_since": "Jede Datei, die dieser Agent geändert hat, committet oder nicht, verglichen mit dem Code vor seiner ersten Änderung ({time}).",
"description_uncommitted": "Jede Datei, die dieser Agent geändert und noch nicht committet hat.",
@@ -40,6 +40,7 @@
},
"committed": "Committet",
"pending": "Nicht committet",
- "generated_hidden": "+ {count} generierte Dateien (Build-Ausgabe), nicht aufgelistet"
+ "generated_hidden": "+ {count} generierte Dateien (Build-Ausgabe), nicht aufgelistet",
+ "editor_badge": "Änderungen von {pane}"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json
index 4769019e7e..70c4d9ebb0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/en.json
@@ -1,6 +1,6 @@
{
"pane_review": {
- "title": "Review changes: {name}",
+ "title": "Review changes: {pane}",
"description_pane": "Every file this agent changed, committed or not, compared with the code before its first edit.",
"description_since": "Every file this agent changed, committed or not, compared with the code before its first edit ({time}).",
"description_uncommitted": "Every file this agent changed that is not committed yet.",
@@ -40,6 +40,7 @@
},
"committed": "Committed",
"pending": "Not committed",
- "generated_hidden": "+ {count} generated files (build output), not listed"
+ "generated_hidden": "+ {count} generated files (build output), not listed",
+ "editor_badge": "Changes by {pane}"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json
index 301f67fb8b..5ef9e0eb1f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pane_review/es.json
@@ -1,6 +1,6 @@
{
"pane_review": {
- "title": "Revisar cambios: {name}",
+ "title": "Revisar cambios: {pane}",
"description_pane": "Cada archivo que este agente cambió, con commit o sin él, comparado con el código antes de su primer cambio.",
"description_since": "Cada archivo que este agente cambió, con commit o sin él, comparado con el código antes de su primer cambio ({time}).",
"description_uncommitted": "Cada archivo que este agente cambió y que aún no tiene commit.",
@@ -40,6 +40,7 @@
},
"committed": "Con commit",
"pending": "Sin commit",
- "generated_hidden": "+ {count} archivos generados (salida de compilación), no listados"
+ "generated_hidden": "+ {count} archivos generados (salida de compilación), no listados",
+ "editor_badge": "Cambios de {pane}"
}
}
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.ts
index c46e7e391b..3d75489481 100644
--- a/jarvis/ui/web/frontend/src/store/codeEditor.ts
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts
@@ -75,8 +75,18 @@ interface ClosedTab {
mode: EditorMode;
}
+/** What a diff tab compares against instead of the last commit. */
+export interface DiffBase {
+ /** A commit id. */
+ ref: string;
+ /** Shown in the diff badge in place of "Changes since the last commit". */
+ label: string;
+}
+
export interface OpenOptions {
mode?: EditorMode;
+ /** Diff only: compare against this commit (a pane review's base); omitted = the last commit. */
+ base?: DiffBase;
/** Single-click opens replace each other; false keeps the tab. */
preview?: boolean;
line?: number;
@@ -95,6 +105,8 @@ interface CodeEditorState {
cursor: CursorInfo | null;
reveal: RevealRequest | null;
closed: ClosedTab[];
+ /** Per file: the commit its diff tab compares against, when it is not the last commit. */
+ diffBases: Record<string, DiffBase>;
openFile: (workspaceId: string, path: string, options?: OpenOptions) => void;
closeTab: (key: string) => void;
closeTabs: (keys: string[]) => void;
@@ -170,6 +182,7 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
cursor: null,
reveal: null,
closed: [],
+ diffBases: {},
openFile: (workspaceId, path, options = {}) => {
const mode = options.mode ?? "edit";
@@ -199,12 +212,21 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({
options.line != null
? { fileKey, line: options.line, column: options.column ?? 1, length: options.length ?? 0, nonce: ++revealNonce }
: state.reveal;
+ // A diff opened from a pane review compares against that review's base;
+ // one opened anywhere else goes back to the last commit.
+ let diffBases = state.diffBases;
+ if (mode === "diff" && diffBases[fileKey]?.ref !== options.base?.ref) {
+ diffBases = { ...diffBases };
+ if (options.base) diffBases[fileKey] = options.base;
+ else delete diffBases[fileKey];
+ }
return {
tabs,
files: prune(files, tabs),
active: { ...state.active, [workspaceId]: key },
visible: true,
reveal,
+ diffBases,
};
});
},
diff --git a/tests/unit/agentic_ide/test_git_changes.py b/tests/unit/agentic_ide/test_git_changes.py
index 05278e97c2..a83a275176 100644
--- a/tests/unit/agentic_ide/test_git_changes.py
+++ b/tests/unit/agentic_ide/test_git_changes.py
@@ -73,6 +73,19 @@ def test_only_narrows_to_named_files_before_the_cap(
assert git_changes.workspace_changes(repo, only=set()).files == []
+def test_head_text_reads_a_named_commit_and_refuses_anything_else(repo: Path) -> None:
+ first = subprocess.run(
+ ["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True, check=True
+ ).stdout.strip()
+ (repo / "top.txt").write_text("later" + chr(10), encoding="utf-8")
+ _git(repo, "commit", "-q", "-am", "later")
+
+ assert git_changes.head_text(repo, "top.txt") == "later" + chr(10)
+ assert git_changes.head_text(repo, "top.txt", first) == "root" + chr(10)
+ with pytest.raises(ValueError):
+ git_changes.head_text(repo, "top.txt", "HEAD~1")
+
+
def test_a_sub_folder_workspace_sees_only_its_own_changes_relative_to_itself(repo: Path) -> None:
(repo / "app" / "main.py").write_text("changed\n", encoding="utf-8")
(repo / "top.txt").write_text("changed\n", encoding="utf-8")