Open-source, local-first AI agent for real work.
TypeScript agent-toolsai-agentbyokcoding-agentcross-platformdesktop-appdeveloper-toolselectronharnessknowledge-basellmwikilocal-firstmcpplugin-systemprivacy-firstskillstypescriptvettaworkflow-automation
import type { DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
import { useTranslation } from "@vetta-org/plugin-sdk";
import { Button } from "@vetta-org/ui";
import type { KeyboardEvent } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { buildReviewPrompt, excerptFromPatch } from "../git/reviewPrompt";
import { getConversationApi, notifyError, resizePanel } from "../git/runtime";
import type { ReviewComment, TurnReview } from "../git/turnReview";
import { addReviewComment, clearReviewFeedback, removeReviewComment, setReviewNote } from "../git/turnReview";
import type { TurnFileChange } from "../git/turnSnapshot";
import { snapshotFileDiff } from "../git/turnSnapshot";
import { FileTypeIcon } from "./FileTypeIcon";
import { CommentIcon, FileIcon, RedoIcon, SendIcon, SplitViewIcon, UndoIcon, UnifiedViewIcon } from "./icons";
import { PatchContent } from "./PatchContent";
import type { CommentRange } from "./ReviewAnnotations";
import { ReviewCommentCard, ReviewCommentComposer } from "./ReviewAnnotations";
import { SplitHandle } from "./SplitHandle";
import { StatusBadge } from "./StatusBadge";
import { TurnFileRow } from "./TurnFileRow";
import { useTurnFileActions } from "./useTurnFileActions";
// 与变更视图同一套宽窄阈值:宽到放得下「列表 + 一屏能读的 diff」才并排。
const DIFF_MIN_WIDTH = 560;
const LIST_DEFAULT_WIDTH = 280;
const LIST_MIN_WIDTH = 180;
const DIFF_RESERVED_WIDTH = 260;
/** Shared with the changes view, so both diffs open in the layout last picked. */
const DIFF_STYLE_KEY = "vetta-git-diff-style";
type AnnotationData = { kind: "comment"; comment: ReviewComment } | { kind: "draft"; range: CommentRange };
function basename(path: string): string {
const i = path.lastIndexOf("/");
return i < 0 ? path : path.slice(i + 1);
}
function toCommentRange(range: SelectedLineRange): CommentRange {
return {
side: range.side ?? range.endSide ?? "additions",
start: Math.min(range.start, range.end),
end: Math.max(range.start, range.end),
};
}
/**
* The panel's "last turn" view: every file the turn changed, its diff between
* the two turn snapshots, and a way to answer it — put files back, comment on
* lines, then hand the comments to the agent as one message.
*/
export function TurnReviewView({
review,
focusPath,
onFocusPath,
}: {
review: TurnReview;
/** File to show; follows the turn card's row clicks. */
focusPath: string | null;
onFocusPath: (path: string) => void;
}): JSX.Element {
const { t } = useTranslation();
const files = useTurnFileActions(review.cwd);
const [containerWidth, setContainerWidth] = useState(0);
const [listWidth, setListWidth] = useState(LIST_DEFAULT_WIDTH);
const [sending, setSending] = useState(false);
const observerRef = useRef<ResizeObserver | null>(null);
const measureRef = useCallback((el: HTMLDivElement | null) => {
observerRef.current?.disconnect();
observerRef.current = null;
if (!el) return;
setContainerWidth(el.getBoundingClientRect().width);
const observer = new ResizeObserver((items) => {
for (const item of items) setContainerWidth(item.contentRect.width);
});
observer.observe(el);
observerRef.current = observer;
}, []);
useEffect(() => () => observerRef.current?.disconnect(), []);
const wide = containerWidth >= DIFF_MIN_WIDTH;
const sorted = useMemo(() => [...review.files].sort((a, b) => a.path.localeCompare(b.path)), [review.files]);
const active = sorted.find((file) => file.path === focusPath) ?? (wide ? sorted[0] : undefined);
const kept = sorted.filter((file) => !review.reverted.has(file.path));
const commentCounts = useMemo(() => {
const counts = new Map<string, number>();
for (const comment of review.comments) counts.set(comment.path, (counts.get(comment.path) ?? 0) + 1);
return counts;
}, [review.comments]);
const openFile = (path: string): void => {
onFocusPath(path);
if (!wide) resizePanel("max");
};
const onSplitDrag = useCallback(
(deltaX: number) => {
setListWidth((w) => {
const max = Math.max(LIST_MIN_WIDTH, containerWidth - DIFF_RESERVED_WIDTH);
return Math.max(LIST_MIN_WIDTH, Math.min(max, w + deltaX));
});
},
[containerWidth],
);
const send = useCallback(async (): Promise<void> => {
const prompt = buildReviewPrompt(review, t);
if (!prompt || sending) return;
setSending(true);
try {
const result = await getConversationApi().sendPrompt(prompt);
if (result.status === "failed") throw new Error(result.error?.message ?? "sendPrompt failed");
clearReviewFeedback(review.cwd);
} catch (error) {
notifyError(t("review.sendFailed"), error);
} finally {
setSending(false);
}
}, [review, sending, t]);
const hasFeedback = review.note.trim().length > 0 || review.comments.length > 0;
const onNoteKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>): void => {
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
event.preventDefault();
void send();
}
};
return (
<div className="flex h-full min-h-0 flex-col">
<div className="flex h-9 shrink-0 items-center gap-2 px-3">
<span className="min-w-0 truncate text-[12px] font-medium text-foreground">{t("review.title", { count: sorted.length })}</span>
<span className="flex shrink-0 items-center gap-1.5 text-[12px] font-medium tabular-nums">
<span className="text-emerald-500/90">+{review.additions}</span>
<span className="text-rose-500/90">−{review.deletions}</span>
</span>
<div className="ml-auto flex shrink-0 items-center">
{kept.length > 0 ? (
<Button
type="button"
size="xs"
variant="ghost"
disabled={files.busy}
onClick={() => files.apply(kept.map((file) => file.path), "revert")}
>
<UndoIcon className="h-3.5 w-3.5" />
{t("review.revertAll")}
</Button>
) : (
<Button
type="button"
size="xs"
variant="ghost"
disabled={files.busy}
onClick={() => files.apply(sorted.map((file) => file.path), "restore")}
>
<RedoIcon className="h-3.5 w-3.5" />
{t("review.restoreAll")}
</Button>
)}
</div>
</div>
<div ref={measureRef} className="flex min-h-0 flex-1 overflow-hidden">
<div
className={wide ? "relative flex min-h-0 shrink-0 flex-col overflow-hidden" : "flex min-h-0 flex-1 flex-col overflow-hidden"}
style={wide ? { width: listWidth } : undefined}
>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-1 text-[12px]">
{sorted.map((file) => (
<TurnFileRow
key={file.path}
file={file}
reverted={review.reverted.has(file.path)}
active={wide && active?.path === file.path}
commentCount={commentCounts.get(file.path) ?? 0}
busy={files.busy}
onOpen={() => openFile(file.path)}
onToggle={() => files.apply([file.path], review.reverted.has(file.path) ? "restore" : "revert")}
/>
))}
</div>
{/* 意见卡与提交框同一副骨架:标题、输入区、卡外的主操作。 */}
<div className="shrink-0 px-2 pb-2 pt-1">
<div className="overflow-hidden rounded-lg border border-border/70 bg-background transition-shadow focus-within:ring-1 focus-within:ring-ring/40">
<div className="flex items-center gap-2 px-2.5 pt-1.5 text-[11.5px] font-medium text-muted-foreground">
<span className="truncate">{t("review.feedbackTitle")}</span>
{review.comments.length > 0 && (
<span className="ml-auto flex shrink-0 items-center gap-1 text-sky-500">
<CommentIcon className="h-3 w-3" />
{t("review.commentCount", { count: review.comments.length })}
</span>
)}
</div>
<textarea
value={review.note}
onChange={(event) => setReviewNote(review.cwd, event.target.value)}
onKeyDown={onNoteKeyDown}
rows={3}
aria-label={t("review.feedbackTitle")}
placeholder={t("review.notePlaceholder")}
className="block max-h-48 min-h-[60px] w-full resize-y bg-transparent px-2.5 py-1.5 text-[12.5px] leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/50"
/>
</div>
<Button
type="button"
size="sm"
variant="default"
className="mt-1.5 w-full"
disabled={!hasFeedback || sending}
onClick={() => void send()}
>
<SendIcon className="h-3.5 w-3.5" />
{sending ? t("review.sending") : t("review.send")}
</Button>
</div>
{wide && <SplitHandle onDrag={onSplitDrag} />}
</div>
{wide &&
(active ? (
<ReviewDiffPane
review={review}
file={active}
busy={files.busy}
onToggle={() => files.apply([active.path], review.reverted.has(active.path) ? "restore" : "revert")}
/>
) : (
<div className="mb-2 ml-0.5 mr-2 mt-1 flex min-h-0 min-w-0 flex-1 flex-col items-center justify-center gap-2 rounded-lg border border-border/70 bg-background text-muted-foreground">
<FileIcon className="h-6 w-6 opacity-50" />
<span className="text-[12px]">{t("diff.selectPrompt")}</span>
</div>
))}
</div>
{files.dialog}
</div>
);
}
/** The selected file's turn diff, with comments laid under the lines they are about. */
function ReviewDiffPane({
review,
file,
busy,
onToggle,
}: {
review: TurnReview;
file: TurnFileChange;
busy: boolean;
onToggle: () => void;
}): JSX.Element {
const { t } = useTranslation();
const [diffStyle, setDiffStyle] = useState<"unified" | "split">(() =>
typeof localStorage !== "undefined" && localStorage.getItem(DIFF_STYLE_KEY) === "split" ? "split" : "unified",
);
const [patch, setPatch] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<CommentRange | null>(null);
const reverted = review.reverted.has(file.path);
useEffect(() => {
let alive = true;
setPatch(null);
setError(null);
setDraft(null);
snapshotFileDiff(review.root, review.before, review.after, file)
.then((value) => {
if (alive) setPatch(value);
})
.catch((err: unknown) => {
if (alive) setError(err instanceof Error ? err.message : String(err));
});
return () => {
alive = false;
};
}, [review.root, review.before, review.after, file]);
const comments = useMemo(() => review.comments.filter((comment) => comment.path === file.path), [review.comments, file.path]);
const annotations = useMemo<DiffLineAnnotation<AnnotationData>[]>(() => {
const out: DiffLineAnnotation<AnnotationData>[] = comments.map((comment) => ({
side: comment.side,
lineNumber: comment.end,
metadata: { kind: "comment", comment },
}));
if (draft) out.push({ side: draft.side, lineNumber: draft.end, metadata: { kind: "draft", range: draft } });
return out;
}, [comments, draft]);
const onCommentRange = useCallback((range: SelectedLineRange) => setDraft(toCommentRange(range)), []);
const renderAnnotation = useCallback(
(annotation: DiffLineAnnotation<AnnotationData>) => {
const data = annotation.metadata;
if (data.kind === "comment") {
return <ReviewCommentCard comment={data.comment} onRemove={() => removeReviewComment(review.cwd, data.comment.id)} />;
}
return (
<ReviewCommentComposer
range={data.range}
onCancel={() => setDraft(null)}
onSubmit={(body) => {
addReviewComment(review.cwd, {
path: file.path,
side: data.range.side,
start: data.range.start,
end: data.range.end,
body,
excerpt: patch ? excerptFromPatch(patch, data.range.side, data.range.start, data.range.end) : [],
});
setDraft(null);
}}
/>
);
},
[review.cwd, file.path, patch],
);
return (
<div className="mb-2 ml-0.5 mr-2 mt-1 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg border border-border/70 bg-background">
<div className="flex shrink-0 items-center gap-1.5 px-2 py-1.5">
<div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5">
<div className="flex items-center gap-1.5">
<FileTypeIcon path={file.path} className="h-4 w-4 shrink-0" />
<span
className="min-w-0 flex-1 truncate text-[12px] text-foreground"
title={file.origPath ? `${file.origPath} → ${file.path}` : file.path}
>
{basename(file.path)}
</span>
<StatusBadge code={file.code} />
</div>
<span className="git-mono truncate text-[11px] leading-[1.35] text-muted-foreground" title={file.path}>
{file.origPath ? `${file.origPath} → ${file.path}` : file.path}
</span>
</div>
<Button type="button" size="xs" variant="ghost" disabled={busy} onClick={onToggle}>
{reverted ? <RedoIcon className="h-3.5 w-3.5" /> : <UndoIcon className="h-3.5 w-3.5" />}
{t(reverted ? "review.restoreFile" : "review.revertFile")}
</Button>
<Button
type="button"
variant="ghost"
size="icon-xs"
onClick={() => {
const next = diffStyle === "unified" ? "split" : "unified";
setDiffStyle(next);
try {
localStorage.setItem(DIFF_STYLE_KEY, next);
} catch {}
}}
title={diffStyle === "unified" ? t("diff.switchToSplit") : t("diff.switchToUnified")}
>
{diffStyle === "unified" ? <SplitViewIcon className="h-3.5 w-3.5" /> : <UnifiedViewIcon className="h-3.5 w-3.5" />}
</Button>
</div>
{/* 撤回后 diff 仍是「本轮改了什么」,只是提示它眼下不在工作区里。 */}
{reverted ? (
<div className="mx-2 mb-1 rounded-md bg-muted/60 px-2 py-1 text-[11px] text-muted-foreground">{t("review.revertedBanner")}</div>
) : (
!file.binary && <div className="px-2.5 pb-1 text-[11px] text-muted-foreground/70">{t("review.commentHint")}</div>
)}
<div className="min-h-0 flex-1 overflow-auto">
{error && <div className="px-3 py-2 text-[12px] text-rose-500">{error}</div>}
{!error && patch === null && <div className="px-3 py-2 text-[12px] text-muted-foreground">{t("diff.loading")}</div>}
{!error &&
patch !== null &&
(patch.trim().length === 0 ? (
<div className="px-3 py-2 text-[12px] text-muted-foreground">{t("diff.empty")}</div>
) : (
<PatchContent<AnnotationData>
patch={patch}
diffStyle={diffStyle}
virtualize
annotations={annotations}
renderAnnotation={renderAnnotation}
onCommentRange={file.binary ? undefined : onCommentRange}
/>
))}
</div>
</div>
);
}