Generic platform points for the `diff-viewer` and `commits` plugins (ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and match.hasReport; `pathShims` (a git PATH shim for every harness) with out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`); `conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for Project/Service "Recent commits". The core commit card, Changes view, diff page and review store are gone; bash_diff.py keeps bashDiff only. Legacy gitCommits / commit-line parsing stays for past transcripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
11 KiB
Python
246 lines
11 KiB
Python
"""The diff view: a conversation's commits, their diffs and the uncommitted changes."""
|
||
|
||
import pathlib
|
||
import threading
|
||
|
||
from fastapi import APIRouter, HTTPException
|
||
from fastapi.responses import Response
|
||
|
||
import schemas
|
||
from conversations import ids
|
||
from conversations.catalog import _resolve_transcript, _summary_and_meta
|
||
from core.http import _r
|
||
from core.state import State
|
||
from diff import convcommits, editsdiff, gitdiff, worktreediff
|
||
from users import access
|
||
from users.caller import Caller, CallerDep
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
def _repo_allowed(caller: Caller, repo: str) -> None:
|
||
"""A guest reads diffs of their projects' repos only (``project:<slug>``)."""
|
||
if caller.is_owner:
|
||
return
|
||
kind, _, slug = (repo or "").partition(":")
|
||
if kind != "project" or not caller.can(slug, "view"):
|
||
raise HTTPException(404, "commit not found")
|
||
|
||
|
||
def _viewed_by(caller: Caller, summary: dict, meta: dict) -> tuple[dict, dict]:
|
||
"""The repos a conversation's diff tabs may open for ``caller``: a guest
|
||
gets their granted projects only. The transcript-derived ones
|
||
(``projectsAuto``, ``servicesAuto``, ``worktreesAuto`` — any path a Bash
|
||
command so much as named) are not a grant: echoing an owner worktree's
|
||
name once put its live diff in the guest's Changes tab."""
|
||
if caller.is_owner:
|
||
return summary, meta
|
||
|
||
def ok(slug) -> bool:
|
||
return caller.can(slug, "view")
|
||
|
||
def own_worktree(e) -> bool:
|
||
name = (e or {}).get("dir") or (e or {}).get("name")
|
||
wt = worktreediff.resolve(name) if name else None
|
||
kind, _, slug = ((wt or {}).get("repo") or "").partition(":")
|
||
return kind == "project" and ok(slug)
|
||
|
||
projects = [p for p in meta.get("projects") or [] if ok(p)]
|
||
auto = [p for p in summary.get("projectsAuto") or [] if ok(p)]
|
||
summary = {**summary, "projectsAuto": auto, "servicesAuto": [],
|
||
"worktreesAuto": [e for e in summary.get("worktreesAuto") or []
|
||
if own_worktree(e)]}
|
||
meta = {**meta, "projects": projects, "services": [],
|
||
"worktrees": [e for e in meta.get("worktrees") or [] if own_worktree(e)]}
|
||
if not projects and not auto:
|
||
# Nothing of theirs: never the superproject fallback a commit or a
|
||
# worktree with no project would otherwise scan.
|
||
summary.update(worktreesAuto=[], lifecycleAuto={})
|
||
meta.update(worktrees=[], committed=False, gitCommits=[])
|
||
return summary, meta
|
||
|
||
|
||
@router.get("/api/conversation-commits", responses=_r(schemas.ConversationCommits))
|
||
def conversation_commits(deps: State, caller: CallerDep, id: str):
|
||
"""The commits a conversation made — its own record (exact, workers
|
||
included), else the time-window guess for an older lab conversation."""
|
||
id = ids.canonical(id) or id # echoed back: an old link's path → uid
|
||
access.ensure_visible(deps, caller, id)
|
||
sid, summary, meta = _summary_and_meta(deps, id)
|
||
summary, meta = _viewed_by(caller, summary, meta)
|
||
data = convcommits.conversation_commits(deps, summary, meta, sid)
|
||
return {"id": id, **data}
|
||
|
||
|
||
@router.get("/api/conversation-commit-diff", responses=_r(schemas.DiffResult))
|
||
def conversation_commit_diff(deps: State, caller: CallerDep, id: str, sha: str,
|
||
root: str | None = None):
|
||
"""One of the conversation's commits: from the lab's git, the patch the
|
||
transcript carries, or the worker it ran on (cached once read).
|
||
|
||
``root``: the repo root a path shim's report named (the commits plugin),
|
||
for a commit the transcript never showed — read from the lab's repo at
|
||
that root, or the worker the conversation ran on. A guest: a lab repo of
|
||
their projects only, a worker only when it is their own computer."""
|
||
access.ensure_visible(deps, caller, id)
|
||
sid, summary, meta = _summary_and_meta(deps, id)
|
||
summary, meta = _viewed_by(caller, summary, meta)
|
||
data = convcommits.conversation_commits(deps, summary, meta, sid)
|
||
hint = None
|
||
if root and not any(c.get("sha") and convcommits.gitcommits.same(c["sha"], sha)
|
||
for c in data["commits"]):
|
||
hint = _root_hint(deps, caller, summary, meta, data, sha, root)
|
||
return convcommits.commit_diff(deps, _resolve_transcript(id), summary, data, sha,
|
||
hint=hint)
|
||
|
||
|
||
def _root_hint(deps, caller: Caller, summary: dict, meta: dict, data: dict,
|
||
sha: str, root: str) -> dict | None:
|
||
"""The record of a commit named by ``root`` only, when ``caller`` may read
|
||
it there (None: the route's 404)."""
|
||
lab_repos = gitdiff._conversation_repos(summary, meta)
|
||
fallback = [*lab_repos[0], *(["super:_"] if lab_repos[2] else [])]
|
||
c = convcommits.hinted_commit(data, sha, root, lab_repos=fallback)
|
||
if c is None or caller.is_owner:
|
||
return c
|
||
if c.get("worker"):
|
||
w = deps.worker_store.get(c["worker"]) or {}
|
||
return c if w.get("owner") == caller.id else None
|
||
try:
|
||
_repo_allowed(caller, c["repo"])
|
||
except HTTPException:
|
||
return None
|
||
return c
|
||
|
||
|
||
@router.get("/api/commit-diff", responses=_r(schemas.DiffResult))
|
||
def commit_diff(caller: CallerDep, repo: str, sha: str):
|
||
"""Structured per-file hunk diff of a single commit within a repo token."""
|
||
_repo_allowed(caller, repo)
|
||
out = gitdiff.commit_diff(repo, sha)
|
||
if out is None:
|
||
raise HTTPException(404, "commit not found")
|
||
return out
|
||
|
||
|
||
# Content-type for image blobs served in the diff view (the only kind the diff
|
||
# viewer requests). Anything else falls back to octet-stream.
|
||
_IMAGE_CT = {
|
||
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
||
".gif": "image/gif", ".webp": "image/webp", ".bmp": "image/bmp",
|
||
".avif": "image/avif", ".svg": "image/svg+xml", ".ico": "image/x-icon",
|
||
}
|
||
|
||
|
||
@router.get("/api/diff-blob")
|
||
def diff_blob(caller: CallerDep, repo: str, path: str, sha: str | None = None,
|
||
wt: str | None = None):
|
||
"""Raw bytes of a file inside a diff — the image side rendered in the viewer.
|
||
|
||
``repo`` is a diff repo token (``project:`` / ``service:`` / ``super:_``),
|
||
``path`` is repo-relative. With ``sha`` the file is read at that rev (e.g. the
|
||
commit's tip for an added image, or ``<sha>^`` for a deleted one); without it
|
||
the current working-tree copy is served (conversation / uncommitted diffs).
|
||
``wt`` names a worktree directory — the file is then read from that worktree
|
||
instead of the canonical checkout (see worktreediff)."""
|
||
_repo_allowed(caller, repo)
|
||
ext = pathlib.PurePosixPath(path).suffix.lower()
|
||
if not caller.is_owner and (wt or ext not in _IMAGE_CT
|
||
or not gitdiff.guest_may_read(repo, path)):
|
||
# A guest gets a diff's images — what this route draws — never a
|
||
# working-tree .env nor a file outside their project.
|
||
raise HTTPException(404, "blob not found")
|
||
data = (worktreediff.blob_bytes(wt, path) if wt
|
||
else gitdiff.blob_bytes(repo, path, sha=sha))
|
||
if data is None:
|
||
raise HTTPException(404, "blob not found")
|
||
ct = _IMAGE_CT.get(ext, "application/octet-stream")
|
||
return Response(content=data, media_type=ct, headers=_BLOB_HEADERS)
|
||
|
||
|
||
# These are a repo's bytes — a guest's project's — on the app's own origin, and
|
||
# an SVG is a document: opened by its URL (a link, a frame) its <script> would
|
||
# run as the app, with the viewer's session. nosniff doesn't stop that. The
|
||
# sandbox policy does: the response is an opaque origin with no script, no
|
||
# requests, no plugins — while <img src> draws it exactly as before (a policy
|
||
# on an image response doesn't apply to the page embedding it).
|
||
_BLOB_HEADERS = {
|
||
"X-Content-Type-Options": "nosniff",
|
||
"Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'",
|
||
"Cache-Control": "public, max-age=3600",
|
||
}
|
||
|
||
|
||
# Replaying a transcript's edits re-reads the whole file; during a live run the
|
||
# panel refetches on every SSE ping, so cache per (path, mtime, size, commits).
|
||
_udiff_cache: dict[str, tuple[tuple, dict]] = {}
|
||
_UDIFF_CACHE_CAP = 8
|
||
_udiff_lock = threading.Lock()
|
||
|
||
|
||
@router.get("/api/conversation-uncommitted-diff", responses=_r(schemas.DiffResult))
|
||
def conversation_uncommitted_diff(deps: State, caller: CallerDep, id: str,
|
||
stats: bool = False):
|
||
"""The conversation's current not-yet-committed changes.
|
||
|
||
When it worked in a git worktree that still exists, this is a **real**
|
||
``git diff HEAD`` (+ untracked files) read from that worktree — see
|
||
worktreediff. Otherwise (or for edits made outside it) the changes are
|
||
replayed from the transcript's accumulated edits/creates/deletes (editsdiff).
|
||
``stats`` strips the hunks — the detail panel only needs paths and +/− counts.
|
||
"""
|
||
access.ensure_visible(deps, caller, id)
|
||
sid, summary, meta = _summary_and_meta(deps, id)
|
||
summary, meta = _viewed_by(caller, summary, meta)
|
||
ap = _resolve_transcript(id)
|
||
data = convcommits.conversation_commits(deps, summary, meta, sid)
|
||
wt_out = worktreediff.worktree_diff(summary, meta,
|
||
summary.get("title") or "", stats=stats)
|
||
try:
|
||
st = ap.stat()
|
||
sig = (st.st_mtime, st.st_size,
|
||
tuple(c.get("sha") for c in data["commits"]))
|
||
except OSError:
|
||
sig = None
|
||
out = None
|
||
with _udiff_lock:
|
||
hit = _udiff_cache.get(str(ap))
|
||
if hit and sig and hit[0] == sig:
|
||
out = hit[1]
|
||
if out is None:
|
||
out = editsdiff.uncommitted_diff(ap, summary.get("title") or "",
|
||
data["commits"])
|
||
if sig:
|
||
with _udiff_lock:
|
||
_udiff_cache[str(ap)] = (sig, out)
|
||
while len(_udiff_cache) > _UDIFF_CACHE_CAP:
|
||
_udiff_cache.pop(next(iter(_udiff_cache)))
|
||
if stats:
|
||
out = {**out, "files": [{**f, "hunks": []} for f in out["files"]]}
|
||
if wt_out is None:
|
||
return out
|
||
# A live worktree is authoritative for its own repo, so the replay only
|
||
# contributes what it saw *elsewhere* (e.g. a stray edit in the main
|
||
# checkout) — otherwise reverted or already-committed files would linger.
|
||
covered = {w["repo"] for w in wt_out["worktrees"]}
|
||
extra = [f for f in out["files"] if f.get("repo") not in covered]
|
||
if not extra:
|
||
return wt_out
|
||
files = wt_out["files"] + extra
|
||
wts = wt_out["worktrees"]
|
||
return {**wt_out, "files": files, "approx": True,
|
||
"additions": sum(f["additions"] for f in files),
|
||
"deletions": sum(f["deletions"] for f in files),
|
||
"subtitle": worktreediff.subtitle(wts, len(files), len(extra))}
|
||
|
||
|
||
@router.get("/api/conversation-diff", responses=_r(schemas.DiffResult))
|
||
def conversation_diff(deps: State, caller: CallerDep, id: str):
|
||
"""The net diff across the conversation's commits (merges left out)."""
|
||
access.ensure_visible(deps, caller, id)
|
||
sid, summary, meta = _summary_and_meta(deps, id)
|
||
summary, meta = _viewed_by(caller, summary, meta)
|
||
data = convcommits.conversation_commits(deps, summary, meta, sid)
|
||
title = summary.get("title") or "Conversation changes"
|
||
return convcommits.net_diff(deps, _resolve_transcript(id), summary, data, title)
|