# Code Review

> Review a change's files, comment on lines, and send the comments to an agent as one review.

Page: https://uicontext.com/docs/components/code-review

Group: Documents.

## When to use

Review a change's files, comment on lines, and send the comments to an agent as one review. Use [Diff](https://uicontext.com/docs/components/diff.md) instead when people only read the change.

## Usage

```ts
import type { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { DiffSide } from "./ui/uicontext/components/Diff.ts"
import { DiffReview, type ReviewComment, type ReviewFile } from "./ui/uicontext/components/DiffReview.ts"

const Message = UiSchema.TaggedEnum({
	RequestedAddCommentReview: { path: Schema.String, side: DiffSide, line: Schema.Number, body: Schema.String },
	RequestedDeleteCommentReview: { comment: Schema.String },
	RequestedSendReview: {},
	RequestedLayoutReview: { layout: Schema.Literals(["unified", "split"]) },
})

// your app keeps the comments: drafts until Send, then sent, then addressed with the agent's reply
export const Review = (h: Html.H<typeof Message.Type>, files: ReadonlyArray<ReviewFile>, comments: ReadonlyArray<ReviewComment>, outcome: Outcome | null) =>
	DiffReview(h, {
		props: { id: "ws-4", files, comments, can: ["comment", "send"], outcome },
		onEmit: {
			RequestedAddComment: ({ path, side, line, body }) => Message.RequestedAddCommentReview({ path, side, line, body }),
			RequestedDeleteComment: ({ comment }) => Message.RequestedDeleteCommentReview({ comment }),
			RequestedSend: () => Message.RequestedSendReview(),
			RequestedLayout: ({ layout }) => Message.RequestedLayoutReview({ layout }),
		},
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Send a review to the agent

Hover a line (or Tab to one and use the arrows) and press + to write a comment. Comments stay drafts until Send to agent; then the agent answers each one.

```ts title="src/demo.ts" source="www/src/examples/code-review/demo.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import { Outcome } from "./ui/uicontext/components/domain/Outcome.ts"
import { DiffSide } from "./ui/uicontext/components/Diff.ts"
import { DiffReview, ReviewComment, type ReviewFile } from "./ui/uicontext/components/DiffReview.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"

const clientBefore = `import axios from "axios"

export async function getInvoice(id: string) {
  const response = await axios.get(\`/api/invoices/\${id}\`)
  return response.data
}
`
const clientAfter = `import { withRetry } from "./retry"

export async function getInvoice(id: string) {
  const response = await withRetry(() => fetch(\`/api/invoices/\${id}\`))
  if (!response.ok) throw new Error(\`Invoice \${id}: \${response.status}\`)
  return response.json()
}
`
const retryAfter = `/** Calls \`run\` again on a 429 or 503, waiting 200 ms, then 400, then 800. */
export async function withRetry(run: () => Promise<Response>, attempts = 3) {
  for (let attempt = 1; ; attempt++) {
    const response = await run()
    if ((response.status !== 429 && response.status !== 503) || attempt >= attempts) return response
    await new Promise((done) => setTimeout(done, 200 * 2 ** (attempt - 1)))
  }
}
`

const files: ReadonlyArray<ReviewFile> = [
	{ path: "src/api/client.ts", before: clientBefore, after: clientAfter },
	{ path: "src/api/retry.ts", before: "", after: retryAfter, status: "added" },
]

const Message = UiSchema.TaggedEnum({
	RequestedAddCommentReview: { path: Schema.String, side: DiffSide, line: Schema.Number, body: Schema.String },
	RequestedDeleteCommentReview: { comment: Schema.String },
	RequestedSendReview: {},
	RequestedLayoutReview: { layout: Schema.Literals(["unified", "split"]) },
	CompletedAgentReply: { comments: Schema.Array(Schema.String) },
})

// stands in for the agent: it reads the comments, changes the code, and answers each
const AnswerReview = Command.make("AnswerReview", { args: { comments: Schema.Array(Schema.String) } }, ({ comments }) =>
	Effect.sleep("2500 millis").pipe(Effect.as(Message.CompletedAgentReply({ comments }))))

const styles = stylex.create({ wide: { inlineSize: "100%" } })

export const ReviewForAgent = Html.component({
	name: "ReviewForAgent",
	model: Schema.Struct({ comments: Schema.Array(ReviewComment), layout: Schema.Literals(["unified", "split"]), next: Schema.Number, outcome: Schema.NullOr(Outcome) }),
	message: Message,
}).make({
	init: () => ({
		comments: [{ id: "c0", path: "src/api/retry.ts", side: "after" as const, line: 4, body: "Retry a network error too, not only 429 and 503.", author: "Grace Liu", state: "addressed" as const,
			reply: "Done: a thrown fetch now counts as a failed attempt." }],
		layout: "unified" as const,
		next: 1,
		outcome: null,
	}),
	update: {
		RequestedAddCommentReview: ($, { path, side, line, body }) => $.evolve({
			comments: (cs) => [...cs, { id: `c${$.model.next}`, path, side, line, body, author: "You", state: "draft" as const }],
			next: (n) => n + 1,
		}),
		RequestedDeleteCommentReview: ($, { comment }) => $.evolve({ comments: (cs) => cs.filter((c) => c.id !== comment) }),
		RequestedSendReview: ($) => {
			const drafts = $.model.comments.filter((c) => c.state === "draft").map((c) => c.id)
			return $.evolve({ comments: (cs) => cs.map((c) => (c.state === "draft" ? { ...c, state: "sent" as const } : c)), outcome: { _tag: "Accepted", request: "send" } })
				.run(AnswerReview.make({ comments: drafts }))
		},
		RequestedLayoutReview: ($, { layout }) => $.evolve({ layout }),
		CompletedAgentReply: ($, { comments }) => $.evolve({
			comments: (cs) => cs.map((c) => (comments.includes(c.id) ? { ...c, state: "addressed" as const, reply: `Done: changed line ${c.line} of ${c.path.split("/").at(-1)} as you asked.` } : c)),
		}),
	},
	view: (h, model) => h.div.attrs(sx(styles.wide)).children(DiffReview(h, {
		props: { id: "ws-4", agentId: "example-diff-review", label: "Changes on maya/fetch-client", files, comments: model.comments, layout: model.layout, can: ["comment", "send"], outcome: model.outcome },
		onEmit: {
			RequestedAddComment: ({ path, side, line, body }) => Message.RequestedAddCommentReview({ path, side, line, body }),
			RequestedDeleteComment: ({ comment }) => Message.RequestedDeleteCommentReview({ comment }),
			RequestedSend: () => Message.RequestedSendReview(),
			RequestedLayout: ({ layout }) => Message.RequestedLayoutReview({ layout }),
		},
	})),
})
```

## API reference

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `id` (required) | `string` | — |
| `files` (required) | `ReviewFile[]` | — |
| `comments` (required) | `ReviewComment[]` | — |
| `layout` | `"unified" \| "split"` | — |
| `can` (required) | `("comment" \| "send")[]` | "comment" lets the person write on lines; "send" sends the drafts |
| `sendLabel` | `string` | "Send to agent" by default |
| `outcome` | `Outcome \| null` | The app's answer to the last send ("send") |
| `label` | `string` | — |
| `agentId` | `string` | — |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedLayout` | `{ id: string; layout: "unified" \| "split" }` | — |
| `RequestedAddComment` | `{ id: string; path: string; side: DiffSide; line: number; body: string }` | Keep a draft comment on a line |
| `RequestedDeleteComment` | `{ id: string; comment: string }` | — |
| `RequestedSend` | `{ id: string; comments: string[] }` | Send every draft to the agent as one review; answer with outcome "send" |

**Agent actions**

| Action | Description |
| --- | --- |
| `RequestedComment` | Write a draft comment on a line of a changed file: its path, side (after for added or unchanged lines) and 1-based line |
| `ClickedSend` | Send every draft comment to the agent as one review |

## Keyboard and accessibility

- Every changed file is a diff with line numbers; Tab reaches one comment button and the arrow keys move it from line to line.
- A comment box takes focus as it opens: Mod+Enter adds the comment and Escape closes it. Each comment says whether it's a draft, sent or addressed in words.
- The drafts bar is a named region with one Send button. Agents read the comments and can write one on a named line.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/code-review
```

With npm: `npx shadcn@latest add checkfu/uicontext/code-review`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/code-review`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/code-review`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/Diff.ts`
- `src/ui/uicontext/components/DiffReview.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/InlineNotice.ts`
- `src/ui/uicontext/components/Kbd.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Outcome.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/touch.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/DiffReview.ts](https://github.com/checkfu/uicontext/blob/main/src/DiffReview.ts)

## Used in

- [Agent studio](https://uicontext.com/blocks/agent-studio.md)

## Related

- [Editor](https://uicontext.com/docs/components/editor.md) (`editor`): A block editor with a slash menu for headings, lists, to-dos and more.
- [Document Blocks](https://uicontext.com/docs/components/document-blocks.md) (`document-blocks`): Read-only rendering of a document's blocks.
- [Markdown](https://uicontext.com/docs/components/markdown.md) (`markdown`): Renders Markdown with readable type.
- [Code Block](https://uicontext.com/docs/components/code-block.md) (`code-block`): Code to read and copy, with highlighting, a file name and line numbers.
- [JSON Viewer](https://uicontext.com/docs/components/json-viewer.md) (`json-viewer`): A JSON value as a tree to open, search and walk with the arrow keys, such as a webhook's payload or a tool call's result.
- [Log Viewer](https://uicontext.com/docs/components/log-viewer.md) (`log-viewer`): A log that follows its newest line, with a filter, level buttons and Wrap, such as a deploy's or a server's.
