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