Files
kandev/apps/web/components/diff/use-diff-viewer-state.ts
T
João Salavisa 57adf1449c feat(review): native code-review agent with inline findings in the Changes panel (#1957)
* feat(review): persist and publish native code-review findings

Adds the backend core for reviewing a task's working diff before a PR
exists: task-scoped review runs and anchored, advisory findings that the
Changes/Review panel can render as inline comments.

- task_review_runs / task_review_findings schema, models, and repository,
  with supersede-on-re-review and a restart sweep that cancels in-flight
  runs rather than leaving them looking alive.
- ReviewService as the single write path, publishing bus events that the
  WS gateway forwards to the client.
- internal/review: reviewer-identity resolution (agent profile > code-review
  utility agent > user default, failing closed on passthrough-only profiles),
  change-set collection, prompt batching, response parsing, anchor
  extraction, and run orchestration.
- publish_review_findings_kandev MCP tool plus the task.review.* WS actions.
- Go djb2 that matches apps/web/lib/utils/hash.ts, asserted from shared
  fixtures on both sides so stale detection agrees across the wire.

Spec: docs/specs/native-code-review/spec.md
Plan: docs/plans/native-code-review/plan.md

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(review): add run_code_review workflow step and wire the review runner

Makes a review pass triggerable both ways and actually runnable end to end.

- run_code_review on_enter action across models, engine compile, and an
  orchestrator callback that logs rather than propagates failures, so a task
  never gets stuck in a step because no reviewer was configured.
- The step's optional agent_profile_id is what lets a step review with a
  different model than it implemented with; export/import swap it for a
  portable agent name/model/mode so it survives a cross-workspace round trip
  instead of carrying a dangling id.
- Concrete adapters for reviewer identity, changed-file collection, prompt
  rendering from the code-review utility agent's editable prompt, and
  inference (session-bound agentctl, falling back to the host instance so a
  review works on a task whose agent is not running).
- Boot sweep cancels review runs interrupted by a restart; the E2E reset
  clears review state before deleting the tasks that own it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): add review findings state, helpers, and live updates

Frontend plumbing for native code review, ahead of the UI that renders it.

- Review types, WS message map, and an API client that preserves the backend's
  machine-readable failure code so the surface can show an actionable message.
- A review store slice that merges findings by id (a re-publish refreshes an
  issue rather than listing it twice) and keeps a bounded run history.
- Findings helpers: composite file keys matching reviewFileKey, staleness via
  the same per-file diff hash that drives review marks, and best-effort
  re-anchoring from the stored anchor text so a moved finding follows the code
  it was written about instead of pointing at whatever now occupies its line.
- Hooks for backfill, resolve/dismiss/reopen with optimistic rollback, and
  sending a finding to the agent as follow-up context without changing its
  status — handing a finding to an agent is not the human accepting it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): render review findings inline in the Changes diff

Findings now appear where the code is, in the same annotation surface as
anchored review comments, with the run control that produces them.

- ReviewFindingCard: severity chip, category, Markdown body, and the three
  advisory actions. A suggestion is labelled "not applied automatically"
  because it is display-only in this iteration. Resolved and dismissed
  findings collapse to one muted line with an Undo, so a reviewed diff does
  not stay cluttered while the human can still change their mind.
- A review-finding annotation type threaded through the diff viewer, anchored
  from the same per-file diff hash the backend stamped. A finding whose diff
  moved is re-anchored from its stored text when that text survives, and
  otherwise reported as unanchored rather than placed against unrelated code.
- Review changes control with idle / running / cancel / failed states, and an
  inline Settings link for the one failure the user can actually fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): make the review control reachable from the Review toolbar

Mounts the Review changes control next to the walkthrough action and lets an
inline finding wire its own actions.

The finding card container now reads the active task and session from the store
instead of taking four callbacks threaded through FileDiffViewer and DiffViewer;
an inline finding annotation only exists when the active task has findings, so
the store is always present and every other diff consumer is spared the
plumbing. Staleness likewise hashes the diff the viewer already holds, which is
already normalized, so it matches the hash the backend stamped without passing
it down.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): surface stale review findings above their file's diff

A finding whose diff moved and whose anchor text is gone had nowhere to render,
so it was silently dropped. It now appears in a collapsed per-file banner above
the diff: the finding may still be valid, and placing it at its stored line
would point at whatever code now occupies that line instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(review): mark the landed native code-review plan tasks done

Tasks 01-09 (backend persistence through inline diff rendering) are
implemented, tested, and committed. Tasks 10-13 — findings overview and step
editor, mobile parity, E2E, and public docs — remain pending.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(review): cover the on-demand review path end to end

Adds the mock-agent review responder and a Playwright spec, so both the happy
path and the no-reviewer path are verified against a real backend.

The mock agent answers any prompt carrying the review sentinel with fenced JSON,
deriving its anchors from the prompt's own diff rather than hardcoding them, so
findings land on files and lines the fixture really changed. It includes one
deliberately malformed entry to exercise the rejected-entry path.

Writing it caught an off-by-one shared by three diff walkers: splitting on "\n"
leaves an empty element after a trailing newline, which carries no diff marker
and was being counted as a context line, pushing new-side numbering one past the
end of a hunk. Interior blank lines still count, since a whitespace-stripped
blank context line legitimately appears as "".

Also adds a listInferenceAgents helper: default_utility_agent_id needs the
registered agent-type id, and an agent row UUID is rejected as not
inference-capable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(review): close review-run races and stale client findings

Addresses the three blockers and three suggestions from the PR #1957 automated
reviews. Two independent reviewers found each blocker separately.

- Launch claimed the task slot only after inserting the run row, so two
  concurrent launches both created a run and the loser returned a pending row
  with no goroutine behind it — a review that never finished until the next
  restart. The slot is now claimed before any DB write, and freed on every
  early return.
- Cancelling only marked the row. The goroutine ran on the shared background
  context, finished inference, and its completion overwrote the cancelled
  status and published findings the user had declined. Runs now carry a cancel
  handle, the WS action routes through the runner so the live context is
  cancelled, CompleteRun/FailRun refuse to resurrect a terminal run, and a
  cancelled pass neither publishes nor re-reports itself as failed.
- The backend deletes a superseded finding and inserts a replacement with a new
  id, but the publish event carried only the new one, so every open browser
  showed both at the same anchor until a reload. The event now names the
  superseded ids and the slice drops them.
- Run() waited on the shared WaitGroup, blocking on every other task's review;
  it now waits on its own pass only.
- createReviewSlice is typed over the `set` it actually uses, so call sites no
  longer pass superfluous arguments (CodeQL js/superfluous-trailing-arguments).
- A GetAgentProfile fault no longer collapses into "profile not found", which
  would have told the user to configure an agent they already have.

The cancel bug exposed a hole in the original tests: they asserted cancel could
not override a terminal run, but never the reverse. Both directions are covered
now, along with the concurrent-launch race, per-run waiting, and the supersede
path on both sides of the wire. Test fakes now mirror the service's terminal
guard rather than hiding it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 15:05:56 +01:00

513 lines
15 KiB
TypeScript

import { useState, useCallback, useEffect, useMemo, useRef, type RefObject } from "react";
import type {
SelectedLineRange,
FileDiffMetadata,
DiffLineAnnotation,
AnnotationSide,
ChangeContent,
} from "@pierre/diffs";
import type { FileDiffData, DiffComment, DiffCommentUpdate } from "@/lib/diff/types";
import { buildDiffComment, useCommentActions } from "@/lib/diff/comment-utils";
import { useDiffComments } from "./use-diff-comments";
import { useDiffMetadata } from "./use-diff-metadata";
import { useExpandableDiff } from "./use-expandable-diff";
import type { RevertBlockInfo } from "./diff-viewer";
import type { AnnotationMetadata } from "./use-diff-annotation-renderer";
import { useReviewFindingAnnotations } from "./use-review-finding-annotations";
import { useOptionalAppStore } from "@/components/state-provider";
import {
walkthroughStepMatchesFile,
type WalkthroughTargetFile,
} from "@/lib/diff/walkthrough-match";
import type { WalkthroughStep } from "@/lib/types/http";
type BuildAnnotationsOpts = {
comments: DiffComment[];
editingCommentId: string | null;
showCommentForm: boolean;
selectedLines: SelectedLineRange | null;
enableAcceptReject: boolean;
fileDiffMetadata: FileDiffMetadata | null;
};
type HunkState = {
addLine: number;
delLine: number;
lastCtxAdd: number;
lastCtxDel: number;
blockIdx: number;
};
export type HunkOutputs = {
result: DiffLineAnnotation<AnnotationMetadata>[];
lineMap: Map<string, string>;
revertMap: Map<string, RevertBlockInfo>;
};
/** Process a single change block within a hunk. */
function processChangeBlock(
content: ChangeContent,
deletionLines: string[],
state: HunkState,
out: HunkOutputs,
) {
const aLen = content.additions;
const dLen = content.deletions;
if (aLen === 0 && dLen === 0) return;
const cbId = `cb-${state.blockIdx++}`;
const side: AnnotationSide = aLen > 0 ? "additions" : "deletions";
const lineNumber = side === "additions" ? state.lastCtxAdd : state.lastCtxDel;
out.result.push({ side, lineNumber, metadata: { type: "hunk-actions", changeBlockId: cbId } });
for (let l = 0; l < aLen; l++) out.lineMap.set(`additions:${state.addLine + l}`, cbId);
for (let l = 0; l < dLen; l++) out.lineMap.set(`deletions:${state.delLine + l}`, cbId);
const oldLines = deletionLines
.slice(content.deletionLineIndex, content.deletionLineIndex + dLen)
.map((l) => l.replace(/\r?\n$/, ""));
out.revertMap.set(cbId, {
addStart: state.addLine,
addCount: aLen,
oldLines,
});
}
/** Build hunk-level annotations, line->changeBlock map, and revert info. */
export function buildHunkAnnotations(fileDiffMetadata: FileDiffMetadata, out: HunkOutputs) {
const state: HunkState = { addLine: 0, delLine: 0, lastCtxAdd: 0, lastCtxDel: 0, blockIdx: 0 };
for (const hunk of fileDiffMetadata.hunks) {
if (hunk.additionCount === 0 && hunk.deletionCount === 0) continue;
state.addLine = hunk.additionStart;
state.delLine = hunk.deletionStart;
state.lastCtxAdd = state.addLine > 1 ? state.addLine - 1 : state.addLine;
state.lastCtxDel = state.delLine > 1 ? state.delLine - 1 : state.delLine;
for (const content of hunk.hunkContent) {
if (content.type === "context") {
const len = content.lines;
state.lastCtxAdd = state.addLine + len - 1;
state.lastCtxDel = state.delLine + len - 1;
state.addLine += len;
state.delLine += len;
continue;
}
processChangeBlock(content, fileDiffMetadata.deletionLines, state, out);
state.addLine += content.additions;
state.delLine += content.deletions;
}
}
}
/** Build all diff line annotations (comments, new-comment form, hunk actions). */
function buildAnnotations(opts: BuildAnnotationsOpts) {
const {
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata,
} = opts;
const result: DiffLineAnnotation<AnnotationMetadata>[] = comments.map((comment) => ({
side: comment.side,
lineNumber: comment.endLine,
metadata: { type: "comment" as const, comment, isEditing: editingCommentId === comment.id },
}));
if (showCommentForm && selectedLines) {
result.push({
side: (selectedLines.side || "additions") as AnnotationSide,
lineNumber: Math.max(selectedLines.start, selectedLines.end),
metadata: { type: "new-comment-form" as const },
});
}
const newLineMap = new Map<string, string>();
const newRevertMap = new Map<string, RevertBlockInfo>();
if (enableAcceptReject && fileDiffMetadata) {
buildHunkAnnotations(fileDiffMetadata, {
result,
lineMap: newLineMap,
revertMap: newRevertMap,
});
}
return { annotations: result, lineMap: newLineMap, revertMap: newRevertMap };
}
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
type UseDiffViewerStateOpts = {
data: FileDiffData;
enableComments: boolean;
enableAcceptReject: boolean;
sessionId?: string;
onCommentAdd?: (comment: DiffComment) => void;
onCommentDelete?: (commentId: string) => void;
onCommentUpdate?: (commentId: string, updates: DiffCommentUpdate) => void;
onCommentRun?: (comment: DiffComment) => void;
externalComments?: DiffComment[];
onRevertBlock?: (filePath: string, info: RevertBlockInfo) => Promise<void> | void;
/** Enable diff expansion (requires fetching full file content) */
enableExpansion?: boolean;
/** Base git ref for fetching old content (e.g., "origin/main", "HEAD~1") */
baseRef?: string;
/** Multi-repo subpath for the file (e.g. "kandev"); empty for single-repo. */
repo?: string;
};
/**
* Returns a `walkthrough-step` annotation anchored to the active walkthrough
* step's line when that step targets this file, else null. Additive and gated:
* with no active walkthrough it returns null and the diff is unaffected.
*/
export function buildWalkthroughSelectedLines(
file: WalkthroughTargetFile,
step: WalkthroughStep | null | undefined,
): SelectedLineRange | null {
if (!step || !walkthroughStepMatchesFile(file, step)) return null;
return {
side: "additions",
start: step.line,
end: step.line_end ?? step.line,
};
}
function useWalkthroughSelection(
filePath: string,
repo: string | undefined,
): {
annotation: DiffLineAnnotation<AnnotationMetadata> | null;
selectedLines: SelectedLineRange | null;
} {
const activeTaskId = useOptionalAppStore((s) => s.tasks.activeTaskId, null);
const walkthrough = useOptionalAppStore(
(s) => (activeTaskId ? s.walkthroughs.byTaskId[activeTaskId] : null),
null,
);
const activeStep = useOptionalAppStore(
(s) => (activeTaskId ? (s.walkthroughs.activeStepByTaskId[activeTaskId] ?? 0) : 0),
0,
);
return useMemo(() => {
const step = walkthrough?.steps[activeStep];
const selectedLines = buildWalkthroughSelectedLines(
{ path: filePath, repository_name: repo },
step,
);
if (!selectedLines) return { annotation: null, selectedLines: null };
return {
annotation: {
side: "additions" as AnnotationSide,
lineNumber: Math.max(selectedLines.start, selectedLines.end),
metadata: { type: "walkthrough-step" as const },
},
selectedLines,
};
}, [walkthrough, activeStep, filePath, repo]);
}
function useDiffViewerAnnotations({
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata,
filePath,
repo,
diff,
changeLineMapRef,
revertInfoRef,
}: BuildAnnotationsOpts & {
filePath: string;
repo?: string;
diff?: string;
changeLineMapRef: RefObject<Map<string, string>>;
revertInfoRef: RefObject<Map<string, RevertBlockInfo>>;
}) {
const { annotations, lineMap, revertMap } = useMemo(
() =>
buildAnnotations({
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata,
}),
[
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata,
],
);
const walkthrough = useWalkthroughSelection(filePath, repo);
const reviewFindings = useReviewFindingAnnotations({ filePath, repo, diff });
const withWalkthrough = useMemo(() => {
const combined = [...annotations, ...reviewFindings.annotations];
return walkthrough.annotation ? [...combined, walkthrough.annotation] : combined;
}, [annotations, reviewFindings.annotations, walkthrough.annotation]);
useEffect(() => {
changeLineMapRef.current = lineMap;
revertInfoRef.current = revertMap;
}, [lineMap, revertMap, changeLineMapRef, revertInfoRef]);
return {
annotations: withWalkthrough,
walkthroughSelectedLines: walkthrough.selectedLines,
unanchoredFindings: reviewFindings.unanchored,
};
}
type CommentHandlerOpts = {
selectedLines: SelectedLineRange | null;
setSelectedLines: React.Dispatch<React.SetStateAction<SelectedLineRange | null>>;
setShowCommentForm: React.Dispatch<React.SetStateAction<boolean>>;
enableComments: boolean;
onCommentAdd?: (comment: DiffComment) => void;
onCommentRun?: (comment: DiffComment) => void;
externalComments?: DiffComment[];
data: FileDiffData;
sessionId?: string;
addComment: (range: SelectedLineRange, content: string) => DiffComment;
removeComment: (commentId: string) => void;
updateComment: (commentId: string, updates: DiffCommentUpdate) => void;
setEditingComment: (commentId: string | null) => void;
onCommentDelete?: (commentId: string) => void;
onCommentUpdate?: (commentId: string, updates: DiffCommentUpdate) => void;
};
function useDiffViewerCommentHandlers(opts: CommentHandlerOpts) {
const {
selectedLines,
setSelectedLines,
setShowCommentForm,
enableComments,
onCommentAdd,
onCommentRun,
externalComments,
data,
sessionId,
addComment,
removeComment,
updateComment,
setEditingComment,
onCommentDelete,
onCommentUpdate,
} = opts;
const handleLineSelectionEnd = useCallback(
(range: SelectedLineRange | null) => {
setSelectedLines(range);
if (range && enableComments) setShowCommentForm(true);
},
[enableComments, setSelectedLines, setShowCommentForm],
);
const createCommentFromSelection = useCallback(
(content: string): DiffComment | null => {
if (!selectedLines) return null;
return buildDiffComment({
filePath: data.filePath,
sessionId: sessionId || "",
startLine: selectedLines.start,
endLine: selectedLines.end,
side: (selectedLines.side || "additions") as DiffComment["side"],
text: content,
});
},
[selectedLines, data.filePath, sessionId],
);
const submitComment = useCallback(
(content: string, runAfter?: (c: DiffComment) => void) => {
if (!selectedLines) return;
if (onCommentAdd && externalComments !== undefined) {
const comment = createCommentFromSelection(content);
if (comment) {
onCommentAdd(comment);
runAfter?.(comment);
}
} else if (sessionId) {
const stored = addComment(selectedLines, content);
if (runAfter && stored) runAfter(stored);
}
setShowCommentForm(false);
setSelectedLines(null);
},
[
selectedLines,
onCommentAdd,
externalComments,
sessionId,
addComment,
createCommentFromSelection,
setShowCommentForm,
setSelectedLines,
],
);
const handleCommentSubmit = useCallback(
(content: string) => submitComment(content),
[submitComment],
);
const handleCommentSubmitAndRun = useCallback(
(content: string) => submitComment(content, onCommentRun),
[submitComment, onCommentRun],
);
const { handleCommentDelete, handleCommentUpdate } = useCommentActions({
removeComment,
updateComment,
setEditingComment,
onCommentDelete,
onCommentUpdate,
externalComments,
});
return {
handleLineSelectionEnd,
handleCommentSubmit,
handleCommentSubmitAndRun: onCommentRun ? handleCommentSubmitAndRun : undefined,
handleCommentDelete,
handleCommentUpdate,
};
}
function useRevertBlock(
filePath: string,
onRevertBlock?: (filePath: string, info: RevertBlockInfo) => Promise<void> | void,
) {
const revertInfoRef = useRef<Map<string, RevertBlockInfo>>(new Map());
const handleRevertBlock = useCallback(
async (changeBlockId: string) => {
const info = revertInfoRef.current.get(changeBlockId);
if (!info) return;
await onRevertBlock?.(filePath, info);
},
[filePath, onRevertBlock],
);
return { revertInfoRef, handleRevertBlock };
}
/**
* The session-scoped comment store for one file. Extracted from
* useDiffViewerState to keep that hook under the function line cap.
*/
function useInternalDiffComments(data: FileDiffData, sessionId?: string) {
return useDiffComments({
sessionId: sessionId || "",
filePath: data.filePath,
diff: data.diff,
newContent: data.newContent,
oldContent: data.oldContent,
});
}
export function useDiffViewerState(opts: UseDiffViewerStateOpts) {
const {
data,
enableComments,
enableAcceptReject,
sessionId,
onCommentAdd,
onCommentDelete,
onCommentUpdate,
onCommentRun,
externalComments,
onRevertBlock,
enableExpansion = false,
baseRef,
repo,
} = opts;
const [selectedLines, setSelectedLines] = useState<SelectedLineRange | null>(null);
const [showCommentForm, setShowCommentForm] = useState(false);
const {
comments: internalComments,
addComment,
removeComment,
updateComment,
editingCommentId,
setEditingComment,
} = useInternalDiffComments(data, sessionId);
const comments = externalComments || internalComments;
const baseDiffMetadata = useDiffMetadata(data);
const expansion = useExpandableDiff({
sessionId,
filePath: data.filePath,
baseRef,
fileDiffMetadata: baseDiffMetadata,
diff: data.diff,
enableExpansion,
repo,
});
const { revertInfoRef, handleRevertBlock } = useRevertBlock(data.filePath, onRevertBlock);
const changeLineMapRef = useRef<Map<string, string>>(new Map());
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { annotations, walkthroughSelectedLines, unanchoredFindings } = useDiffViewerAnnotations({
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata: expansion.metadata,
filePath: data.filePath,
repo,
diff: data.diff,
changeLineMapRef,
revertInfoRef,
});
const commentHandlers = useDiffViewerCommentHandlers({
selectedLines,
setSelectedLines,
setShowCommentForm,
enableComments,
onCommentAdd,
onCommentRun,
externalComments,
data,
sessionId,
addComment,
removeComment,
updateComment,
setEditingComment,
onCommentDelete,
onCommentUpdate,
});
return {
comments,
fileDiffMetadata: expansion.metadata,
annotations,
walkthroughSelectedLines,
unanchoredFindings,
selectedLines,
showCommentForm,
setShowCommentForm,
setSelectedLines,
editingCommentId,
setEditingComment,
handleRevertBlock,
...commentHandlers,
changeLineMapRef,
hideTimeoutRef,
isExpansionContentLoaded: expansion.isContentLoaded,
isExpansionLoading: expansion.isLoading,
expansionError: expansion.error,
loadExpansionContent: expansion.loadContent,
canExpand: expansion.canExpand,
};
}