g1t/apps/web/app/routes/repo/plan.tsx

302 lines13,664 bytesCodeBlame
1import { env } from "cloudflare:workers";
2import type { G1tEvent } from "@g1t/contracts";
3import { ArrowRight, CircleCheck, FileCode2, Sparkles } from "lucide-react";
4import { Form, Link, data } from "react-router";
5
6import type { Route } from "./+types/plan";
7import { refusal, requireRepo } from "../../lib/access.server";
8import { whyNot } from "../../lib/access";
9import { page } from "../../lib/meta";
10import { Markdown } from "../../components/markdown";
11import { Activity, Exchanges } from "../../components/activity";
12import { Outcome } from "../../components/outcome";
13import { ErrorText, SubmitButton, TimeAgo, usePending } from "../../components/ui";
14import { Checkbox } from "../../components/ui/checkbox";
15import { Label } from "../../components/work";
16import { billing, events, identity, work } from "../../lib/services.server";
17import {
18 assertSameOrigin,
19 getViewer,
20 requireUser,
21 unwrap,
22} from "../../lib/session.server";
23import { useRefreshWhile } from "../../lib/refresh";
24
25
26export function meta({ params, ...args }: Route.MetaArgs) {
27 return page(args, { title: `Plan · ${params.owner}/${params.repo} · g1t` });
28}
29
30export async function loader({ params, context }: Route.LoaderArgs) {
31 const viewer = getViewer(context);
32 // Anyone who can read the repository: a public one's to anyone, a private one's to people with a role.
33 const { access } = await requireRepo(context, params, "read");
34 const path = { namespace: params.owner, name: params.repo };
35 const [plan, ledger] = await Promise.all([
36 work.getPlan(path, viewer, params.id),
37 billing.ledger(params.owner, viewer),
38 ]);
39 const found = unwrap(plan);
40 // What the agents working on this outcome have cost so far.
41 const pulls = new Set(found.progress.flatMap((item) => (item.pull != null ? [item.pull] : [])));
42 const repo = `${params.owner}/${params.repo}`;
43 const costMicros = ledger.ok
44 ? ledger.value
45 .filter((entry) => entry.kind === "usage" && entry.repo === repo && entry.number != null && pulls.has(entry.number))
46 .reduce((sum, entry) => sum - entry.amountMicros, 0)
47 : null;
48 // What happened across the outcome's issues and pull requests.
49 let activity: G1tEvent[] = [];
50 if (found.status === "applied" && found.progress.length > 0) {
51 const numbers = new Set([
52 ...found.progress.map((item) => item.number),
53 ...found.progress.flatMap((item) => (item.pull != null ? [item.pull] : [])),
54 ]);
55 const since = found.finishedAt ?? found.createdAt;
56 const recent = await events.list({ repoId: found.repoId, limit: 200 }).catch(() => []);
57 activity = recent
58 .filter((event) => event.time >= since)
59 .filter((event) => {
60 const data = event.data as { number?: number; issue?: number };
61 // Issues an agent filed while working on this outcome belong to it too.
62 if (event.type === "issue.opened" && event.actor === "usr_g1t_agent") return true;
63 return (data.number != null && numbers.has(data.number)) || (data.issue != null && numbers.has(data.issue));
64 })
65 .slice(0, 40);
66 // Events name accounts by id; show names.
67 const named = await identity
68 .usernames([...new Set(activity.flatMap((event) => (event.actor ? [event.actor] : [])))])
69 .catch(() => ({}) as Record<string, string>);
70 const known: Record<string, string> = { ...named, usr_g1t_agent: "g1t", g1t_policy: "g1t" };
71 activity = activity.map((event) => ({ ...event, actor: event.actor ? (known[event.actor] ?? event.actor) : null }));
72 }
73 return { plan: found, costMicros, activity, can: access.can };
74}
75
76export async function action({ request, params, context }: Route.ActionArgs) {
77 assertSameOrigin(request);
78 const user = requireUser(context, request);
79 const form = await request.formData();
80 const path = { namespace: params.owner, name: params.repo };
81 // Opening the issues and putting agents on them: Write and up.
82 const refused = await refusal(context, params, "run");
83 if (refused) return { error: refused };
84 const applied = await env.RUNNER.applyPlan(user, path, params.id, {
85 assign: form.get("action") === "assign",
86 keep: form.getAll("keep").map(Number),
87 });
88 return applied.ok ? null : { error: applied.error.message };
89}
90
91export default function PlanPage({ loaderData, actionData, params }: Route.ComponentProps) {
92 const { plan, costMicros, activity } = loaderData;
93 const base = `/${params.owner}/${params.repo}`;
94 // Either way of applying it, so the other button waits too.
95 const applying = usePending();
96
97 // The agent is still writing it.
98 const planning = plan.status === "planning";
99 // Planning, or agents still converging what was applied.
100 const moving =
101 planning || plan.progress.some((item) => item.state !== "landed" && item.state !== "closed");
102 useRefreshWhile(moving);
103 const converging = plan.status === "applied" && plan.progress.length > 0;
104
105 const independent = plan.issues.filter((issue) => issue.dependsOn.length === 0).length;
106 return (
107 <div className={converging ? "" : "max-w-4xl"}>
108 <p className="text-sm">
109 <Link to={`${base}/plans`} className="text-muted hover:text-fg">
110 Plans
111 </Link>
112 </p>
113 <h2 className="mt-2 text-xl font-semibold tracking-tight">The outcome</h2>
114 <div className="mt-3 rounded-xl border border-line bg-surface p-5 text-sm">
115 <Markdown source={plan.brief} repo={{ namespace: params.owner, name: params.repo }} />
116 </div>
117 <p className="mt-2 text-xs text-faint">
118 Asked for by {plan.author.username} <TimeAgo at={plan.createdAt} />
119 </p>
120
121 {converging && (
122 <section className="mt-8">
123 <Outcome plan={plan} base={base} costMicros={costMicros} />
124 {plan.exchanges.length > 0 && (
125 <div className="mt-10">
126 <h3 className="font-mono text-[0.6875rem] tracking-[0.2em] text-faint uppercase">Agents talking</h3>
127 <div className="mt-3 max-w-3xl">
128 <Exchanges exchanges={plan.exchanges} base={base} />
129 </div>
130 </div>
131 )}
132 {activity.length > 0 && (
133 <div className="mt-10">
134 <h3 className="font-mono text-[0.6875rem] tracking-[0.2em] text-faint uppercase">What happened</h3>
135 <div className="mt-3 max-w-3xl">
136 <Activity events={activity} base={base} />
137 </div>
138 </div>
139 )}
140 </section>
141 )}
142
143 {planning && (
144 <div className="mt-8 flex items-center gap-3 rounded-xl border border-accent/30 bg-accent/5 px-4 py-4 text-sm">
145 <span className="size-2 animate-pulse rounded-full bg-accent" />
146 <span>
147 An agent is reading the repository and writing the plan. This takes a
148 minute or two; the page fills in when it is done.
149 </span>
150 </div>
151 )}
152 {plan.status === "failed" && (
153 <div className="mt-8 rounded-xl border border-danger/40 bg-danger/5 px-4 py-4 text-sm">
154 <p className="font-medium">The plan could not be written</p>
155 <p className="mt-1 text-muted">{plan.error}</p>
156 <p className="mt-3">
157 <Link to={`${base}/plans`} className="text-fg underline underline-offset-4">
158 Try again
159 </Link>
160 </p>
161 </div>
162 )}
163
164 {plan.issues.length > 0 && (
165 <Form method="post" className="mt-8">
166 <div className="flex flex-wrap items-baseline justify-between gap-2">
167 <h2 className="text-xl font-semibold tracking-tight">
168 {plan.status === "applied" ? "What was opened" : "The plan"}
169 </h2>
170 <p className="text-sm text-muted">
171 {plan.issues.length} {plan.issues.length === 1 ? "issue" : "issues"},{" "}
172 {independent} that can start at once
173 </p>
174 </div>
175 {plan.summary && <p className="mt-2 text-sm text-muted">{plan.summary}</p>}
176
177 <ol className="mt-5 space-y-3">
178 {plan.issues.map((issue, index) => {
179 const position = index + 1;
180 return (
181 <li
182 key={position}
183 className="flex gap-3 rounded-xl border border-line bg-surface p-4"
184 >
185 {plan.status === "ready" ? (
186 <Checkbox
187 name="keep"
188 value={String(position)}
189 defaultChecked
190 aria-label={`Open issue ${position}`}
191 className="mt-1"
192 />
193 ) : (
194 <span className="mt-0.5 w-5 shrink-0 text-center font-mono text-sm text-faint">
195 {position}
196 </span>
197 )}
198 <div className="min-w-0 grow">
199 <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
200 {issue.number != null ? (
201 <Link
202 to={`${base}/issues/${issue.number}`}
203 className="font-medium hover:underline"
204 >
205 {issue.title}{" "}
206 <span className="font-normal text-faint">#{issue.number}</span>
207 </Link>
208 ) : (
209 <span className="font-medium">
210 <span className="mr-1.5 font-mono text-sm font-normal text-faint">
211 {position}.
212 </span>
213 {issue.title}
214 </span>
215 )}
216 {issue.labels.map((name) => (
217 <Label key={name} name={name} />
218 ))}
219 </div>
220 <p className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">
221 {issue.dependsOn.length === 0 ? (
222 <span className="text-accent">Starts at once</span>
223 ) : (
224 <span className="flex items-center gap-1">
225 <ArrowRight size={12} />
226 After{" "}
227 {issue.dependsOn
228 .map((earlier) => {
229 const number = plan.issues[earlier - 1]?.number;
230 return number != null ? `#${number}` : `${earlier}`;
231 })
232 .join(", ")}
233 </span>
234 )}
235 {(issue.done ?? []).map((point) => (
236 <span key={point} className="flex items-center gap-1">
237 <CircleCheck size={12} />
238 {point}
239 </span>
240 ))}
241 </p>
242 {issue.files.length > 0 && (
243 <p className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 font-mono text-xs text-faint">
244 <FileCode2 size={12} />
245 {issue.files.map((file) => (
246 <span key={file}>{file}</span>
247 ))}
248 </p>
249 )}
250 <details className="mt-2">
251 <summary className="cursor-pointer text-xs text-faint hover:text-fg">
252 What the agent will be told
253 </summary>
254 <div className="mt-2 border-t border-line pt-3">
255 <Markdown source={issue.body} repo={{ namespace: params.owner, name: params.repo }} />
256 </div>
257 </details>
258 </div>
259 </li>
260 );
261 })}
262 </ol>
263
264 {plan.status === "ready" && (
265 <div className="mt-6 flex flex-wrap items-center gap-3">
266 <SubmitButton variant="accent" name="action" value="assign" pending="Opening issues…" disabled={applying || !loaderData.can.run} title={whyNot(loaderData.can, "run")}>
267 <Sparkles size={15} />
268 Open these and assign g1t
269 </SubmitButton>
270 <SubmitButton variant="quiet" name="action" value="open" pending="Opening issues…" disabled={applying || !loaderData.can.run} title={whyNot(loaderData.can, "run")}>
271 Only open the issues
272 </SubmitButton>
273 <span className="text-xs text-muted">
274 Untick any you do not want. Agents work on the independent ones at once
275 and the rest follow as what they depend on merges.
276 </span>
277 </div>
278 )}
279 {plan.status === "applied" && !moving && (
280 <p className="mt-6 text-sm text-muted">Everything in this plan has landed.</p>
281 )}
282 {plan.status === "applied" && moving && (
283 <p className="mt-6 text-sm text-muted">
284 Some are still open. Follow them under{" "}
285 <Link to={`${base}/issues`} className="text-fg underline underline-offset-4">
286 Issues
287 </Link>{" "}
288 or in{" "}
289 <Link to="/" className="text-fg underline underline-offset-4">
290 mission control
291 </Link>
292 .
293 </p>
294 )}
295 <div className="mt-3">
296 <ErrorText>{actionData?.error}</ErrorText>
297 </div>
298 </Form>
299 )}
300 </div>
301 );
302}