Skip to content

Agent Zero AI framework

Add right canvas diff viewer

Alessandro58a5f8276b8e
diff --git a/plugins/_diff_viewer/api/diff.py b/plugins/_diff_viewer/api/diff.py
new file mode 100644
index 000000000..ee5b42a07
--- /dev/null
+++ b/plugins/_diff_viewer/api/diff.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+from helpers import files, projects, settings
+from helpers.api import ApiHandler, Request, Response
+from plugins._diff_viewer.helpers.diff import collect_workspace_diff
+
+
+class Diff(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ context_id = str(input.get("context_id") or "").strip()
+ workspace_path, display_path = self._resolve_workspace(context_id)
+ return collect_workspace_diff(
+ workspace_path,
+ context_id=context_id,
+ display_path=display_path,
+ )
+
+ def _resolve_workspace(self, context_id: str) -> tuple[str, str]:
+ if context_id:
+ context = self.use_context(context_id)
+ project_name = projects.get_context_project_name(context)
+ if project_name:
+ project_path = projects.get_project_folder(project_name)
+ display_path = files.normalize_a0_path(project_path)
+ return files.fix_dev_path(display_path), display_path
+
+ configured = str(settings.get_settings().get("workdir_path") or "")
+ display_path = configured or files.normalize_a0_path(files.get_abs_path("usr/workdir"))
+ return files.fix_dev_path(display_path), display_path
diff --git a/plugins/_diff_viewer/extensions/webui/apply_snapshot_before/refresh-diff-viewer.js b/plugins/_diff_viewer/extensions/webui/apply_snapshot_before/refresh-diff-viewer.js
new file mode 100644
index 000000000..5afcccbfc
--- /dev/null
+++ b/plugins/_diff_viewer/extensions/webui/apply_snapshot_before/refresh-diff-viewer.js
@@ -0,0 +1,9 @@
+export default function refreshDiffViewerOnContextChange(ctx) {
+ const diffViewer = globalThis.Alpine?.store?.("diffViewer");
+ const canvas = globalThis.Alpine?.store?.("rightCanvas");
+ if (!diffViewer || !canvas?.isOpen || canvas.activeSurfaceId !== "diff") return;
+ const nextContextId = String(ctx?.snapshot?.context || "");
+ if (nextContextId && nextContextId !== diffViewer.contextId) {
+ diffViewer.scheduleRefresh({ contextId: nextContextId, reason: "context-change" });
+ }
+}
diff --git a/plugins/_diff_viewer/extensions/webui/right-canvas-panels/diff-viewer-panel.html b/plugins/_diff_viewer/extensions/webui/right-canvas-panels/diff-viewer-panel.html
new file mode 100644
index 000000000..157089158
--- /dev/null
+++ b/plugins/_diff_viewer/extensions/webui/right-canvas-panels/diff-viewer-panel.html
@@ -0,0 +1,8 @@
+<div
+ class="right-canvas-surface-panel diff-viewer-canvas-surface"
+ data-surface-id="diff"
+ x-show="$store.rightCanvas && $store.rightCanvas.isOpen && $store.rightCanvas.activeSurfaceId === 'diff'"
+ style="display: none;"
+>
+ <x-component path="/plugins/_diff_viewer/webui/diff-viewer-panel.html" mode="canvas"></x-component>
+</div>
diff --git a/plugins/_diff_viewer/extensions/webui/right_canvas_register_surfaces/register-diff-viewer.js b/plugins/_diff_viewer/extensions/webui/right_canvas_register_surfaces/register-diff-viewer.js
new file mode 100644
index 000000000..39ac86f7b
--- /dev/null
+++ b/plugins/_diff_viewer/extensions/webui/right_canvas_register_surfaces/register-diff-viewer.js
@@ -0,0 +1,37 @@
+function waitForElement(selector, timeoutMs = 3000) {
+ const found = document.querySelector(selector);
+ if (found) return Promise.resolve(found);
+ return new Promise((resolve) => {
+ const timeout = globalThis.setTimeout(() => {
+ observer.disconnect();
+ resolve(document.querySelector(selector));
+ }, timeoutMs);
+ const observer = new MutationObserver(() => {
+ const element = document.querySelector(selector);
+ if (!element) return;
+ globalThis.clearTimeout(timeout);
+ observer.disconnect();
+ resolve(element);
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ });
+}
+
+export default async function registerDiffViewerSurface(canvas) {
+ canvas.registerSurface({
+ id: "diff",
+ title: "Diff",
+ icon: "difference",
+ order: 30,
+ modalPath: "/plugins/_diff_viewer/webui/main.html",
+ async open(payload = {}) {
+ await waitForElement('[data-surface-id="diff"] .diff-viewer-panel');
+ const diffViewer = globalThis.Alpine?.store?.("diffViewer");
+ await diffViewer?.onOpen?.(payload);
+ },
+ async close() {
+ const diffViewer = globalThis.Alpine?.store?.("diffViewer");
+ diffViewer?.cleanup?.();
+ },
+ });
+}
diff --git a/plugins/_diff_viewer/helpers/__init__.py b/plugins/_diff_viewer/helpers/__init__.py
new file mode 100644
index 000000000..75da34a92
--- /dev/null
+++ b/plugins/_diff_viewer/helpers/__init__.py
@@ -0,0 +1 @@
+"""Helpers for the built-in diff viewer plugin."""
diff --git a/plugins/_diff_viewer/helpers/diff.py b/plugins/_diff_viewer/helpers/diff.py
new file mode 100644
index 000000000..33a6c7aff
--- /dev/null
+++ b/plugins/_diff_viewer/helpers/diff.py
@@ -0,0 +1,347 @@
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from helpers import files
+
+
+MAX_PATCH_LINES = 2500
+MAX_PATCH_BYTES = 240_000
+MAX_UNTRACKED_BYTES = 180_000
+GIT_TIMEOUT_SECONDS = 8
+
+GROUP_ORDER = ("staged", "unstaged", "untracked")
+STATUS_LABELS = {
+ "A": "added",
+ "C": "copied",
+ "D": "deleted",
+ "M": "modified",
+ "R": "renamed",
+ "T": "type_changed",
+ "U": "unmerged",
+ "?": "untracked",
+}
+
+
+class GitDiffError(RuntimeError):
+ pass
+
+
+def collect_workspace_diff(
+ workspace_path: str,
+ *,
+ context_id: str = "",
+ display_path: str | None = None,
+) -> dict[str, Any]:
+ workspace = Path(workspace_path).expanduser().resolve()
+ display = display_path or str(workspace)
+
+ if not workspace.exists() or not workspace.is_dir():
+ return {
+ "ok": False,
+ "context_id": context_id,
+ "workspace_path": display,
+ "is_git_repo": False,
+ "error": "Workspace path does not exist or is not a directory.",
+ "branch": "",
+ "totals": {"files": 0, "additions": 0, "deletions": 0},
+ "groups": _empty_groups(),
+ }
+
+ if not _is_git_repo(workspace):
+ return {
+ "ok": True,
+ "context_id": context_id,
+ "workspace_path": display,
+ "is_git_repo": False,
+ "branch": "",
+ "totals": {"files": 0, "additions": 0, "deletions": 0},
+ "groups": _empty_groups(),
+ }
+
+ groups = [
+ {"kind": "staged", "files": _collect_diff_group(workspace, "staged")},
+ {"kind": "unstaged", "files": _collect_diff_group(workspace, "unstaged")},
+ {"kind": "untracked", "files": _collect_untracked_group(workspace)},
+ ]
+
+ seen_paths: set[str] = set()
+ additions = 0
+ deletions = 0
+ for group in groups:
+ for item in group["files"]:
+ seen_paths.add(str(item.get("path") or item.get("old_path") or ""))
+ additions += int(item.get("additions") or 0)
+ deletions += int(item.get("deletions") or 0)
+
+ return {
+ "ok": True,
+ "context_id": context_id,
+ "workspace_path": display,
+ "is_git_repo": True,
+ "branch": _branch_name(workspace),
+ "totals": {
+ "files": len([path for path in seen_paths if path]),
+ "additions": additions,
+ "deletions": deletions,
+ },
+ "groups": groups,
+ }
+
+
+def _empty_groups() -> list[dict[str, Any]]:
+ return [{"kind": kind, "files": []} for kind in GROUP_ORDER]
+
+
+def _git(workspace: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ env = os.environ.copy()
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GIT_OPTIONAL_LOCKS"] = "0"
+ completed = subprocess.run(
+ ["git", "-C", str(workspace), *args],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ env=env,
+ timeout=GIT_TIMEOUT_SECONDS,
+ )
+ if check and completed.returncode != 0:
+ message = (completed.stderr or completed.stdout or "Git command failed.").strip()
+ raise GitDiffError(message)
+ return completed
+
+
+def _is_git_repo(workspace: Path) -> bool:
+ return _git(workspace, "rev-parse", "--is-inside-work-tree", check=False).returncode == 0
+
+
+def _branch_name(workspace: Path) -> str:
+ branch = _git(workspace, "branch", "--show-current", check=False).stdout.strip()
+ if branch:
+ return branch
+ return _git(workspace, "rev-parse", "--short", "HEAD", check=False).stdout.strip()
+
+
+def _collect_diff_group(workspace: Path, kind: str) -> list[dict[str, Any]]:
+ cached_args = ["--cached"] if kind == "staged" else []
+ status_output = _git(
+ workspace,
+ "diff",
+ *cached_args,
+ "--name-status",
+ "-z",
+ "--find-renames",
+ "--relative",
+ "--",
+ ".",
+ ).stdout
+ entries = _parse_name_status(status_output)
+ result: list[dict[str, Any]] = []
+
+ for entry in entries:
+ path = entry["path"]
+ old_path = entry.get("old_path", "")
+ if _is_a0_metadata_path(path) and (not old_path or _is_a0_metadata_path(old_path)):
+ continue
+
+ stat_paths = [candidate for candidate in (old_path, path) if candidate]
+ additions, deletions, binary = _diff_numstat(workspace, kind, stat_paths)
+ if _is_zero_line_gitkeep_change(path, old_path, additions, deletions):
+ continue
+
+ too_large = additions + deletions > MAX_PATCH_LINES
+ patch = ""
+ if not binary and not too_large:
+ patch = _diff_patch(workspace, kind, stat_paths)
+ if len(patch.encode("utf-8", errors="replace")) > MAX_PATCH_BYTES:
+ patch = ""
+ too_large = True
+
+ result.append(
+ {
+ "path": path,
+ "old_path": old_path,
+ "status": STATUS_LABELS.get(entry["status"], entry["status"].lower()),
+ "additions": additions,
+ "deletions": deletions,
+ "binary": binary,
+ "too_large": too_large,
+ "patch": patch,
+ }
+ )
+
+ return result
+
+
+def _collect_untracked_group(workspace: Path) -> list[dict[str, Any]]:
+ output = _git(
+ workspace,
+ "ls-files",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ "--",
+ ".",
+ ).stdout
+ result: list[dict[str, Any]] = []
+ for path in [part for part in output.split("\0") if part]:
+ path = path.replace("\\", "/")
+ if _is_a0_metadata_path(path):
+ continue
+ item = _untracked_file_diff(workspace, path)
+ if _is_zero_line_gitkeep_change(item["path"], item.get("old_path", ""), item["additions"], item["deletions"]):
+ continue
+ result.append(item)
+ result.sort(key=lambda item: item["path"])
+ return result
+
+
+def _parse_name_status(output: str) -> list[dict[str, str]]:
+ parts = [part for part in output.split("\0") if part]
+ entries: list[dict[str, str]] = []
+ index = 0
+ while index < len(parts):
+ raw_status = parts[index]
+ index += 1
+ status = raw_status[:1]
+ if status in {"R", "C"} and index + 1 < len(parts):
+ old_path = parts[index].replace("\\", "/")
+ new_path = parts[index + 1].replace("\\", "/")
+ index += 2
+ entries.append({"status": status, "old_path": old_path, "path": new_path})
+ continue
+ if index < len(parts):
+ path = parts[index].replace("\\", "/")
+ index += 1
+ entries.append({"status": status, "path": path, "old_path": ""})
+ entries.sort(key=lambda item: item.get("path") or item.get("old_path") or "")
+ return entries
+
+
+def _diff_numstat(workspace: Path, kind: str, paths: list[str]) -> tuple[int, int, bool]:
+ args = ["diff"]
+ if kind == "staged":
+ args.append("--cached")
+ output = _git(
+ workspace,
+ *args,
+ "--numstat",
+ "--find-renames",
+ "--relative",
+ "--",
+ *paths,
+ ).stdout
+ first = next((line for line in output.splitlines() if line.strip()), "")
+ if not first:
+ return 0, 0, False
+ parts = first.split("\t")
+ if len(parts) < 2:
+ return 0, 0, False
+ if parts[0] == "-" or parts[1] == "-":
+ return 0, 0, True
+ return _safe_int(parts[0]), _safe_int(parts[1]), False
+
+
+def _diff_patch(workspace: Path, kind: str, paths: list[str]) -> str:
+ args = ["diff"]
+ if kind == "staged":
+ args.append("--cached")
+ return _git(
+ workspace,
+ *args,
+ "--patch",
+ "--find-renames",
+ "--relative",
+ "--",
+ *paths,
+ ).stdout
+
+
+def _untracked_file_diff(workspace: Path, path: str) -> dict[str, Any]:
+ file_path = (workspace / path).resolve()
+ additions = 0
+ binary = False
+ too_large = False
+ patch = ""
+
+ try:
+ with open(file_path, "rb") as handle:
+ data = handle.read(MAX_UNTRACKED_BYTES + 1)
+ too_large = len(data) > MAX_UNTRACKED_BYTES
+ sample = data[: min(len(data), 10 * 1024)]
+ binary = files.is_probably_binary_bytes(sample)
+ if not binary and not too_large:
+ text = data.decode("utf-8", errors="replace")
+ lines = text.splitlines()
+ additions = len(lines)
+ if len(lines) > MAX_PATCH_LINES:
+ too_large = True
+ else:
+ patch = _synthetic_untracked_patch(path, lines, text.endswith("\n"))
+ elif not binary:
+ additions = _count_newlines(data[:MAX_UNTRACKED_BYTES])
+ except OSError:
+ too_large = True
+
+ return {
+ "path": path,
+ "old_path": "",
+ "status": "untracked",
+ "additions": additions,
+ "deletions": 0,
+ "binary": binary,
+ "too_large": too_large,
+ "patch": patch,
+ }
+
+
+def _synthetic_untracked_patch(path: str, lines: list[str], has_trailing_newline: bool) -> str:
+ escaped = path.replace("\t", "\\t")
+ header = [
+ f"diff --git a/{escaped} b/{escaped}",
+ "new file mode 100644",
+ "index 0000000..0000000",
+ "--- /dev/null",
+ f"+++ b/{escaped}",
+ ]
+ if not lines:
+ return "\n".join(header) + "\n"
+ body = [f"@@ -0,0 +1,{len(lines)} @@"]
+ body.extend(f"+{line}" for line in lines)
+ if not has_trailing_newline:
+ body.append("\\ No newline at end of file")
+ return "\n".join(header + body) + "\n"
+
+
+def _count_newlines(data: bytes) -> int:
+ if not data:
+ return 0
+ count = data.count(b"\n")
+ return count if data.endswith(b"\n") else count + 1
+
+
+def _safe_int(value: str) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+def _is_a0_metadata_path(path: str) -> bool:
+ normalized = path.replace("\\", "/").lstrip("/")
+ return normalized == ".a0proj" or normalized.startswith(".a0proj/")
+
+
+def _is_zero_line_gitkeep_change(path: str, old_path: str, additions: int, deletions: int) -> bool:
+ if additions != 0 or deletions != 0:
+ return False
+ candidates = [path, old_path]
+ return any(
+ candidate.replace("\\", "/").rstrip("/").split("/")[-1] == ".gitkeep"
+ for candidate in candidates
+ if candidate
+ )
diff --git a/plugins/_diff_viewer/plugin.yaml b/plugins/_diff_viewer/plugin.yaml
new file mode 100644
index 000000000..7aa99f486
--- /dev/null
+++ b/plugins/_diff_viewer/plugin.yaml
@@ -0,0 +1,8 @@
+name: _diff_viewer
+title: Diff Viewer
+description: Right canvas Git working tree diff viewer for the active chat or task workspace.
+version: 0.1.0
+always_enabled: false
+settings_sections: []
+per_project_config: false
+per_agent_config: false
diff --git a/plugins/_diff_viewer/webui/diff-viewer-panel.html b/plugins/_diff_viewer/webui/diff-viewer-panel.html
new file mode 100644
index 000000000..bb510748b
--- /dev/null
+++ b/plugins/_diff_viewer/webui/diff-viewer-panel.html
@@ -0,0 +1,572 @@
+<html>
+<head>
+ <script type="module">
+ import { store } from "/plugins/_diff_viewer/webui/diff-viewer-store.js";
+ </script>
+</head>
+<body>
+ <div class="diff-viewer-panel" x-data x-create="$store.diffViewer.onMount($el, xAttrs($el) || {})" x-destroy="$store.diffViewer.cleanup()">
+ <template x-if="$store.diffViewer">
+ <div class="diff-viewer-shell">
+ <div class="diff-viewer-toolbar">
+ <div class="diff-viewer-title">
+ <span class="material-symbols-outlined">difference</span>
+ <span>Review</span>
+ </div>
+ <span class="diff-viewer-spacer"></span>
+ <button type="button" class="diff-viewer-icon-button" title="Expand all" aria-label="Expand all" @click="$store.diffViewer.expandAll()" :disabled="!$store.diffViewer.hasChanges()">
+ <span class="material-symbols-outlined">unfold_more</span>
+ </button>
+ <button type="button" class="diff-viewer-icon-button" title="Collapse all" aria-label="Collapse all" @click="$store.diffViewer.collapseAll()" :disabled="!$store.diffViewer.hasChanges()">
+ <span class="material-symbols-outlined">unfold_less</span>
+ </button>
+ <button type="button" class="diff-viewer-icon-button" title="Refresh" aria-label="Refresh" @click="$store.diffViewer.refresh()" :disabled="$store.diffViewer.loading">
+ <span class="material-symbols-outlined" :class="{ spinning: $store.diffViewer.loading }">refresh</span>
+ </button>
+ </div>
+
+ <div class="diff-viewer-summary">
+ <div class="diff-viewer-summary-main">
+ <strong x-text="$store.diffViewer.payload?.totals?.files || 0"></strong>
+ <span>files changed</span>
+ <span class="diff-add" x-text="$store.diffViewer.formatSigned($store.diffViewer.payload?.totals?.additions, '+')"></span>
+ <span class="diff-del" x-text="$store.diffViewer.formatSigned($store.diffViewer.payload?.totals?.deletions, '-')"></span>
+ </div>
+ <div class="diff-viewer-summary-meta">
+ <span x-text="$store.diffViewer.payload?.branch || 'no branch'"></span>
+ <span class="diff-viewer-dot"></span>
+ <span :title="$store.diffViewer.workspacePath" x-text="$store.diffViewer.workspacePath || 'workspace'"></span>
+ </div>
+ </div>
+
+ <div class="diff-viewer-status" x-show="$store.diffViewer.loading || $store.diffViewer.error" style="display: none;">
+ <span class="material-symbols-outlined" :class="{ spinning: $store.diffViewer.loading }" x-text="$store.diffViewer.loading ? 'progress_activity' : 'error'"></span>
+ <span x-text="$store.diffViewer.loading ? 'Loading changes...' : $store.diffViewer.error"></span>
+ </div>
+
+ <div class="diff-viewer-body">
+ <template x-if="$store.diffViewer.payload && !$store.diffViewer.payload.is_git_repo && !$store.diffViewer.loading && !$store.diffViewer.error">
+ <div class="diff-viewer-empty">
+ <span class="material-symbols-outlined">folder_off</span>
+ <strong>Not a Git workspace</strong>
+ <span x-text="$store.diffViewer.workspacePath"></span>
+ </div>
+ </template>
+
+ <template x-if="$store.diffViewer.payload?.is_git_repo && !$store.diffViewer.hasChanges() && !$store.diffViewer.loading && !$store.diffViewer.error">
+ <div class="diff-viewer-empty">
+ <span class="material-symbols-outlined">check_circle</span>
+ <strong>No changes</strong>
+ <span>The selected context workspace is clean.</span>
+ </div>
+ </template>
+
+ <div class="diff-viewer-groups" x-show="$store.diffViewer.hasChanges()" style="display: none;">
+ <template x-for="group in $store.diffViewer.visibleGroups()" :key="group.kind">
+ <section class="diff-viewer-group">
+ <header class="diff-viewer-group-header">
+ <span x-text="$store.diffViewer.groupTitle(group.kind)"></span>
+ <span class="diff-viewer-count" x-text="group.files.length"></span>
+ </header>
+ <template x-for="file in group.files" :key="$store.diffViewer.fileKey(group, file)">
+ <article class="diff-file">
+ <button type="button" class="diff-file-header" @click="$store.diffViewer.toggleFile(group, file)" :title="$store.diffViewer.fileTitle(file)">
+ <span class="material-symbols-outlined diff-file-chevron" x-text="$store.diffViewer.isExpanded(group, file) ? 'expand_less' : 'expand_more'"></span>
+ <span class="diff-file-name" x-text="$store.diffViewer.fileTitle(file)"></span>
+ <span class="diff-file-status" x-text="$store.diffViewer.statusLabel(file)"></span>
+ <span class="diff-file-counts">
+ <span class="diff-add" x-text="$store.diffViewer.formatSigned(file.additions, '+')"></span>
+ <span class="diff-del" x-text="$store.diffViewer.formatSigned(file.deletions, '-')"></span>
+ </span>
+ </button>
+
+ <div class="diff-file-tools" x-show="$store.diffViewer.isExpanded(group, file)" style="display: none;">
+ <button type="button" class="diff-viewer-tool-button" title="Open containing folder" @click="$store.diffViewer.openContainingFolder(file)">
+ <span class="material-symbols-outlined">folder_open</span>
+ <span>Folder</span>
+ </button>
+ <button type="button" class="diff-viewer-tool-button" title="Copy path" @click="$store.diffViewer.copyPath(file)">
+ <span class="material-symbols-outlined">content_copy</span>
+ <span>Path</span>
+ </button>
+ </div>
+
+ <div class="diff-file-body" x-show="$store.diffViewer.isExpanded(group, file)" style="display: none;">
+ <template x-if="file.binary">
+ <div class="diff-file-note">
+ <span class="material-symbols-outlined">data_object</span>
+ <span>Binary file changed.</span>
+ </div>
+ </template>
+ <template x-if="file.too_large && !file.binary">
+ <div class="diff-file-note">
+ <span class="material-symbols-outlined">text_snippet</span>
+ <span>Diff is too large to render inline.</span>
+ </div>
+ </template>
+ <template x-if="!file.binary && !file.too_large && file.patch">
+ <div class="diff-code" role="table" aria-label="Unified diff">
+ <template x-for="line in $store.diffViewer.patchLines(file)" :key="line.id">
+ <div class="diff-line" :class="`is-${line.type}`" role="row">
+ <span class="diff-line-marker" x-text="line.type === 'add' ? '+' : (line.type === 'del' ? '-' : '')"></span>
+ <code x-text="line.text"></code>
+ </div>
+ </template>
+ </div>
+ </template>
+ </div>
+ </article>
+ </template>
+ </section>
+ </template>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .diff-viewer-panel,
+ .diff-viewer-shell {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+ min-width: 0;
+ min-height: 0;
+ background: color-mix(in srgb, var(--color-background) 96%, #000 4%);
+ color: var(--color-text);
+ }
+
+ .diff-viewer-panel {
+ container-type: inline-size;
+ }
+
+ .modal-inner.diff-viewer-modal {
+ box-sizing: border-box;
+ container-type: inline-size;
+ width: min(82vw, 1180px);
+ height: min(88vh, 900px);
+ min-width: min(340px, calc(100vw - 16px));
+ min-height: min(500px, calc(100vh - 16px));
+ max-width: calc(100vw - 16px);
+ max-height: calc(100vh - 16px);
+ resize: both;
+ border: 1px solid color-mix(in srgb, var(--color-border) 75%, transparent);
+ border-radius: 7px;
+ box-shadow: 0 18px 48px rgba(0, 0, 0, 0.32);
+ background: color-mix(in srgb, var(--color-background) 94%, #000 6%);
+ }
+
+ .modal.modal-floating {
+ pointer-events: none;
+ }
+
+ .modal.modal-floating .modal-inner {
+ pointer-events: auto;
+ }
+
+ .modal-inner.diff-viewer-modal .modal-header {
+ min-height: 34px;
+ padding: 0.35rem 0.75rem 0.35rem 1rem;
+ cursor: move;
+ user-select: none;
+ background: color-mix(in srgb, var(--color-background) 92%, #000 8%);
+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 70%, transparent);
+ }
+
+ .modal-inner.diff-viewer-modal .modal-scroll {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: hidden;
+ padding: 0;
+ }
+
+ .modal-inner.diff-viewer-modal .modal-bd.diff-viewer-modal-body {
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ padding: 0;
+ }
+
+ .modal-inner.diff-viewer-modal .modal-bd.diff-viewer-modal-body > x-component,
+ .modal-inner.diff-viewer-modal .modal-bd.diff-viewer-modal-body > div[x-data] {
+ display: flex;
+ flex: 1 1 auto;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ }
+
+ .diff-viewer-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 44px;
+ padding: 7px 9px;
+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 66%, transparent);
+ background: color-mix(in srgb, var(--color-background) 92%, #000 8%);
+ }
+
+ .diff-viewer-title,
+ .diff-viewer-summary-main,
+ .diff-viewer-summary-meta,
+ .diff-viewer-status,
+ .diff-file-counts,
+ .diff-file-tools,
+ .diff-viewer-tool-button,
+ .diff-file-note {
+ display: flex;
+ align-items: center;
+ }
+
+ .diff-viewer-title {
+ gap: 7px;
+ min-width: 0;
+ font-weight: 700;
+ font-size: 0.9rem;
+ }
+
+ .diff-viewer-title .material-symbols-outlined {
+ font-size: 19px;
+ }
+
+ .diff-viewer-spacer {
+ flex: 1 1 auto;
+ min-width: 8px;
+ }
+
+ .diff-viewer-icon-button,
+ .diff-viewer-tool-button {
+ appearance: none;
+ border: 1px solid color-mix(in srgb, var(--color-border) 64%, transparent);
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--color-panel) 80%, transparent);
+ color: var(--color-text);
+ font: inherit;
+ cursor: pointer;
+ }
+
+ .diff-viewer-icon-button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ min-width: 32px;
+ padding: 0;
+ }
+
+ .diff-viewer-tool-button {
+ gap: 5px;
+ min-height: 28px;
+ padding: 4px 8px;
+ font-size: 0.76rem;
+ }
+
+ .diff-viewer-icon-button:hover:not(:disabled),
+ .diff-viewer-tool-button:hover {
+ background: color-mix(in srgb, var(--color-background-hover) 70%, transparent);
+ border-color: color-mix(in srgb, var(--color-primary) 28%, var(--color-border));
+ }
+
+ .diff-viewer-icon-button:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ }
+
+ .diff-viewer-icon-button .material-symbols-outlined,
+ .diff-viewer-tool-button .material-symbols-outlined {
+ font-size: 17px;
+ }
+
+ .diff-viewer-summary {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: 3px;
+ padding: 9px 11px;
+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 54%, transparent);
+ background: color-mix(in srgb, var(--color-panel) 54%, transparent);
+ }
+
+ .diff-viewer-summary-main {
+ gap: 5px;
+ min-width: 0;
+ font-size: 0.86rem;
+ }
+
+ .diff-viewer-summary-meta {
+ gap: 7px;
+ min-width: 0;
+ color: var(--color-text-muted);
+ font-size: 0.74rem;
+ }
+
+ .diff-viewer-summary-meta span:last-child {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .diff-viewer-dot {
+ width: 4px;
+ height: 4px;
+ flex: 0 0 auto;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--color-text-muted) 50%, transparent);
+ }
+
+ .diff-add {
+ color: #31c48d;
+ }
+
+ .diff-del {
+ color: #f05252;
+ }
+
+ .diff-viewer-status {
+ gap: 8px;
+ min-height: 34px;
+ padding: 6px 11px;
+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 44%, transparent);
+ color: var(--color-text-muted);
+ font-size: 0.82rem;
+ }
+
+ .diff-viewer-body {
+ display: flex;
+ flex: 1 1 auto;
+ min-width: 0;
+ min-height: 0;
+ overflow: auto;
+ }
+
+ .diff-viewer-groups {
+ display: flex;
+ flex: 1 1 auto;
+ min-width: 0;
+ flex-direction: column;
+ gap: 12px;
+ padding: 12px;
+ }
+
+ .diff-viewer-group {
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ gap: 7px;
+ }
+
+ .diff-viewer-group-header {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ min-height: 26px;
+ color: var(--color-text);
+ font-size: 0.82rem;
+ font-weight: 700;
+ }
+
+ .diff-viewer-count {
+ min-width: 22px;
+ padding: 2px 6px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--color-panel) 78%, transparent);
+ color: var(--color-text-muted);
+ text-align: center;
+ font-size: 0.72rem;
+ }
+
+ .diff-file {
+ overflow: hidden;
+ border: 1px solid color-mix(in srgb, var(--color-border) 58%, transparent);
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--color-panel) 72%, transparent);
+ }
+
+ .diff-file-header {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto auto;
+ align-items: center;
+ gap: 7px;
+ width: 100%;
+ min-height: 38px;
+ padding: 0 9px;
+ border: 0;
+ background: transparent;
+ color: var(--color-text);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+
+ .diff-file-header:hover {
+ background: color-mix(in srgb, var(--color-background-hover) 56%, transparent);
+ }
+
+ .diff-file-chevron {
+ font-size: 18px;
+ color: var(--color-text-muted);
+ }
+
+ .diff-file-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-family: var(--font-family-code);
+ font-size: 0.78rem;
+ font-weight: 650;
+ }
+
+ .diff-file-status {
+ padding: 2px 6px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--color-background) 70%, transparent);
+ color: var(--color-text-muted);
+ font-size: 0.68rem;
+ text-transform: capitalize;
+ white-space: nowrap;
+ }
+
+ .diff-file-counts {
+ gap: 5px;
+ justify-content: end;
+ min-width: 72px;
+ font-family: var(--font-family-code);
+ font-size: 0.74rem;
+ }
+
+ .diff-file-tools {
+ justify-content: flex-end;
+ gap: 6px;
+ min-height: 34px;
+ padding: 4px 8px;
+ border-top: 1px solid color-mix(in srgb, var(--color-border) 34%, transparent);
+ background: color-mix(in srgb, var(--color-background) 55%, transparent);
+ }
+
+ .diff-file-body {
+ border-top: 1px solid color-mix(in srgb, var(--color-border) 44%, transparent);
+ }
+
+ .diff-file-note {
+ gap: 8px;
+ padding: 12px;
+ color: var(--color-text-muted);
+ font-size: 0.82rem;
+ }
+
+ .diff-code {
+ overflow: auto;
+ padding: 4px 0;
+ background: color-mix(in srgb, var(--color-background) 91%, #000 9%);
+ font-family: var(--font-family-code);
+ font-size: 0.74rem;
+ line-height: 1.45;
+ }
+
+ .diff-line {
+ display: grid;
+ grid-template-columns: 24px minmax(0, 1fr);
+ min-width: max-content;
+ }
+
+ .diff-line-marker {
+ position: sticky;
+ left: 0;
+ z-index: 1;
+ min-height: 1.45em;
+ padding-right: 5px;
+ background: inherit;
+ color: var(--color-text-muted);
+ text-align: right;
+ user-select: none;
+ }
+
+ .diff-line code {
+ display: block;
+ min-height: 1.45em;
+ padding: 0 10px 0 6px;
+ color: inherit;
+ font: inherit;
+ white-space: pre;
+ }
+
+ .diff-line.is-add {
+ background: rgba(39, 174, 96, 0.16);
+ color: color-mix(in srgb, #8df0b0 78%, var(--color-text));
+ }
+
+ .diff-line.is-del {
+ background: rgba(231, 76, 60, 0.17);
+ color: color-mix(in srgb, #ffaaa2 78%, var(--color-text));
+ }
+
+ .diff-line.is-hunk {
+ background: rgba(99, 102, 241, 0.16);
+ color: color-mix(in srgb, #b9c3ff 80%, var(--color-text));
+ }
+
+ .diff-line.is-meta,
+ .diff-line.is-note {
+ color: var(--color-text-muted);
+ }
+
+ .diff-viewer-empty {
+ display: grid;
+ flex: 1 1 auto;
+ place-items: center;
+ align-content: center;
+ gap: 7px;
+ min-width: 0;
+ padding: 24px;
+ color: var(--color-text-muted);
+ text-align: center;
+ }
+
+ .diff-viewer-empty .material-symbols-outlined {
+ font-size: 28px;
+ }
+
+ .diff-viewer-empty span:last-child {
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.78rem;
+ }
+
+ .diff-viewer-panel .spinning {
+ display: inline-block;
+ animation: diff-viewer-spin 0.8s linear infinite;
+ }
+
+ @keyframes diff-viewer-spin {
+ to { transform: rotate(360deg); }
+ }
+
+ @container (max-width: 560px) {
+ .diff-file-header {
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ }
+
+ .diff-file-status {
+ display: none;
+ }
+
+ .diff-viewer-tool-button span:last-child {
+ display: none;
+ }
+ }
+ </style>
+</body>
+</html>
diff --git a/plugins/_diff_viewer/webui/diff-viewer-store.js b/plugins/_diff_viewer/webui/diff-viewer-store.js
new file mode 100644
index 000000000..d13e619c2
--- /dev/null
+++ b/plugins/_diff_viewer/webui/diff-viewer-store.js
@@ -0,0 +1,321 @@
+import { createStore } from "/js/AlpineStore.js";
+import { callJsonApi } from "/js/api.js";
+import { getContext } from "/index.js";
+import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";
+
+const REFRESH_DEBOUNCE_MS = 180;
+
+function lineType(text) {
+ if (text.startsWith("@@")) return "hunk";
+ if (text.startsWith("+++") || text.startsWith("---") || text.startsWith("diff --git") || text.startsWith("index ")) {
+ return "meta";
+ }
+ if (text.startsWith("+")) return "add";
+ if (text.startsWith("-")) return "del";
+ if (text.startsWith("\\ No newline")) return "note";
+ return "context";
+}
+
+function dirname(path) {
+ const clean = String(path || "").replace(/\/+$/, "");
+ const index = clean.lastIndexOf("/");
+ return index > 0 ? clean.slice(0, index) : "";
+}
+
+const model = {
+ loading: false,
+ error: "",
+ payload: null,
+ contextId: "",
+ workspacePath: "",
+ expanded: {},
+ _root: null,
+ _mode: "canvas",
+ _refreshTimer: null,
+ _floatingCleanup: null,
+ _requestSeq: 0,
+
+ async init(element = null) {
+ await this.onMount(element, { mode: "canvas" });
+ },
+
+ async onMount(element = null, options = {}) {
+ if (element) this._root = element;
+ this._mode = options?.mode === "modal" ? "modal" : "canvas";
+ if (this._mode === "modal") {
+ this.setupFloatingModal(element);
+ } else {
+ this.setupCanvasSurface(element);
+ }
+ this.contextId = this.resolveContextId();
+ if (!this.payload && !this.loading) {
+ await this.refresh({ contextId: this.contextId });
+ }
+ },
+
+ async onOpen(payload = {}) {
+ const nextContextId = String(payload.contextId || payload.context_id || this.resolveContextId() || "");
+ await this.refresh({ contextId: nextContextId });
+ },
+
+ cleanup() {
+ if (this._refreshTimer) {
+ clearTimeout(this._refreshTimer);
+ this._refreshTimer = null;
+ }
+ this._floatingCleanup?.();
+ this._floatingCleanup = null;
+ },
+
+ setupFloatingModal(element = null) {
+ this._floatingCleanup?.();
+ const root = element || globalThis.document?.querySelector(".diff-viewer-panel");
+ const modal = root?.closest?.(".modal");
+ const inner = modal?.querySelector?.(".modal-inner");
+ const body = modal?.querySelector?.(".modal-bd");
+ const header = modal?.querySelector?.(".modal-header");
+ if (!modal || !inner || !header) return;
+ modal.classList.add("modal-floating");
+ inner.classList.add("diff-viewer-modal", "modal-no-backdrop");
+ body?.classList?.add("diff-viewer-modal-body");
+
+ const rect = inner.getBoundingClientRect();
+ inner.style.left = `${Math.max(8, rect.left)}px`;
+ inner.style.top = `${Math.max(8, rect.top)}px`;
+ inner.style.transform = "none";
+
+ let drag = null;
+ let resizeObserver = null;
+ const viewportGap = 8;
+ const clampPosition = (left, top) => {
+ const bounds = inner.getBoundingClientRect();
+ const maxLeft = Math.max(viewportGap, globalThis.innerWidth - bounds.width - viewportGap);
+ const maxTop = Math.max(viewportGap, globalThis.innerHeight - bounds.height - viewportGap);
+ return {
+ left: Math.min(Math.max(viewportGap, left), maxLeft),
+ top: Math.min(Math.max(viewportGap, top), maxTop),
+ };
+ };
+ const clampGeometry = () => {
+ const bounds = inner.getBoundingClientRect();
+ const left = Math.max(viewportGap, bounds.left);
+ const top = Math.max(viewportGap, bounds.top);
+ const maxWidth = Math.max(340, globalThis.innerWidth - viewportGap * 2);
+ const maxHeight = Math.max(360, globalThis.innerHeight - viewportGap * 2);
+ if (bounds.width > maxWidth) inner.style.width = `${maxWidth}px`;
+ if (bounds.height > maxHeight) inner.style.height = `${maxHeight}px`;
+ const next = clampPosition(left, top);
+ inner.style.left = `${next.left}px`;
+ inner.style.top = `${next.top}px`;
+ inner.style.maxWidth = `${Math.max(340, globalThis.innerWidth - next.left - viewportGap)}px`;
+ inner.style.maxHeight = `${Math.max(360, globalThis.innerHeight - next.top - viewportGap)}px`;
+ };
+ clampGeometry();
+ globalThis.addEventListener("resize", clampGeometry);
+ if (globalThis.ResizeObserver) {
+ resizeObserver = new ResizeObserver(clampGeometry);
+ resizeObserver.observe(inner);
+ }
+
+ const onPointerMove = (event) => {
+ if (!drag) return;
+ const next = clampPosition(
+ drag.left + event.clientX - drag.x,
+ drag.top + event.clientY - drag.y,
+ );
+ inner.style.left = `${next.left}px`;
+ inner.style.top = `${next.top}px`;
+ clampGeometry();
+ };
+ const onPointerUp = () => {
+ drag = null;
+ globalThis.removeEventListener("pointermove", onPointerMove);
+ globalThis.removeEventListener("pointerup", onPointerUp);
+ try {
+ header.releasePointerCapture?.(header.__diffViewerPanelPointerId || 0);
+ } catch {}
+ };
+ const onPointerDown = (event) => {
+ if (event.button !== 0) return;
+ if (event.target?.closest?.("button, input, select, textarea, a")) return;
+ const current = inner.getBoundingClientRect();
+ drag = {
+ x: event.clientX,
+ y: event.clientY,
+ left: current.left,
+ top: current.top,
+ };
+ header.__diffViewerPanelPointerId = event.pointerId;
+ header.setPointerCapture?.(event.pointerId);
+ globalThis.addEventListener("pointermove", onPointerMove);
+ globalThis.addEventListener("pointerup", onPointerUp);
+ event.preventDefault();
+ };
+ header.addEventListener("pointerdown", onPointerDown);
+
+ this._floatingCleanup = () => {
+ header.removeEventListener("pointerdown", onPointerDown);
+ globalThis.removeEventListener("pointermove", onPointerMove);
+ globalThis.removeEventListener("pointerup", onPointerUp);
+ globalThis.removeEventListener("resize", clampGeometry);
+ resizeObserver?.disconnect?.();
+ };
+ },
+
+ setupCanvasSurface(element = null) {
+ this._floatingCleanup?.();
+ this._floatingCleanup = null;
+ if (element) this._root = element;
+ },
+
+ resolveContextId() {
+ const urlContext = new URLSearchParams(globalThis.location?.search || "").get("ctxid");
+ return getContext?.() || urlContext || globalThis.Alpine?.store?.("chats")?.selected || "";
+ },
+
+ scheduleRefresh(options = {}) {
+ if (this._refreshTimer) clearTimeout(this._refreshTimer);
+ this._refreshTimer = setTimeout(() => {
+ this._refreshTimer = null;
+ this.refresh(options).catch((error) => {
+ console.error("Diff refresh failed", error);
+ });
+ }, REFRESH_DEBOUNCE_MS);
+ },
+
+ async refresh(options = {}) {
+ const contextId = String(options.contextId || options.context_id || this.resolveContextId() || "");
+ const seq = ++this._requestSeq;
+ this.loading = true;
+ this.error = "";
+ try {
+ const response = await callJsonApi("/plugins/_diff_viewer/diff", { context_id: contextId });
+ if (seq !== this._requestSeq) return;
+ if (!response?.ok) {
+ throw new Error(response?.error || "Could not load diff.");
+ }
+ this.payload = response;
+ this.contextId = String(response.context_id || contextId || "");
+ this.workspacePath = String(response.workspace_path || "");
+ this.reconcileExpanded();
+ } catch (error) {
+ if (seq !== this._requestSeq) return;
+ this.error = error instanceof Error ? error.message : String(error);
+ } finally {
+ if (seq === this._requestSeq) this.loading = false;
+ }
+ },
+
+ reconcileExpanded() {
+ const next = {};
+ let index = 0;
+ for (const group of this.visibleGroups()) {
+ for (const file of group.files || []) {
+ const key = this.fileKey(group, file);
+ next[key] = this.expanded[key] ?? index < 4;
+ index += 1;
+ }
+ }
+ this.expanded = next;
+ },
+
+ visibleGroups() {
+ return (this.payload?.groups || []).filter((group) => Array.isArray(group.files) && group.files.length > 0);
+ },
+
+ hasChanges() {
+ return this.visibleGroups().length > 0;
+ },
+
+ groupTitle(kind) {
+ const labels = {
+ staged: "Staged",
+ unstaged: "Unstaged",
+ untracked: "Untracked",
+ };
+ return labels[kind] || kind;
+ },
+
+ statusLabel(file) {
+ return String(file?.status || "changed").replaceAll("_", " ");
+ },
+
+ fileKey(group, file) {
+ return `${group?.kind || "diff"}:${file?.old_path || ""}:${file?.path || ""}`;
+ },
+
+ isExpanded(group, file) {
+ return this.expanded[this.fileKey(group, file)] !== false;
+ },
+
+ toggleFile(group, file) {
+ const key = this.fileKey(group, file);
+ this.expanded[key] = !this.isExpanded(group, file);
+ },
+
+ expandAll() {
+ const next = {};
+ for (const group of this.visibleGroups()) {
+ for (const file of group.files || []) {
+ next[this.fileKey(group, file)] = true;
+ }
+ }
+ this.expanded = next;
+ },
+
+ collapseAll() {
+ const next = {};
+ for (const group of this.visibleGroups()) {
+ for (const file of group.files || []) {
+ next[this.fileKey(group, file)] = false;
+ }
+ }
+ this.expanded = next;
+ },
+
+ patchLines(file) {
+ const patch = String(file?.patch || "");
+ if (!patch) return [];
+ const textLines = patch.endsWith("\n") ? patch.slice(0, -1).split("\n") : patch.split("\n");
+ return textLines.map((text, index) => ({
+ id: `${index}-${text.slice(0, 20)}`,
+ text,
+ type: lineType(text),
+ }));
+ },
+
+ fileTitle(file) {
+ if (file?.old_path && file.old_path !== file.path) {
+ return `${file.old_path} -> ${file.path}`;
+ }
+ return file?.path || file?.old_path || "";
+ },
+
+ formatSigned(value, sign) {
+ const number = Number(value) || 0;
+ return `${sign}${number.toLocaleString()}`;
+ },
+
+ fullPath(file) {
+ const relativePath = String(file?.path || file?.old_path || "").replace(/^\/+/, "");
+ const base = String(this.workspacePath || "").replace(/\/+$/, "");
+ return relativePath ? `${base}/${relativePath}` : base;
+ },
+
+ async openContainingFolder(file) {
+ const parent = dirname(this.fullPath(file));
+ await fileBrowserStore.open(parent || this.workspacePath || "$WORK_DIR");
+ },
+
+ async copyPath(file) {
+ const path = this.fullPath(file);
+ try {
+ await navigator.clipboard.writeText(path);
+ globalThis.justToast?.("Path copied", "success", 1200, "diff-viewer-copy");
+ } catch (_error) {
+ globalThis.prompt?.("Copy path", path);
+ }
+ },
+};
+
+export const store = createStore("diffViewer", model);
diff --git a/plugins/_diff_viewer/webui/main.html b/plugins/_diff_viewer/webui/main.html
new file mode 100644
index 000000000..3830d8c9b
--- /dev/null
+++ b/plugins/_diff_viewer/webui/main.html
@@ -0,0 +1,14 @@
+<html
+ class="diff-viewer-modal modal-no-backdrop"
+ data-canvas-surface="diff"
+ data-canvas-modal-path="/plugins/_diff_viewer/webui/main.html"
+ data-canvas-dock-title="Open Diff in canvas"
+ data-canvas-dock-icon="dock_to_right"
+>
+<head>
+ <title>Diff</title>
+</head>
+<body class="diff-viewer-modal-body">
+ <x-component path="/plugins/_diff_viewer/webui/diff-viewer-panel.html" mode="modal"></x-component>
+</body>
+</html>
diff --git a/tests/test_diff_viewer.py b/tests/test_diff_viewer.py
new file mode 100644
index 000000000..f8fed240d
--- /dev/null
+++ b/tests/test_diff_viewer.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import asyncio
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from flask import Flask
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+if str(PROJECT_ROOT) not in sys.path:
+ sys.path.insert(0, str(PROJECT_ROOT))
+
+from plugins._diff_viewer.helpers import diff as diff_helper
+from plugins._diff_viewer.helpers.diff import collect_workspace_diff
+
+
+def run_git(repo_dir: Path, *args: str) -> str:
+ completed = subprocess.run(
+ ["git", "-C", str(repo_dir), *args],
+ check=True,
+ text=True,
+ capture_output=True,
+ )
+ return completed.stdout.strip()
+
+
+def init_repo(repo_dir: Path) -> None:
+ run_git(repo_dir, "init")
+ run_git(repo_dir, "config", "user.name", "Test User")
+ run_git(repo_dir, "config", "user.email", "[email protected]")
+ (repo_dir / "tracked.txt").write_text("one\n", encoding="utf-8")
+ run_git(repo_dir, "add", "tracked.txt")
+ run_git(repo_dir, "commit", "-m", "initial")
+
+
+def files_for_group(payload: dict, kind: str) -> list[dict]:
+ return next(group["files"] for group in payload["groups"] if group["kind"] == kind)
+
+
+def test_collect_workspace_diff_returns_non_git_state(tmp_path: Path) -> None:
+ payload = collect_workspace_diff(str(tmp_path), context_id="ctx")
+
+ assert payload["ok"] is True
+ assert payload["context_id"] == "ctx"
+ assert payload["is_git_repo"] is False
+ assert payload["totals"] == {"files": 0, "additions": 0, "deletions": 0}
+
+
+def test_collect_workspace_diff_groups_staged_unstaged_and_untracked(tmp_path: Path) -> None:
+ init_repo(tmp_path)
+ (tmp_path / "tracked.txt").write_text("one\nstaged\n", encoding="utf-8")
+ run_git(tmp_path, "add", "tracked.txt")
+ (tmp_path / "tracked.txt").write_text("one\nstaged\nunstaged\n", encoding="utf-8")
+ (tmp_path / "new.txt").write_text("hello\n", encoding="utf-8")
+
+ payload = collect_workspace_diff(str(tmp_path))
+
+ staged = files_for_group(payload, "staged")
+ unstaged = files_for_group(payload, "unstaged")
+ untracked = files_for_group(payload, "untracked")
+ assert staged[0]["path"] == "tracked.txt"
+ assert staged[0]["status"] == "modified"
+ assert "+staged" in staged[0]["patch"]
+ assert unstaged[0]["path"] == "tracked.txt"
+ assert "+unstaged" in unstaged[0]["patch"]
+ assert untracked[0]["path"] == "new.txt"
+ assert untracked[0]["status"] == "untracked"
+ assert "+hello" in untracked[0]["patch"]
+ assert payload["totals"]["files"] == 2
+ assert payload["totals"]["additions"] == 3
+
+
+def test_collect_workspace_diff_ignores_zero_line_gitkeep(tmp_path: Path) -> None:
+ init_repo(tmp_path)
+ (tmp_path / ".gitkeep").write_text("", encoding="utf-8")
+ (tmp_path / "nested").mkdir()
+ (tmp_path / "nested" / ".gitkeep").write_text("", encoding="utf-8")
+ (tmp_path / "real.txt").write_text("real\n", encoding="utf-8")
+ run_git(tmp_path, "add", ".gitkeep")
+
+ payload = collect_workspace_diff(str(tmp_path))
+ paths = [
+ item["path"]
+ for group in payload["groups"]
+ for item in group["files"]
+ ]
+
+ assert ".gitkeep" not in paths
+ assert "nested/.gitkeep" not in paths
+ assert paths == ["real.txt"]
+ assert payload["totals"] == {"files": 1, "additions": 1, "deletions": 0}
+
+
+def test_collect_workspace_diff_deleted_renamed_binary_large_and_a0_exclusion(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ init_repo(tmp_path)
+ (tmp_path / "rename_me.txt").write_text("move\n", encoding="utf-8")
+ (tmp_path / "delete_me.txt").write_text("delete\n", encoding="utf-8")
+ run_git(tmp_path, "add", "rename_me.txt", "delete_me.txt")
+ run_git(tmp_path, "commit", "-m", "fixtures")
+
+ run_git(tmp_path, "mv", "rename_me.txt", "renamed.txt")
+ (tmp_path / "delete_me.txt").unlink()
+ (tmp_path / "binary.bin").write_bytes(b"\x00\x01data")
+ (tmp_path / ".a0proj").mkdir()
+ (tmp_path / ".a0proj" / "project.json").write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(diff_helper, "MAX_UNTRACKED_BYTES", 10)
+ (tmp_path / "large.txt").write_text("0123456789\n" * 5, encoding="utf-8")
+
+ payload = collect_workspace_diff(str(tmp_path))
+ staged = files_for_group(payload, "staged")
+ unstaged = files_for_group(payload, "unstaged")
+ untracked = files_for_group(payload, "untracked")
+
+ git_changes = staged + unstaged
+ statuses = {(item["path"], item["status"]) for item in git_changes}
+ assert ("delete_me.txt", "deleted") in statuses
+ assert ("renamed.txt", "renamed") in statuses
+ renamed = next(item for item in git_changes if item["path"] == "renamed.txt")
+ assert renamed["old_path"] == "rename_me.txt"
+ assert renamed["additions"] == 0
+ assert renamed["deletions"] == 0
+ binary = next(item for item in untracked if item["path"] == "binary.bin")
+ assert binary["binary"] is True
+ large = next(item for item in untracked if item["path"] == "large.txt")
+ assert large["too_large"] is True
+ assert all(not item["path"].startswith(".a0proj") for item in untracked)
+
+
+def test_collect_workspace_diff_limits_nested_workspace_to_pathspec(tmp_path: Path) -> None:
+ init_repo(tmp_path)
+ (tmp_path / "outside.txt").write_text("outside\n", encoding="utf-8")
+ (tmp_path / "nested").mkdir()
+ (tmp_path / "nested" / "inside.txt").write_text("inside\n", encoding="utf-8")
+
+ payload = collect_workspace_diff(str(tmp_path / "nested"))
+ untracked = files_for_group(payload, "untracked")
+
+ assert [item["path"] for item in untracked] == ["inside.txt"]
+
+
+def test_diff_api_resolves_project_context_workspace(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pytest.importorskip("whisper")
+ pytest.importorskip("langchain_core")
+ from plugins._diff_viewer.api import diff as diff_api
+
+ init_repo(tmp_path)
+ (tmp_path / "changed.txt").write_text("changed\n", encoding="utf-8")
+ handler = diff_api.Diff(Flask("diff-test"), threading.RLock())
+ monkeypatch.setattr(handler, "use_context", lambda context_id: SimpleNamespace(id=context_id))
+ monkeypatch.setattr(diff_api.projects, "get_context_project_name", lambda _context: "demo")
+ monkeypatch.setattr(diff_api.projects, "get_project_folder", lambda _name: str(tmp_path))
+ monkeypatch.setattr(diff_api.files, "normalize_a0_path", lambda path: path)
+ monkeypatch.setattr(diff_api.files, "fix_dev_path", lambda path: path)
+
+ payload = asyncio.run(handler.process({"context_id": "ctx-project"}, None))
+
+ assert isinstance(payload, dict)
+ assert payload["ok"] is True
+ assert payload["context_id"] == "ctx-project"
+ assert payload["workspace_path"] == str(tmp_path)
+ assert files_for_group(payload, "untracked")[0]["path"] == "changed.txt"
+
+
+def test_diff_api_falls_back_to_default_workdir(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pytest.importorskip("whisper")
+ pytest.importorskip("langchain_core")
+ from plugins._diff_viewer.api import diff as diff_api
+
+ init_repo(tmp_path)
+ (tmp_path / "workdir.txt").write_text("workdir\n", encoding="utf-8")
+ handler = diff_api.Diff(Flask("diff-test-default"), threading.RLock())
+ monkeypatch.setattr(diff_api.settings, "get_settings", lambda: {"workdir_path": str(tmp_path)})
+ monkeypatch.setattr(diff_api.files, "fix_dev_path", lambda path: path)
+
+ payload = asyncio.run(handler.process({}, None))
+
+ assert isinstance(payload, dict)
+ assert payload["workspace_path"] == str(tmp_path)
+ assert files_for_group(payload, "untracked")[0]["path"] == "workdir.txt"
diff --git a/webui/js/modals.js b/webui/js/modals.js
index fb53f9441..764faa429 100644
--- a/webui/js/modals.js
+++ b/webui/js/modals.js
@@ -58,6 +58,8 @@ function modalSuppressesBackdrop(modal) {
|| path === "plugins/_browser/webui/main.html"
|| path === "/plugins/_office/webui/main.html"
|| path === "plugins/_office/webui/main.html"
+ || path === "/plugins/_diff_viewer/webui/main.html"
+ || path === "plugins/_diff_viewer/webui/main.html"
|| modal?.element?.classList?.contains("modal-floating")
|| modal?.element?.classList?.contains("modal-no-backdrop")
|| modal?.inner?.classList?.contains("modal-no-backdrop");