Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

213 lines · 12.8 KBRaw History
1/** @jsxImportSource hono/jsx */
2import type { FC } from "hono/jsx";
3import { requireAccount, type AppContext } from "../auth/principal.js";
4import { loadRepo } from "../http/common.js";
5import { atLeast } from "../repo/types.js";
6import { csrfToken } from "../web/csrf.js";
7import { KCheckbox, KRadio, KSelect } from "../web/kumo.js";
8import { page as settingsPage } from "../web/repo-settings.js";
9import { Form, Time, act, post, prm, repoUrl, statusOf, type WebApp } from "../web/ui.js";
10import { ModelKeys, PROVIDERS, type Provider } from "./keys.js";
11import { AUTHORS, findingId, MAX_AUTOFIXES, PR_DAILY_AUTOMATIC, PR_DAILY_REVIEWS, REPO_DAILY_DEFAULT, REPO_DAILY_MAX, REVIEW_MAX_MODEL_CALLS, REVIEW_TIMEOUT_MS, REVIEW_TOKENS_DEFAULT, REVIEW_TOKENS_MAX, REVIEW_TOKENS_MIN, TRIGGERS, type ReviewSettings } from "./review.js";
12import { askForReview, reviewSettings, saveReviewSettings } from "./reviews.js";
13import { parseRuntimeChoice, runtimeChoices, runtimeLabel } from "./runtimes.js";
14import { drivableAgents } from "./tasks.js";
15import { OpenRouterModel } from "./tasks-web.js";
16
17/**
18 * Web pages for agent code review: Settings → Agent review, the PR page's
19 * "Request agent review" button and the "Fix it" link on findings.
20 */
21
22type Loaded = Awaited<ReturnType<typeof loadRepo>>;
23
24/** What the PR page needs: set when reviews are on and the viewer is a person with write access. */
25export interface PullReviewCtx {
26 agent: string;
27}
28
29export async function pullReviewCtx(c: AppContext, l: Loaded): Promise<PullReviewCtx | null> {
30 if (l.caller.kind !== "user" || !atLeast(l.caller.role, "write") || l.repo.archived) return null;
31 const s = await reviewSettings(c.env, l.repo.id).catch(() => null);
32 return s?.enabled ? { agent: s.agent.login } : null;
33}
34
35/** The Reviewers sidebar's button. */
36export const RequestAgentReview: FC<{ c: AppContext; l: Loaded; pr: number; ctx: PullReviewCtx }> = ({ c, l, pr, ctx }) => (
37 <Form action={`${repoUrl(l.repo)}/pull/${pr}/agent-review`} t={csrfToken(c)} style="margin-top:8px">
38 <button class="btn sm block" title={`Ask ${ctx.agent} to review this pull request now`}>
39 Request agent review
40 </button>
41 </Form>
42);
43
44/** "Fix it" under an agent review finding, for people with write access. */
45export const FixIt: FC<{ l: Loaded; pr: number; comment: { id: string; body: string; author: { kind: string } } }> = ({ l, pr, comment }) =>
46 comment.author.kind === "agent" && findingId(comment.body) && atLeast(l.caller.role, "write") && l.caller.kind === "user" && !l.repo.archived ? (
47 <a class="btn sm" href={`${repoUrl(l.repo)}/tasks/new?pull=${pr}&finding=${encodeURIComponent(comment.id)}`} title="Start an agent task that fixes this on the pull request's branch">
48 Fix it
49 </a>
50 ) : null;
51
52async function settingsForm(c: AppContext, l: Loaded, error?: string, values?: Partial<Record<string, string>>) {
53 const me = requireAccount(c);
54 const base = repoUrl(l.repo);
55 const [current, agents, keys] = await Promise.all([reviewSettings(c.env, l.repo.id), drivableAgents(c, me, l), new ModelKeys(c.env).providers(me.id)]);
56 const v = (k: string, d: string) => values?.[k] ?? d;
57 const s: Partial<ReviewSettings> = current ?? {};
58 const runtimes = runtimeChoices(keys, Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, p.name])) as Record<Provider, string>);
59 const currentChoice = s.runtime ? (s.via ? `${s.runtime}+${s.via}` : s.runtime) : undefined;
60 const youPay = !current || current.person.id === me.id;
61 return settingsPage(
62 c,
63 l,
64 "agent-review",
65 <>
66 <h1>Agent review</h1>
67 <p class="muted">
68 One of your agents reviews pull requests for bugs, security issues and logic errors, like Cursor's Bugbot. It reads the changes in a read-only sandbox, then posts its findings as review comments, with an <b>Agent review</b> check that fails when a finding is blocking (branch protection can require it). Rules in <code>REVIEW.md</code> or <code>.cursor/BUGBOT.md</code> files apply. See <a href="/docs/agents/review">Agent review</a>.
69 </p>
70 {error ? <div class="flash error">{error}</div> : null}
71 {current ? (
72 <div class={`flash ${current.enabled ? "info" : ""}`}>
73 {current.enabled ? (
74 <>
75 Agent review is <b>on</b>: {current.agent.login} reviews with {runtimeLabel(current.runtime, current)}, using <b>{current.person.login}</b>'s model key (since <Time at={current.optedInAt} />).
76 </>
77 ) : (
78 <>Agent review is <b>off</b>.</>
79 )}
80 </div>
81 ) : null}
82 <Form action={`${base}/settings/agent-review`} t={csrfToken(c)} class="box">
83 <div class="head">
84 <h2>{current?.enabled ? "Change agent review" : "Turn on agent review"}</h2>
85 </div>
86 <div class="body fbody">
87 {!agents.length ? (
88 <div class="flash info">
89 You don't have an agent with write access here yet. <a href="/settings/agents">Create an agent</a>, then give it write access to this repository.
90 </div>
91 ) : null}
92 <div class="field">
93 <label for="agent">Agent</label>
94 <KSelect id="agent" name="agent" block label="Agent" value={v("agent", s.agent && agents.some((a) => a.id === s.agent!.id) ? s.agent.login : (agents[0]?.login ?? ""))} options={agents.map((a) => ({ value: a.login, label: a.name ? `${a.login} (${a.name})` : a.login }))} placeholder="Choose an agent" />
95 </div>
96 <div class="field">
97 <label>Runtime</label>
98 <KRadio name="runtime" label="Runtime" value={v("runtime", currentChoice ?? runtimes.find((r) => !r.disabled)?.value ?? "custom")} items={runtimes} />
99 </div>
100 <OpenRouterModel value={v("model", s.model ?? "")} />
101 <div class="field">
102 <label for="command">
103 Command <span class="faint">(custom runtime only)</span>
104 </label>
105 <input id="command" name="command" type="text" maxlength={2000} value={v("command", s.command ?? "")} placeholder='my-reviewer --prompt "$DIFFINERY_TASK_PROMPT"' />
106 <div class="hint">Gets the review instructions in $DIFFINERY_TASK_PROMPT and must end its output with the findings block they describe.</div>
107 </div>
108 <div class="field">
109 <label>When to review</label>
110 <KRadio name="trigger" label="When to review" value={v("trigger", s.trigger ?? "push")} items={Object.entries(TRIGGERS).map(([value, label]) => ({ value, label }))} />
111 <div class="hint">People with write access can always ask: the Request agent review button, a comment starting with @{s.agent?.login ?? "agent"} review, or requesting the agent as a reviewer.</div>
112 </div>
113 <div class="field">
114 <label>Which pull requests</label>
115 <KRadio name="authors" label="Which pull requests" value={v("authors", s.authors ?? "all")} items={Object.entries(AUTHORS).map(([value, label]) => ({ value, label }))} />
116 </div>
117 <div class="fchecks">
118 <KCheckbox name="drafts" checked={v("drafts", s.drafts ? "1" : "") === "1"} label="Review draft pull requests too" />
119 <KCheckbox
120 name="autofix"
121 checked={v("autofix", s.autofix ? "1" : "") === "1"}
122 label="Autofix"
123 description={<>When a review finds blocking problems, start an agent task that fixes them on the pull request's branch, at most {MAX_AUTOFIXES} times per pull request.</>}
124 />
125 </div>
126 <div class="fgrid">
127 <div class="field">
128 <label for="daily_limit">Daily limit</label>
129 <input id="daily_limit" name="daily_limit" type="number" min={1} max={REPO_DAILY_MAX} step={1} value={v("daily_limit", String(s.dailyLimit ?? REPO_DAILY_DEFAULT))} />
130 <div class="hint">The most reviews and autofix runs this repository starts in 24 hours. When it is reached, pull requests get an action-required check instead of a review, autofix waits, and you get an email. Each pull request also gets at most {PR_DAILY_AUTOMATIC} automatic reviews and {PR_DAILY_REVIEWS} in all a day.</div>
131 </div>
132 <div class="field">
133 <label for="tokens_per_review">Tokens per review</label>
134 <input id="tokens_per_review" name="tokens_per_review" type="number" min={REVIEW_TOKENS_MIN} max={REVIEW_TOKENS_MAX} step={1} value={v("tokens_per_review", String(s.tokensPerReview ?? REVIEW_TOKENS_DEFAULT))} />
135 <div class="hint">
136 A review stops when its next model request could take it past this many tokens (cache reads count as a tenth), after {REVIEW_MAX_MODEL_CALLS} model requests, or after {REVIEW_TIMEOUT_MS / 60_000} minutes, whichever comes first. Diffinery books the most each request may cost before sending it, then counts the tokens your provider reports.
137 </div>
138 </div>
139 </div>
140 <div class="flash info">
141 Every review on this repository, automatic or asked for by anyone with write access, runs with <b>your</b> model key{youPay ? "" : `, instead of ${current!.person.login}'s`}. Anything the agent reads, including code in pull requests, can try to trick it ("prompt injection"); its sandbox is read-only, but it can use your model access while a review runs. Use a dedicated key with a spending limit.
142 </div>
143 <div class="fchecks">
144 <KCheckbox name="accept" label="Agent reviews on this repository, including ones other people ask for, use my model key" />
145 </div>
146 <div class="factions">
147 <button class="btn primary" disabled={!agents.length}>
148 {current?.enabled ? "Save" : "Turn on agent review"}
149 </button>
150 </div>
151 </div>
152 </Form>
153 {current?.enabled ? (
154 <Form action={`${base}/settings/agent-review/off`} t={csrfToken(c)} class="box" confirm="Turn off agent review? Reviews already running finish.">
155 <div class="body row">
156 <div class="grow muted small">Turning it off stops new reviews. Findings already posted stay on their pull requests.</div>
157 <button class="btn danger">Turn off</button>
158 </div>
159 </Form>
160 ) : null}
161 </>,
162 error ? 422 : undefined,
163 );
164}
165
166export function registerReviews(web: WebApp): void {
167 const admin = (c: AppContext) => loadRepo(c, prm(c, "owner"), prm(c, "repo"), "admin");
168
169 web.get("/:owner/:repo/settings/agent-review", async (c) => settingsForm(c, await admin(c)));
170
171 post(web, "/:owner/:repo/settings/agent-review", async (c, f) => {
172 const l = await admin(c);
173 const values = { agent: f.s("agent"), runtime: f.s("runtime") || "claude-code", model: f.s("model"), command: f.s("command"), trigger: f.s("trigger") || "push", authors: f.s("authors") || "all", drafts: f.all("drafts").length ? "1" : "", autofix: f.all("autofix").length ? "1" : "", daily_limit: f.s("daily_limit"), tokens_per_review: f.s("tokens_per_review") };
174 try {
175 const { runtime, provider } = parseRuntimeChoice(values.runtime);
176 const s = await saveReviewSettings(c, l, { ...values, runtime, provider, model: provider ? values.model : undefined, drafts: !!values.drafts, autofix: !!values.autofix, accept: f.all("accept").length > 0 });
177 const me = requireAccount(c);
178 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "review.settings", target: `${l.repo.owner_login}/${l.repo.name}`, detail: { enabled: true, agent: s?.agent.login, runtime: s?.runtime, provider: s?.via ?? undefined, model: s?.model ?? undefined, trigger: s?.trigger, autofix: s?.autofix, daily_limit: s?.dailyLimit, tokens_per_review: s?.tokensPerReview } }));
179 } catch (e) {
180 const st = statusOf(e);
181 if (st.status >= 500) throw e;
182 return settingsForm(c, l, st.message, values);
183 }
184 return act(c, `${repoUrl(l.repo)}/settings/agent-review`, async () => {}, "Agent review is on.");
185 });
186
187 post(web, "/:owner/:repo/settings/agent-review/off", async (c) => {
188 const l = await admin(c);
189 return act(
190 c,
191 `${repoUrl(l.repo)}/settings/agent-review`,
192 async () => {
193 await saveReviewSettings(c, l, { enabled: false });
194 const me = requireAccount(c);
195 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: me.id, actorLogin: me.login, action: "review.settings", target: `${l.repo.owner_login}/${l.repo.name}`, detail: { enabled: false } }));
196 },
197 "Agent review is off.",
198 );
199 });
200
201 post(web, "/:owner/:repo/pull/:number/agent-review", async (c) => {
202 const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write");
203 const n = Number(c.req.param("number"));
204 return act(
205 c,
206 `${repoUrl(l.repo)}/pull/${n}`,
207 async () => {
208 await askForReview(c, l, n);
209 },
210 "Agent review requested. The result appears here and in the Agent review check.",
211 );
212 });
213}