[W9-4] Add code-snippet viewer for revision findings (#532)

Backend: GET /git/file reads a file at a branch tip (read_file_at_branch)
and slices it to a line window — explicit start/end, a line+context center,
or the whole file capped at 2000 lines. _compute_file_range is the pure
helper (unit-tested).

Frontend: useGitFile hook + CodeSnippet (styled <pre>, line numbers, active-
line highlight — matches git-diff-viewer, no shiki). Wired into FindingCard
so each file:line finding shows the surrounding source. Fail-open: a missing
file renders a muted hint, never breaks the card.

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-07-15 04:34:12 +02:00
committed by GitHub
co-authored by Renn F
parent 1054538d2f
commit f07e2420a8
10 changed files with 427 additions and 2 deletions
@@ -0,0 +1,97 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import React from "react";
// Stub useGitFile so CodeSnippet is tested in isolation from TanStack Query.
const { useGitFile } = vi.hoisted(() => ({ useGitFile: vi.fn() }));
vi.mock("@/hooks/use-git", () => ({ useGitFile }));
import { CodeSnippet } from "../code-snippet";
interface MockReturn {
data?: {
branch: string;
path: string;
content: string;
start_line: number;
total_lines: number;
truncated: boolean;
} | null;
isLoading?: boolean;
isError?: boolean;
}
function mockReturn(r: MockReturn) {
useGitFile.mockReturnValue({
data: r.data ?? null,
isLoading: r.isLoading ?? false,
isError: r.isError ?? false,
});
}
describe("CodeSnippet", () => {
it("renders line numbers and the truncated note for a loaded slice", () => {
mockReturn({
data: {
branch: "feature/backend/abc",
path: "roboco/services/task.py",
content: "import os\n\ndef x():\n pass",
start_line: 40,
total_lines: 200,
truncated: true,
},
});
const { container } = render(
<CodeSnippet branch="feature/backend/abc" file="roboco/services/task.py" activeLine={42} />,
);
// Line numbers start at 40 for the 4 content lines.
expect(screen.getByText("40")).toBeInTheDocument();
expect(screen.getByText("43")).toBeInTheDocument();
expect(screen.getByText("def x():")).toBeInTheDocument();
expect(
screen.getByText(/showing lines 4043 of 200/),
).toBeInTheDocument();
// Sanity: only one snippet block rendered.
expect(container.querySelectorAll("pre")).toHaveLength(1);
});
it("highlights the active line", () => {
mockReturn({
data: {
branch: "b",
path: "p.py",
content: "a\nb\nc",
start_line: 1,
total_lines: 3,
truncated: false,
},
});
render(<CodeSnippet branch="b" file="p.py" activeLine={2} />);
// The active line's content is "b"; its row carries the highlight class.
const row = screen.getByText("b").parentElement;
expect(row?.className).toContain("bg-blue-500/15");
});
it("renders the fail-open hint on an error", () => {
mockReturn({ isError: true });
render(<CodeSnippet branch="b" file="p.py" activeLine={1} />);
expect(screen.getByText(/Couldnt load this file/)).toBeInTheDocument();
});
it("renders a skeleton while loading", () => {
mockReturn({ isLoading: true });
const { container } = render(
<CodeSnippet branch="b" file="p.py" activeLine={1} />,
);
expect(container.querySelector(".animate-pulse")).not.toBeNull();
});
it("renders nothing when branch is missing", () => {
mockReturn({ data: null });
const { container } = render(
<CodeSnippet branch={null} file="p.py" activeLine={1} />,
);
expect(container.firstChild).toBeNull();
});
});
+84
View File
@@ -0,0 +1,84 @@
"use client";
import { useGitFile } from "@/hooks/use-git";
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
interface CodeSnippetProps {
branch: string | null | undefined;
file: string | null | undefined;
activeLine?: number | null;
context?: number;
}
// A compact file-content window for a revision finding: shows the lines around
// `activeLine` from `branch:file`, with the flagged line highlighted. Lazy and
// fail-open — a missing/deleted file renders a muted hint, never breaks the
// finding card. Styled to match git-diff-viewer's <pre> convention.
export function CodeSnippet({
branch,
file,
activeLine,
context = 10,
}: CodeSnippetProps) {
const enabled = !!branch && !!file;
const { data, isLoading, isError } = useGitFile(
branch,
file,
activeLine ?? undefined,
context,
enabled,
);
if (!enabled) return null;
if (isLoading) {
return <Skeleton className="h-24 w-full rounded" />;
}
if (isError || !data || !data.content) {
return (
<p className="text-xs text-muted-foreground">
Couldnt load this files content from {branch}.
</p>
);
}
const lines = data.content.split("\n");
const active = activeLine ?? null;
return (
<div className="rounded border bg-muted/30">
<ScrollArea className="h-64">
<pre className="p-2 font-mono text-[11px] leading-relaxed sm:text-xs">
{lines.map((text, i) => {
const lineNo = data.start_line + i;
const isActive = active != null && lineNo === active;
return (
<div
key={i}
className={cn(
"flex gap-3 px-2 -mx-2 rounded-sm",
isActive &&
"bg-blue-500/15 ring-1 ring-inset ring-blue-500/30",
)}
>
<span className="select-none w-8 shrink-0 text-right text-muted-foreground/60">
{lineNo}
</span>
<span className="whitespace-pre">{text || " "}</span>
</div>
);
})}
</pre>
</ScrollArea>
{data.truncated && (
<p className="border-t px-2 py-1 text-[10px] text-muted-foreground">
showing lines {data.start_line}{data.start_line + lines.length - 1}{" "}
of {data.total_lines}
</p>
)}
</div>
);
}
@@ -11,6 +11,12 @@ const { useTaskFindings } = vi.hoisted(() => ({ useTaskFindings: vi.fn() }));
vi.mock("@/hooks/use-tasks", () => ({ useTaskFindings }));
// CodeSnippet runs a real useQuery (needs a QueryClient); stub it so the
// findings test stays focused on grouping/rendering, not git fetching.
vi.mock("@/components/git/code-snippet", () => ({
CodeSnippet: () => <div data-testid="code-snippet" />,
}));
import { TabFindings } from "../tab-findings";
function buildTask(overrides: Partial<Task> = {}): Task {
@@ -7,6 +7,7 @@ import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { ListChecks } from "lucide-react";
import { CodeSnippet } from "@/components/git/code-snippet";
interface TabFindingsProps {
task: Task;
@@ -37,7 +38,13 @@ const ORIGIN_LABEL: Record<string, string> = {
ceo: "CEO",
};
function FindingCard({ finding }: { finding: TaskFinding }) {
function FindingCard({
finding,
branch,
}: {
finding: TaskFinding;
branch: string | null;
}) {
return (
<Card>
<CardContent className="pt-4 space-y-2">
@@ -65,6 +72,13 @@ function FindingCard({ finding }: { finding: TaskFinding }) {
</code>
)}
</div>
{finding.file && (
<CodeSnippet
branch={branch}
file={finding.file}
activeLine={finding.line}
/>
)}
<div className="space-y-1 text-sm">
<p>
<span className="text-muted-foreground">Expected:</span>{" "}
@@ -154,7 +168,7 @@ export function TabFindings({ task }: TabFindingsProps) {
</div>
<div className="space-y-3">
{group.items.map((f) => (
<FindingCard key={f.id} finding={f} />
<FindingCard key={f.id} finding={f} branch={task.branch_name} />
))}
</div>
</div>
+22
View File
@@ -11,6 +11,7 @@ import type {
GitLogResponse,
GitBranchListResponse,
GitDiffResponse,
GitFileContentResponse,
GitCommitRequest,
GitCommitResponse,
GitPushRequest,
@@ -45,6 +46,8 @@ export const gitKeys = {
[...gitKeys.all, "branches", projectSlug, { includeRemote }] as const,
diff: (projectSlug: string, staged?: boolean, filePath?: string) =>
[...gitKeys.all, "diff", projectSlug, { staged, filePath }] as const,
file: (branch: string, path: string, line?: number, context?: number) =>
[...gitKeys.all, "file", branch, path, { line, context }] as const,
};
// =============================================================================
@@ -118,6 +121,25 @@ export function useGitDiff(
});
}
/**
* Read a file at a branch tip, sliced around an optional line.
*/
export function useGitFile(
branch: string | null | undefined,
path: string | null | undefined,
line: number | null | undefined,
context: number = 10,
enabled: boolean = true,
) {
return useQuery<GitFileContentResponse>({
queryKey: gitKeys.file(branch ?? "", path ?? "", line ?? undefined, context),
queryFn: () => gitApi.getFile(branch!, path!, line ?? undefined, context),
enabled: enabled && !!branch && !!path,
staleTime: 60000, // 1 minute — branch content is stable
retry: false, // a 404 (file gone) shouldn't retry forever
});
}
// =============================================================================
// Mutation Hooks
// =============================================================================
+30
View File
@@ -11,6 +11,7 @@ import type {
GitLogResponse,
GitBranchListResponse,
GitDiffResponse,
GitFileContentResponse,
GitCommitRequest,
GitCommitResponse,
GitPushRequest,
@@ -160,6 +161,35 @@ export const gitApi = {
return data;
},
/**
* Read a file's content at a branch tip, sliced to a line window.
*/
getFile: async (
branch: string,
path: string,
line?: number,
context: number = 10,
): Promise<GitFileContentResponse> => {
if (isMockMode()) {
const lines = Array.from(
{ length: 5 },
(_, i) => `// mock line ${i + 1}`,
);
return {
branch,
path,
content: lines.join("\n"),
start_line: 1,
total_lines: lines.length,
truncated: false,
};
}
const { data } = await api.get<GitFileContentResponse>("/git/file", {
params: { branch, path, line, context },
});
return data;
},
// ===========================================================================
// WRITE OPERATIONS
// ===========================================================================
+9
View File
@@ -54,6 +54,15 @@ export interface GitDiffResponse {
files_changed: number;
}
export interface GitFileContentResponse {
branch: string;
path: string;
content: string;
start_line: number;
total_lines: number;
truncated: boolean;
}
export interface GitCommitResponse {
commit_hash: string;
message: string;