proposal-view.tsx
This file
Path
apps/web/src/features/proposal/proposal-view.tsx
483 lines · 15.0 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { Brand } from "@repo/brand";2import type { ConfigFile } from "@repo/protocol/domain/common";3import { DraftState } from "@repo/protocol/domain/proposal";4import type { Proposal } from "@repo/protocol/domain/proposal";5import type { DecisionId, ProjectName } from "@repo/protocol/ids";6import { groups } from "@repo/protocol/refusal";7import type { Refusal } from "@repo/protocol/refusal";8import { Array as Arr, DateTime, Option } from "effect";9import { constVoid } from "effect/Function";10import { ChevronDown, Scale, X } from "lucide-react";11import { useId, useState } from "react";12import type { ReactNode } from "react";1314import { Button } from "../../components/ui/button.tsx";15import { Textarea } from "../../components/ui/textarea.tsx";16import { isTestPath } from "../code/diff-model.ts";17import { FactBlock } from "../shared/facts.tsx";18import { HandleLink } from "../shared/handle.tsx";19import { AppLink } from "../shared/link.tsx";20import { decisionPath } from "../shared/paths.ts";21import { RefusalView } from "../shared/refusal.tsx";22import { Workspace } from "../shared/shell/workspace.tsx";23import { StatusLine } from "../shared/status-line.tsx";24import { When } from "../shared/time.tsx";25import { DraftedCode } from "./client-file.tsx";2627/**28 * The platform's `DRAFT_ROUNDS`, which the web's production code does not29 * import; `test/proposal.test.tsx` holds the two equal.30 */31export const DRAFT_ATTEMPTS = 3;3233const NOTE_LIMIT = 2000;3435export const standing = (proposal: Proposal) =>36 proposal.state === "open" && proposal.draft !== undefined37 ? proposal.draft._tag38 : proposal.state;3940const draftingNow = DraftState.isAnyOf(["Drafting"]);4142const failedNow = DraftState.isAnyOf(["Failed"]);4344export const isDrafting = (proposal: Proposal) =>45 proposal.draft !== undefined && draftingNow(proposal.draft);4647const refusalKinds = groups.flatMap(({ members }) => [...members]);4849/**50 * A draft keeps only the tag, so a refusal that needs fields of its own cannot51 * be drawn whole.52 */53export const refusalOfTag = (tag: string): Option.Option<Refusal> =>54 Arr.findFirst(refusalKinds, (kind) => kind.identifier === tag).pipe(55 Option.flatMap((kind): Option.Option<Refusal> =>56 // SAFETY: `makeOption` checks its input at run time, so a refusal whose fields all have defaults is made and one that needs a field answers None.57 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a loop over the union's members cannot name each member's input; see SAFETY.58 kind.makeOption({} as never)59 )60 );6162const isAskFile = ({ path }: ConfigFile) =>63 path.startsWith(`${Brand.configDir}/`) || path.endsWith(".ask.ts");6465const filesInOrder = (files: readonly ConfigFile[]) => {66 const askFile = files.find(isAskFile);67 const rest = files.filter((file) => file !== askFile);68 const checks = rest.filter(({ path }) => isTestPath(path));69 const others = rest.filter(({ path }) => !isTestPath(path));7071 return { askFile, checks, others };72};7374const kindIn = (source: string) =>75 /\bkinds\.(?<kind>[A-Za-z]+)/u.exec(source)?.groups?.kind;7677const Step = ({78 children,79 id,80 title,81}: {82 readonly children: ReactNode;83 readonly id: string;84 readonly title: string;85}) => (86 <section aria-labelledby={id} className="flex min-w-0 flex-col gap-3">87 <h2 className="text-title" id={id}>88 {title}89 </h2>90 {children}91 </section>92);9394const Row = ({95 children,96 label,97}: {98 readonly children: ReactNode;99 readonly label: string;100}) => (101 <div className="contents">102 <dt className="text-label text-muted-foreground pt-0.5">{label}</dt>103 <dd className="text-ui min-w-0 [overflow-wrap:anywhere]">{children}</dd>104 </div>105);106107const AskFileStep = ({108 file,109 proposal,110}: {111 readonly file: ConfigFile | undefined;112 readonly proposal: Proposal;113}) => {114 const kind = file === undefined ? undefined : kindIn(file.content);115116 return (117 <Step id={`${proposal.id}-ask-file`} title="The ask file">118 <dl className="tablet:grid-cols-[7rem_1fr] grid grid-cols-1 gap-x-4 gap-y-1.5">119 <Row label="Want">{proposal.want}</Row>120 {proposal.territory === undefined ? null : (121 <Row label="Territory">122 <code className="text-mono font-mono">{proposal.territory}</code>123 </Row>124 )}125 {kind === undefined ? null : (126 <Row label="Kind">127 <code className="text-mono font-mono">{kind}</code>128 </Row>129 )}130 </dl>131 {file === undefined ? null : (132 <details className="group">133 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 [&::-webkit-details-marker]:hidden">134 Its source, <code className="text-mono font-mono">{file.path}</code>135 <ChevronDown136 aria-hidden="true"137 className="size-3.5 transition-transform duration-150 group-open:rotate-180"138 strokeWidth={1.75}139 />140 </summary>141 <div className="mt-2">142 <DraftedCode content={file.content} path={file.path} />143 </div>144 </details>145 )}146 </Step>147 );148};149150const RedFirst = ({ draft }: { readonly draft: DraftState }) =>151 DraftState.match(draft, {152 Drafting: () => null,153 Failed: () => null,154 Ready: ({ attempts, model, red }) => (155 <Step id="red-first" title="Red first">156 <p className="text-ui">157 The check ran on main and fails twice the same way in lane {red.lane}:{" "}158 <span className="sr-only">{red.signature}</span>159 </p>160 <samp161 aria-hidden="true"162 className="border-rule bg-surface text-mono leading-terminal block border px-3 py-2 font-mono [overflow-wrap:anywhere] whitespace-pre-wrap"163 >164 {red.signature}165 </samp>166 <p className="text-label text-muted-foreground font-normal">167 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}168 </p>169 </Step>170 ),171 });172173const FailedRound = ({ draft }: { readonly draft: DraftState }) =>174 DraftState.match(draft, {175 Drafting: () => null,176 Failed: ({ attempts, model, refusal, round }) =>177 Option.match(refusalOfTag(refusal), {178 onNone: () => (179 <p className="text-want flex items-start gap-2" data-draft="Failed">180 <X181 aria-hidden="true"182 className="mt-1 size-4 shrink-0"183 strokeWidth={1.75}184 />185 <span>186 <strong className="font-semibold">The draft failed:</strong>{" "}187 <code className="text-mono font-mono">{refusal}</code>, in round{" "}188 {round}, after {attempts} of {DRAFT_ATTEMPTS} attempts by {model}.189 </span>190 </p>191 ),192 onSome: (made) => (193 <div className="flex flex-col gap-2" data-draft="Failed">194 <p className="text-ui text-muted-foreground">195 Round {round} failed after {attempts} of {DRAFT_ATTEMPTS} attempts196 by {model}, with:197 </p>198 <RefusalView refusals={[made]} />199 </div>200 ),201 }),202 Ready: () => null,203 });204205const Redraft = ({206 again,207 busy,208 onRedraft,209}: {210 readonly again: boolean;211 readonly busy: boolean;212 readonly onRedraft: (note: string | undefined) => void;213}) => {214 const [note, setNote] = useState("");215 const noteId = useId();216217 return (218 <section219 aria-label="Draft again"220 className="border-rule flex flex-col gap-3 border-t pt-4"221 >222 <details className="group">223 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 py-1 select-none [&::-webkit-details-marker]:hidden">224 Add a note for the agent225 <ChevronDown226 aria-hidden="true"227 className="size-3.5 transition-transform duration-150 group-open:rotate-180"228 strokeWidth={1.75}229 />230 </summary>231 <label232 className="text-label text-muted-foreground mt-2 block"233 htmlFor={noteId}234 >235 What the next draft should do differently236 </label>237 <Textarea238 className="tablet:text-ui mt-1 text-base"239 id={noteId}240 maxLength={NOTE_LIMIT}241 onChange={(event) => {242 setNote(event.target.value);243 }}244 value={note}245 />246 </details>247 <Button248 className="tablet:h-9 tablet:w-fit h-11 w-full px-4"249 disabled={busy}250 onClick={() => {251 const written = note.trim();252253 onRedraft(written.length === 0 ? undefined : written);254 }}255 type="button"256 variant="outline"257 >258 {again ? "Draft again" : "Let the platform's agent draft it"}259 </Button>260 </section>261 );262};263264const DecisionLink = ({265 decision,266 project,267}: {268 readonly decision: DecisionId;269 readonly project: ProjectName;270}) => (271 <AppLink272 className="text-ui decoration-rule flex w-fit items-center gap-2 font-medium underline hover:decoration-current"273 data-decision={decision}274 to={decisionPath(project, decision)}275 >276 <Scale aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />277 Decide it: {decision}278 </AppLink>279);280281const roundLine = (draft: DraftState) =>282 DraftState.match(draft, {283 Drafting: ({ round }) => `Round ${round}, drafting now`,284 Failed: ({ attempts, round }) =>285 `Round ${round} failed after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,286 Ready: ({ attempts, round }) =>287 `Round ${round} ready after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,288 });289290const ProposalFacts = ({291 decision,292 now,293 project,294 proposal,295}: {296 readonly decision: Option.Option<DecisionId>;297 readonly now: DateTime.Utc;298 readonly project: ProjectName;299 readonly proposal: Proposal;300}) => (301 <>302 <FactBlock label="Proposal">303 <dl className="text-ui grid grid-cols-[6rem_1fr] gap-x-3 gap-y-1.5">304 <dt className="text-label text-muted-foreground pt-0.5">Proposed by</dt>305 <dd>306 <HandleLink handle={proposal.proposer} />{" "}307 <span className="text-muted-foreground">308 <When at={proposal.openedAt} now={now} />309 </span>310 </dd>311 <dt className="text-label text-muted-foreground pt-0.5">Expires</dt>312 <dd>313 <When at={proposal.expiresAt} now={now} />314 <span className="text-muted-foreground">315 {" "}316 unless a maintainer opens it317 </span>318 </dd>319 <dt className="text-label text-muted-foreground pt-0.5">State</dt>320 <dd321 className="first-letter:uppercase"322 data-standing={standing(proposal)}323 >324 {proposal.state}325 </dd>326 </dl>327 </FactBlock>328 {Option.isSome(decision) ? (329 <FactBlock label="Decision">330 <DecisionLink decision={decision.value} project={project} />331 </FactBlock>332 ) : null}333 {proposal.draft === undefined ? null : (334 <FactBlock label="Drafting">335 <p className="text-ui">{roundLine(proposal.draft)}</p>336 </FactBlock>337 )}338 </>339);340341const ProposalStatus = ({ proposal }: { readonly proposal: Proposal }) => {342 const { draft } = proposal;343 const drafting = draft !== undefined && draftingNow(draft);344345 return (346 <div347 className="flex flex-col gap-3"348 data-draft={draft?._tag}349 data-proposal={proposal.id}350 data-standing={standing(proposal)}351 >352 {draft !== undefined && failedNow(draft) && proposal.state === "open" ? (353 <FailedRound draft={draft} />354 ) : (355 <StatusLine subject={{ kind: "proposal", proposal }} />356 )}357 {drafting ? (358 <p className="text-ui text-muted-foreground max-w-(--measure)">359 The platform's agent is writing the ask and a check, then running360 the check on main, where it must fail twice the same way. This takes a361 few minutes; the page follows it.362 </p>363 ) : null}364 {drafting && draft.note !== undefined ? (365 <p366 className="text-ui [overflow-wrap:anywhere] whitespace-pre-line"367 data-note=""368 >369 <span className="text-label text-muted-foreground">Note:</span>{" "}370 {draft.note}371 </p>372 ) : null}373 </div>374 );375};376377const DraftGuide = ({378 files,379 proposal,380}: {381 readonly files: readonly ConfigFile[];382 readonly proposal: Proposal;383}) => {384 const { askFile, checks, others } = filesInOrder(files);385 const kept = proposal.draft !== undefined && failedNow(proposal.draft);386387 if (files.length === 0) {388 return proposal.draft === undefined ? (389 <p className="text-body max-w-(--measure)">390 A want alone: no ask file or check yet. A maintainer who accepts it391 writes the change it asks for.392 </p>393 ) : null;394 }395396 return (397 <>398 {kept ? (399 <p className="text-ui text-muted-foreground" data-kept="">400 An earlier round's ready draft, which a maintainer can still401 accept: it runs red first again on main before the ask opens.402 </p>403 ) : null}404 <AskFileStep file={askFile} proposal={proposal} />405 {checks.length === 0 ? null : (406 <Step id={`${proposal.id}-check`} title="The check">407 {[...checks, ...others].map(({ content, path }) => (408 <DraftedCode content={content} key={path} path={path} />409 ))}410 </Step>411 )}412 {proposal.draft === undefined ? null : (413 <RedFirst draft={proposal.draft} />414 )}415 </>416 );417};418419export const ProposalView = ({420 busy = false,421 children,422 decision,423 files,424 mayRedraft,425 now = DateTime.nowUnsafe(),426 onRedraft = constVoid,427 project,428 proposal,429}: {430 readonly project: ProjectName;431 readonly proposal: Proposal;432 readonly files: readonly ConfigFile[];433 readonly decision: Option.Option<DecisionId>;434 readonly mayRedraft: boolean;435 readonly onRedraft?: (note: string | undefined) => void;436 readonly busy?: boolean;437 readonly children?: ReactNode;438 readonly now?: DateTime.Utc;439}): ReactNode => {440 const open = proposal.state === "open";441442 return (443 <Workspace444 crumbs={[445 { label: project, to: `/${project}` },446 { label: "Proposals" },447 { label: proposal.id, mono: true },448 ]}449 facts={450 <ProposalFacts451 decision={decision}452 now={now}453 project={project}454 proposal={proposal}455 />456 }457 factsHeading="This proposal"458 meta={459 <>460 proposed by <HandleLink handle={proposal.proposer} /> ·{" "}461 <code className="text-mono font-mono">{proposal.id}</code>462 </>463 }464 state={<StatusLine compact subject={{ kind: "proposal", proposal }} />}465 status={<ProposalStatus proposal={proposal} />}466 said467 title={proposal.want}468 >469 {Option.isSome(decision) && open ? (470 <DecisionLink decision={decision.value} project={project} />471 ) : null}472 <DraftGuide files={files} proposal={proposal} />473 {children}474 {mayRedraft && open && !isDrafting(proposal) ? (475 <Redraft476 again={proposal.draft !== undefined}477 busy={busy}478 onRedraft={onRedraft}479 />480 ) : null}481 </Workspace>482 );483};