Skip to content
refs
History
603 lines · 29.3 KBRaw
1import { Badge, Banner, Button, Empty, Input, InputArea, LayerCard, LinkButton } from "@refs/design-system";
2import { AgentAvatar, Ago } from "@refs/design-system";
3import { ArrowBendDownRightIcon, CaretDownIcon, CompassIcon, FileCodeIcon, GitBranchIcon, QuestionIcon, RecordIcon, WarningIcon } from "@refs/design-system/icons";
4import { MAX_BODY_LENGTH, MAX_TITLE_LENGTH, pullLink, type CommitSummary, type OnlineAgent, type ReviewThread } from "@refs/backend/contract";
5
6import { narrative, netDecisions, parseDecisions, type DecisionRecord } from "@refs/protocol";
7import { createContext, useContext, useEffect, useRef, useState } from "react";
8import { data, redirect, useFetcher, useRouteLoaderData } from "react-router";
9import type { Route } from "./+types/pull-reasoning";
10import type { loader as pullLoader } from "./pull-layout";
11import { useLive } from "../components/live";
12import { CommitMark } from "../components/commit-mark";
13import { PullStatusIcon } from "../components/pull-status";
14import { Opener, isAgent } from "../components/timeline";
15import { MentionTools, RUN_STATES, agentsOn } from "../components/mentions";
16import { ReviewThreadCard, type ThreadComment } from "../components/review-thread";
17import { THREAD_INTENTS, threadAction } from "../lib/threads";
18import { failed, formText, found, signedIn, fullName } from "../lib/session";
19import { useOnSuccess } from "../components/use-on-success";
20
21export const meta: Route.MetaFunction = ({ params }) => [
22 {
23 title: `Reasoning · Pull request #${params.number} · ${fullName(params)} · refs`,
24 },
25];
26
27export async function loader({ params, context }: Route.LoaderArgs) {
28 const refs = signedIn(context);
29 const repo = await found(refs.repo(fullName(params)));
30 const pull = await found(repo.pull(Number(params.number)));
31 const [timeline, agents, mentions, threads, branches] = await Promise.all([pull.timeline(), repo.agents(), pull.mentions(), pull.threads(), pull.branches()]);
32 const comments = timeline.filter((event): event is ThreadComment => event.kind === "pull.commented" && event.data.thread !== undefined);
33 return {
34 comments,
35 agents,
36 mentions,
37 branches,
38 threads: threads.filter((thread) => thread.decision !== null),
39 canResolve: refs.viewer.agent === null && repo.summary.can.write,
40 };
41}
42
43export async function action({ request, params, context }: Route.ActionArgs) {
44 const repo = await found(signedIn(context).repo(fullName(params)));
45 const pull = await found(repo.pull(Number(params.number)));
46 const form = await request.formData();
47 const intent = formText(form, "intent");
48 if (THREAD_INTENTS.has(intent)) {
49 const outcome = await threadAction(pull, intent, form);
50 return outcome.ok ? { intent, error: null } : failed(outcome.problem, { intent });
51 }
52 if (intent === "branch") {
53 const outcome = await pull.branch({ from: formText(form, "from"), title: formText(form, "title"), instruction: formText(form, "body"), assign: formText(form, "assign") === "1" });
54 return outcome.ok ? redirect(`${pullLink(fullName(params), outcome.value.pull)}/reasoning`) : failed(outcome.problem, { intent });
55 }
56 if (intent !== "steer") return data({ intent, error: "Unknown action." }, { status: 400 });
57 const outcome = await pull.steer({
58 revision: formText(form, "revision"),
59 decision: formText(form, "decision"),
60 body: formText(form, "body"),
61 assign: formText(form, "assign") === "1",
62 });
63 return outcome.ok ? { intent, error: null } : failed(outcome.problem, { intent });
64}
65
66type Steering = Route.ComponentProps["loaderData"] & {
67 revision: string;
68 base: string;
69 now: number;
70 onBranch: readonly OnlineAgent[];
71};
72const SteeringContext = createContext<Steering | null>(null);
73
74function Steer({ record, before, draft, onDraft }: { record: DecisionRecord; before: string; draft: string | null; onDraft: (draft: string | null) => void }) {
75 const { agents, revision, onBranch, canResolve } = useContext(SteeringContext)!;
76 const fetcher = useFetcher<typeof action>();
77 const [body, setBody] = useState("");
78 const area = useRef<HTMLDivElement>(null);
79 useEffect(() => {
80 if (draft === null) return;
81 const mention = onBranch.map((agent) => `@agent/${agent.session}`).join(" ");
82 setBody(`${mention}${mention ? " " : ""}${draft}`);
83 area.current?.querySelector("textarea")?.focus();
84 }, [draft]);
85 useOnSuccess(fetcher, () => onDraft(null));
86 if (draft === null) return null;
87
88 return (
89 <fetcher.Form method="post" className="reveal flex flex-col gap-3 rounded-panel bg-panel p-4 shadow-[0_0_0_1px_var(--accent-hover),0_0_0_4px_var(--accent-tint)]">
90 <input type="hidden" name="decision" value={record.decisionId} />
91 <input type="hidden" name="from" value={before} />
92 <input type="hidden" name="title" value={`Instead of: ${record.decision}`.slice(0, MAX_TITLE_LENGTH)} />
93 <input type="hidden" name="revision" value={revision} />
94 <div ref={area}>
95 <InputArea
96 label="Steer from this decision"
97 name="body"
98 value={body}
99 onValueChange={setBody}
100 maxLength={MAX_BODY_LENGTH}
101 rows={3}
102 description="Steer: the agent answers here, and this closes when it pushes a decision that supersedes this one. Try on a new branch: a new branch redoes this commit with its own pull request, and this one stays as it is."
103 />
104 </div>
105 <MentionTools agents={agents} body={body} onBody={setBody} canAssign />
106 {fetcher.data?.error && <Banner variant="error" description={fetcher.data.error} />}
107 <div className="flex flex-wrap justify-end gap-2">
108 <Button type="button" variant="secondary" onClick={() => onDraft(null)}>
109 Cancel
110 </Button>
111 {canResolve && (
112 <Button type="submit" name="intent" value="branch" variant="secondary" icon={<GitBranchIcon size={16} />} disabled={!body.trim()} loading={fetcher.state !== "idle" && fetcher.formData?.get("intent") === "branch"}>
113 Try on a new branch
114 </Button>
115 )}
116 <Button type="submit" name="intent" value="steer" variant="primary" icon={<CompassIcon size={16} />} disabled={!body.trim()} loading={fetcher.state !== "idle" && fetcher.formData?.get("intent") === "steer"}>
117 Steer
118 </Button>
119 </div>
120 </fetcher.Form>
121 );
122}
123
124function BranchFrom({ commit, title }: { commit: string; title: string }) {
125 const short = commit.slice(0, 7);
126 const { agents, onBranch } = useContext(SteeringContext)!;
127 const fetcher = useFetcher<typeof action>();
128 const dialog = useRef<HTMLDialogElement>(null);
129 const [body, setBody] = useState("");
130 const open = () => {
131 setBody(onBranch.map((agent) => `@agent/${agent.session} `).join(""));
132 dialog.current?.showModal();
133 };
134
135 return (
136 <>
137 <Button type="button" variant="ghost" size="sm" icon={<GitBranchIcon />} onClick={open}>
138 Branch from here…
139 </Button>
140 <dialog ref={dialog} className="m-auto w-[min(36rem,calc(100vw-2rem))] rounded-sheet bg-raised p-0 text-ink shadow-surface max-sm:mb-0 max-sm:w-full max-sm:max-w-full max-sm:rounded-b-none max-sm:pb-[env(safe-area-inset-bottom)]">
141 <fetcher.Form method="post" className="flex flex-col gap-3 p-5">
142 <input type="hidden" name="intent" value="branch" />
143 <input type="hidden" name="from" value={commit} />
144 <h2 className="m-0 text-lg font-semibold">
145 Branch from <code className="font-mono">{short}</code>
146 </h2>
147 <p className="m-0 text-sm text-muted">A new branch continues from this commit, with its own pull request. This pull request stays as it is.</p>
148 <Input label="Title" name="title" defaultValue={`${title}: another path from ${short}`.slice(0, MAX_TITLE_LENGTH)} maxLength={MAX_TITLE_LENGTH} required />
149 <InputArea label="What should the agent try from here?" name="body" value={body} onValueChange={setBody} maxLength={MAX_BODY_LENGTH} rows={4} />
150 <MentionTools agents={agents} body={body} onBody={setBody} canAssign />
151 {fetcher.data?.error && <Banner variant="error" description={fetcher.data.error} />}
152 <div className="flex justify-end gap-2">
153 <Button type="button" variant="secondary" onClick={() => dialog.current?.close()}>
154 Cancel
155 </Button>
156 <Button type="submit" variant="primary" icon={<GitBranchIcon size={16} />} disabled={!body.trim()} loading={fetcher.state !== "idle"}>
157 Branch
158 </Button>
159 </div>
160 </fetcher.Form>
161 </dialog>
162 </>
163 );
164}
165
166function Branches({ commit }: { commit: string }) {
167 const { branches, base } = useContext(SteeringContext)!;
168 const here = branches.filter((branch) => branch.commit === commit);
169 if (!here.length) return null;
170 return (
171 <ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
172 {here.map(({ pull }) => (
173 <li key={pull.number} className="flex flex-wrap items-center gap-2">
174 <PullStatusIcon status={pull.status} size={14} />
175 <span className="text-muted">Branched into</span>
176 <a href={`${pullLink(pull.repo, pull.number)}/reasoning`} className="font-medium text-accent-text">
177 {pull.title} #{pull.number}
178 </a>
179 </li>
180 ))}
181 </ul>
182 );
183}
184
185function Threads({ decision }: { decision: string }) {
186 const { threads, comments, agents, mentions, canResolve, base, now } = useContext(SteeringContext)!;
187 return threads
188 .filter((thread) => thread.decision === decision)
189 .map((thread: ReviewThread) => (
190 <ReviewThreadCard
191 key={thread.id}
192 thread={thread}
193 comments={comments.filter((comment) => comment.data.thread === thread.id)}
194 pullBase={base}
195 agents={agents}
196 canResolve={canResolve}
197 mentionsOf={(comment) => mentions.filter((mention) => mention.comment === comment && !RUN_STATES.has(mention.state))}
198 now={now}
199 />
200 ));
201}
202
203interface Step {
204 readonly commit: CommitSummary;
205 readonly story: string;
206 readonly decisions: readonly DecisionRecord[];
207 readonly problems: readonly string[];
208}
209
210function unexplained(step: Step): boolean {
211 return (step.commit.files?.length ?? 0) > 0 && !step.story && step.decisions.length === 0;
212}
213
214const ROW = "shadow-[inset_0_-1px_0_var(--hairline)] last:shadow-none";
215const ROW_BUTTON = "flex w-full cursor-pointer items-start gap-3 px-4 py-3 text-left hover:bg-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent-hover";
216
217function Caret({ open }: { open: boolean }) {
218 return <CaretDownIcon aria-hidden="true" className={`mt-0.5 shrink-0 text-faint ${open ? "rotate-180" : ""}`} />;
219}
220
221function plural(count: number, one: string): string {
222 return `${count} ${count === 1 ? one : `${one}s`}`;
223}
224
225function Flags({ steps }: { steps: readonly Step[] }) {
226 const first = (test: (step: Step) => boolean) => steps.find(test)?.commit.hash;
227 const broken = (step: Step) => step.problems.length > 0;
228 const items = [
229 { count: steps.filter(unexplained).length, label: "unexplained change", step: first(unexplained), tone: "text-caution" },
230 { count: steps.filter(broken).length, label: "unreadable record", step: first(broken), tone: "text-danger" },
231 ].filter((item) => item.count > 0);
232 return (
233 <span className="flex flex-wrap gap-x-3 font-normal tabular-nums">
234 {items.map((item) => (
235 <a key={item.label} href={`#${item.step}`} className={`${item.tone} underline-offset-4 hover:underline`}>
236 {plural(item.count, item.label)}
237 </a>
238 ))}
239 </span>
240 );
241}
242
243function Pick({ label, onPick }: { label: string; onPick: () => void }) {
244 return (
245 <button type="button" onClick={onPick} className="shrink-0 cursor-pointer text-compact text-accent-text opacity-0 transition-opacity duration-150 group-hover:opacity-100 focus-visible:opacity-100 max-sm:opacity-100">
246 {label}
247 </button>
248 );
249}
250
251function Field({ label, children }: { label: string; children: React.ReactNode }) {
252 return (
253 <>
254 <dt className="caption pt-0.5 text-faint max-sm:-mb-1.5">{label}</dt>
255 <dd className="m-0 min-w-0">{children}</dd>
256 </>
257 );
258}
259
260/** A commit body as paragraphs and lists: hard-wrapped lines are joined, list items keep their own lines. */
261function Prose({ text }: { text: string }) {
262 const blocks = text.split(/\n{2,}/).map((block) => block.split("\n"));
263 return (
264 <div className="flex max-w-[72ch] flex-col gap-2.5 text-compact leading-relaxed text-ink">
265 {blocks.map((lines, index) =>
266 lines.every((line) => /^\s*[-*] /.test(line)) ? (
267 <ul key={index} className="m-0 flex list-disc flex-col gap-1 pl-5 marker:text-faint">
268 {lines.map((line) => (
269 <li key={line}>{line.replace(/^\s*[-*] /, "")}</li>
270 ))}
271 </ul>
272 ) : (
273 <p key={index} className="m-0">
274 {lines.join(" ")}
275 </p>
276 ),
277 )}
278 </div>
279 );
280}
281
282function Author({ commit }: { commit: CommitSummary }) {
283 return commit.pushedBy && isAgent(commit.pushedBy) ? <Opener by={commit.pushedBy} /> : commit.author;
284}
285
286interface Judged {
287 readonly record: DecisionRecord;
288 readonly before: string;
289 readonly commit: CommitSummary;
290}
291
292function JudgedDecision({ judged, open, steered, onToggle }: { judged: Judged; open: boolean; steered: boolean; onToggle: () => void }) {
293 const { record, before, commit } = judged;
294 const short = commit.hash.slice(0, 7);
295 const { now } = useContext(SteeringContext)!;
296 const [draft, setDraft] = useState<string | null>(null);
297 const notTaken = [...new Set([...record.alternativesConsidered, ...Object.keys(record.rejected)])];
298 const touches = [...record.affectedComponents, ...record.evidence];
299 return (
300 <li id={record.decisionId} className={`scroll-mt-24 ${ROW}`}>
301 <button type="button" aria-expanded={open} onClick={onToggle} className={ROW_BUTTON}>
302 <RecordIcon aria-hidden="true" className={`mt-0.5 shrink-0 ${open ? "text-ink" : "text-faint"}`} />
303 <span className="flex min-w-0 flex-1 flex-col gap-1 sm:flex-row sm:items-baseline sm:gap-4">
304 <span className={`min-w-0 flex-1 text-base leading-snug text-pretty text-ink ${open ? "font-semibold" : "font-medium"}`}>{record.decision}</span>
305 <span className="flex shrink-0 gap-3 text-xs text-faint tabular-nums">
306 {record.assumptions.length > 0 && <span className="text-caution">{plural(record.assumptions.length, "assumption")}</span>}
307 {steered && <span className="text-accent-text">Steered</span>}
308 <span className="font-mono">{short}</span>
309 </span>
310 </span>
311 <Caret open={open} />
312 </button>
313 <div className={open ? "flex flex-col gap-4 px-4 pt-1 pb-4 sm:pl-11" : "hidden"}>
314 <dl className="m-0 grid max-w-[72ch] gap-x-6 gap-y-2.5 text-compact leading-relaxed sm:grid-cols-[9rem_minmax(0,1fr)]">
315 <Field label="Why">
316 {record.reason.length === 1 ? (
317 record.reason[0]
318 ) : (
319 <ul className="m-0 flex list-disc flex-col gap-1 pl-4 marker:text-faint">
320 {record.reason.map((reason) => (
321 <li key={reason}>{reason}</li>
322 ))}
323 </ul>
324 )}
325 </Field>
326 {record.toReverse && <Field label="If this changes later">{record.toReverse}</Field>}
327 {record.assumptions.length > 0 && (
328 <Field label="Assumes">
329 <ul className="m-0 flex list-none flex-col gap-1 p-0">
330 {record.assumptions.map((assumption) => (
331 <li key={assumption} className="group flex items-baseline justify-between gap-3">
332 <span className="text-caution">{assumption}</span>
333 <Pick label="Challenge" onPick={() => setDraft(`This assumption doesn't hold: "${assumption}". `)} />
334 </li>
335 ))}
336 </ul>
337 </Field>
338 )}
339 {notTaken.length > 0 && (
340 <Field label="Not taken">
341 <ul className="m-0 flex list-none flex-col gap-1 p-0">
342 {notTaken.map((name) => (
343 <li key={name} className="group flex items-baseline justify-between gap-3">
344 <span className="flex min-w-0 flex-col">
345 <span>{name}</span>
346 {record.rejected[name] && <span className="text-muted">{record.rejected[name]}</span>}
347 </span>
348 <Pick label="Take this path" onPick={() => setDraft(`Go with ${name} instead. `)} />
349 </li>
350 ))}
351 </ul>
352 </Field>
353 )}
354 {touches.length > 0 && (
355 <Field label="Touches">
356 <span className="font-mono text-xs text-muted">{touches.join(", ")}</span>
357 </Field>
358 )}
359 </dl>
360 <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
361 <span className="text-xs text-muted">
362 <Author commit={commit} /> ·{" "}
363 <a href={`#${commit.hash}`} className="font-mono underline-offset-4 hover:text-ink hover:underline">
364 {short}
365 </a>{" "}
366 · <Ago at={commit.committedAt} now={now} />
367 </span>
368 {draft === null && (
369 <Button type="button" variant="secondary" size="sm" icon={<CompassIcon />} onClick={() => setDraft("")}>
370 Steer
371 </Button>
372 )}
373 </div>
374 <Steer record={record} before={before} draft={draft} onDraft={setDraft} />
375 <Threads decision={record.decisionId} />
376 </div>
377 </li>
378 );
379}
380
381function Decisions({ judged, status, files, open, steered, onToggle }: { judged: readonly Judged[]; status: "open" | "closed" | "merged"; files: string; open: string | null; steered: ReadonlySet<string | null>; onToggle: (id: string) => void }) {
382 const count = plural(judged.length, "decision");
383 return (
384 <LayerCard id="decisions" className="scroll-mt-24">
385 <LayerCard.Secondary>
386 <h2 className="m-0 text-compact font-medium tabular-nums">{judged.length === 0 ? "Decisions" : status === "merged" ? `${count} accepted at merge` : status === "open" ? `${count} to judge` : count}</h2>
387 </LayerCard.Secondary>
388 {judged.length === 0 ? (
389 <LayerCard.Primary className="items-start gap-3 py-5">
390 <div className="flex flex-col gap-1">
391 <p className="m-0 text-base font-medium text-ink">No decision needs your judgement</p>
392 <p className="m-0 max-w-[60ch] text-compact text-muted">No commit on this branch records a choice for you to make. Read the commits below, or review the code.</p>
393 </div>
394 <LinkButton href={files} variant="secondary" size="sm" icon={<FileCodeIcon />}>
395 Review the files
396 </LinkButton>
397 </LayerCard.Primary>
398 ) : (
399 <ol className="m-0 flex list-none flex-col p-0">
400 {judged.map((item) => (
401 <JudgedDecision key={item.record.decisionId} judged={item} open={open === item.record.decisionId} steered={steered.has(item.record.decisionId)} onToggle={() => onToggle(item.record.decisionId)} />
402 ))}
403 </ol>
404 )}
405 </LayerCard>
406 );
407}
408
409/** A decision inside its step: one line that leads back to the decision in the list above. */
410function CommitDecision({ record, listed, supersededIn }: { record: DecisionRecord; listed: boolean; supersededIn: string | undefined }) {
411 const superseded = supersededIn !== undefined;
412 return (
413 <li className="flex items-start gap-2 text-compact">
414 <RecordIcon aria-hidden="true" className="mt-0.5 shrink-0 text-faint" />
415 {listed ? (
416 <a href={`#${record.decisionId}`} className="min-w-0 font-medium text-ink underline-offset-4 hover:underline">
417 {record.decision}
418 </a>
419 ) : (
420 <span className={`min-w-0 text-muted ${superseded ? "line-through decoration-faint" : ""}`}>{record.decision}</span>
421 )}
422 {superseded && (
423 <a href={`#${supersededIn}`} className="shrink-0">
424 <Badge variant="secondary">Reconsidered in {supersededIn.slice(0, 7)}</Badge>
425 </a>
426 )}
427 </li>
428 );
429}
430
431function CommitRow({ step, open, listed, supersededIn, onToggle }: { step: Step; open: boolean; listed: ReadonlySet<string>; supersededIn: ReadonlyMap<string, string>; onToggle: () => void }) {
432 const { now, canResolve } = useContext(SteeringContext)!;
433 const { pull } = useRouteLoaderData<typeof pullLoader>("routes/pull-layout")!;
434 const { commit, story, decisions, problems } = step;
435 const files = commit.files ?? [];
436 const agent = commit.pushedBy !== undefined && commit.pushedBy !== null && isAgent(commit.pushedBy);
437 return (
438 <li id={commit.hash} className={`group/commit scroll-mt-24 ${ROW}`}>
439 <div className="relative flex items-center gap-3 py-2.5 pr-4 pl-12 hover:bg-hover">
440 <CommitMark agent={agent} decisions={decisions.length} />
441 <button type="button" aria-expanded={open} onClick={onToggle} className="flex min-w-0 flex-1 cursor-pointer flex-col text-left after:absolute after:inset-0 focus-visible:outline-none focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-accent-hover">
442 <span className={`max-w-full font-medium text-ink ${open ? "" : "truncate"}`}>{commit.title}</span>
443 <span className="flex max-w-full flex-wrap items-center gap-x-1.5 text-compact text-muted">
444 <Author commit={commit} /> committed <Ago at={commit.committedAt} now={now} />
445 {unexplained(step) && <span className="text-caution">· No reason given</span>}
446 {problems.length > 0 && <span className="text-danger">· Unreadable record</span>}
447 </span>
448 </button>
449 <a href={`/${pull.repo}/commit/${commit.hash}`} className="relative z-1 shrink-0 rounded-chip bg-sunken px-1.5 py-0.5 font-mono text-xs text-ink shadow-[inset_0_0_0_1px_var(--hairline)] hover:text-accent-text">
450 {commit.hash.slice(0, 7)}
451 </a>
452 <Caret open={open} />
453 </div>
454 {open && (
455 <div className="relative flex min-w-0 flex-col gap-3.5 pt-1 pr-4 pb-4 pl-12">
456 <span aria-hidden className="absolute top-0 bottom-0 left-[22px] w-0.5 bg-porcelain/45 group-last/commit:hidden" />
457 {story && <Prose text={story} />}
458 {unexplained(step) && (
459 <p className="m-0 flex items-center gap-1.5 text-compact text-caution">
460 <QuestionIcon className="shrink-0" />
461 This commit changes code without saying why.
462 </p>
463 )}
464 {problems.map((problem) => (
465 <p key={problem} className="m-0 flex items-start gap-1.5 text-compact text-danger">
466 <WarningIcon className="mt-0.5 shrink-0" />
467 <span>
468 A decision record here could not be read. <span className="text-muted">{problem}</span>
469 </span>
470 </p>
471 ))}
472 {decisions.length > 0 && (
473 <ul className="m-0 flex list-none flex-col gap-1.5 p-0">
474 {decisions.map((record) => (
475 <CommitDecision key={record.decisionId} record={record} listed={listed.has(record.decisionId)} supersededIn={supersededIn.get(record.decisionId)} />
476 ))}
477 </ul>
478 )}
479 {files.length > 0 && (
480 <details className="text-compact">
481 <summary className="w-fit cursor-pointer text-muted select-none hover:text-ink">{plural(files.length, "file")} changed</summary>
482 <ul className="m-0 mt-2 flex list-none flex-col gap-0.5 p-0 font-mono text-xs text-muted">
483 {files.map((path) => (
484 <li key={path} className="truncate">
485 {path}
486 </li>
487 ))}
488 </ul>
489 </details>
490 )}
491 <Branches commit={commit.hash} />
492 {canResolve && (
493 <div className="-ml-2">
494 <BranchFrom commit={commit.hash} title={pull.title} />
495 </div>
496 )}
497 </div>
498 )}
499 </li>
500 );
501}
502
503function OnThisLine({ agents, branches }: { agents: readonly OnlineAgent[]; branches: Steering["branches"] }) {
504 return (
505 <aside className="flex flex-col gap-5 xl:sticky xl:top-24 xl:self-start">
506 <section className="flex flex-col gap-2">
507 <h2 className="caption m-0 text-faint">Agents on this branch</h2>
508 {agents.length ? (
509 <ul className="m-0 flex list-none flex-col gap-2 p-0">
510 {agents.map((agent) => (
511 <li key={agent.session} className="flex items-start gap-2.5 text-compact">
512 <AgentAvatar name={agent.runtime} size="xs" className="mt-0.5" />
513 <span className="flex min-w-0 flex-col leading-tight">
514 <span className="truncate font-medium">
515 {agent.runtime} <span className="font-normal text-muted">for {agent.onBehalfOf.name}</span>
516 </span>
517 <span className="truncate text-xs text-faint">{[agent.machine, agent.branch].filter(Boolean).join(" · ") || "idle"}</span>
518 </span>
519 </li>
520 ))}
521 </ul>
522 ) : (
523 <p className="m-0 text-compact text-muted">No agent is working on this branch now.</p>
524 )}
525 </section>
526 {branches.length > 0 && (
527 <section className="flex flex-col gap-2">
528 <h2 className="caption m-0 text-faint">Branches from this pull request</h2>
529 <ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-compact">
530 {branches.map(({ pull }) => (
531 <li key={pull.number} className="flex items-center gap-2">
532 <GitBranchIcon className="shrink-0 text-ochre" />
533 <a href={`${pullLink(pull.repo, pull.number)}/reasoning`} className="truncate text-accent-text hover:underline">
534 {pull.title} #{pull.number}
535 </a>
536 </li>
537 ))}
538 </ul>
539 </section>
540 )}
541 </aside>
542 );
543}
544
545export default function PullReasoning({ loaderData }: Route.ComponentProps) {
546 const { pull, changes, now } = useRouteLoaderData<typeof pullLoader>("routes/pull-layout")!;
547 useLive(pull.repo);
548 const commits = changes?.commits ?? [];
549 const steps: Step[] = commits.map((commit) => {
550 const parsed = parseDecisions(commit.message ?? "", commit.hash);
551 return { commit, story: narrative(commit.message ?? ""), decisions: parsed.decisions, problems: parsed.problems.map((problem) => problem.message) };
552 });
553 const judged: Judged[] = netDecisions(steps.flatMap((step, index) => step.decisions.map((record) => ({ record, before: index === 0 ? (changes?.base ?? "") : steps[index - 1].commit.hash, commit: step.commit }))));
554 const [openDecision, setOpenDecision] = useState<string | null>(judged.length === 1 ? judged[0].record.decisionId : null);
555 const [openCommit, setOpenCommit] = useState<string | null>(null);
556 const follow = (id: string) => {
557 if (commits.some((commit) => commit.hash === id)) setOpenCommit(id);
558 else if (judged.some(({ record }) => record.decisionId === id)) setOpenDecision(id);
559 };
560 useEffect(() => follow(decodeURIComponent(location.hash.slice(1))), []);
561 if (!changes || !steps.length)
562 return (
563 <Empty icon={<ArrowBendDownRightIcon size={40} />} title="No reasoning yet" description={changes ? `${pull.base} already contains every commit on ${pull.head}.` : `The ${pull.head} branch no longer exists.`} />
564 );
565
566 const supersededIn = new Map<string, string>();
567 steps.forEach((step) => step.decisions.forEach((record) => record.supersedes.forEach((id) => supersededIn.set(id, step.commit.hash))));
568 const steering: Steering = {
569 ...loaderData,
570 revision: changes.head,
571 base: pullLink(pull.repo, pull.number),
572 now,
573 onBranch: agentsOn(loaderData.agents, pull.head),
574 };
575 const steered = new Set(loaderData.threads.map((thread) => thread.decision));
576 const listed = new Set(judged.map(({ record }) => record.decisionId));
577 const followLink = (event: React.MouseEvent) => {
578 const href = (event.target as Element).closest("a")?.getAttribute("href");
579 if (href?.startsWith("#")) follow(decodeURIComponent(href.slice(1)));
580 };
581
582 return (
583 <SteeringContext.Provider value={steering}>
584 <div onClick={followLink} className={`grid gap-10 ${steering.onBranch.length || loaderData.branches.length ? "xl:grid-cols-[minmax(0,1fr)_17rem]" : ""}`}>
585 <div className="flex w-full max-w-[60rem] min-w-0 flex-col gap-3">
586 <Decisions judged={judged} status={pull.status} files={`${steering.base}/files`} open={openDecision} steered={steered} onToggle={(id) => setOpenDecision((current) => (current === id ? null : id))} />
587 <LayerCard className="mt-5">
588 <LayerCard.Secondary className="flex-wrap justify-between gap-x-4 gap-y-0.5">
589 <h2 className="m-0 text-compact font-medium tabular-nums">{plural(steps.length, "commit")}</h2>
590 <Flags steps={steps} />
591 </LayerCard.Secondary>
592 <ol className="m-0 flex list-none flex-col p-0">
593 {steps.map((step) => (
594 <CommitRow key={step.commit.hash} step={step} open={openCommit === step.commit.hash} listed={listed} supersededIn={supersededIn} onToggle={() => setOpenCommit((current) => (current === step.commit.hash ? null : step.commit.hash))} />
595 ))}
596 </ol>
597 </LayerCard>
598 </div>
599 {(steering.onBranch.length > 0 || loaderData.branches.length > 0) && <OnThisLine agents={steering.onBranch} branches={loaderData.branches} />}
600 </div>
601 </SteeringContext.Provider>
602 );
603}