Skip to content
Myr

Merge branch 'build/911-web-propose-and-proposal'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents a0c8f4f, 91bdc90 · Browse files · 15 files+1997 added−77 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+1997 added−77 removed

  • tests:+692 added−1 removed
  • other:+1305 added−76 removed

15 files+1997 added−77 removed

added:apps/web/src/client/proposal.ts+71 added
added:apps/web/src/client/propose.ts+72 added
modified:apps/web/src/features/decision/decision-card.tsx+169 added-51 removed
3 unmodified lines
4 * and when, and one button per choice its subject allows. A note is5 * optional. A `Finish` decision links to the answer's diff; no other6 * decision shows one, and the card never shows the diff itself.7 *8 * An `OpenProposal` shows the files the proposal would add (the ask file and9 * its check) as code under their paths, links the proposal's page, and holds10 * Accept while the platform's agent is drafting the proposal again: the11 * draft state is passed in, or read from `showProposal` when it is not.12 *13 * The subject's words follow GLOSSARY.md (ask, answer, landing, finish,14 * vouch). The default's word is the decision's `default` field as the15 * platform set it: the web keeps no table of defaults by subject.16 */17import type { Decide } from "@repo/protocol/contracts";18import type { Evidence as Fact } from "@repo/protocol/domain/common";19import { DecisionSubject } from "@repo/protocol/domain/decision";20import type { Choice, Decision } from "@repo/protocol/domain/decision";21import { DraftState } from "@repo/protocol/domain/proposal";22import type { ProjectName, ProposalId } from "@repo/protocol/ids";23import { DateTime, Option } from "effect";16import { FileDiff, Hourglass, ShieldCheck } from "lucide-react";24import { FileDiff, FileText, Hourglass, ShieldCheck } from "lucide-react";25import { useId, useState } from "react";26import type { ReactNode } from "react";2728import { Button } from "../../components/ui/button.tsx";29import { Spinner } from "../../components/ui/spinner.tsx";30import { Textarea } from "../../components/ui/textarea.tsx";31import {32 changedFiles,33 isFinishDecision,34 PATCH_LABEL,35 patchOf,36} from "../finish/patch.ts";37import { DraftedCode } from "../proposal/client-file.tsx";38import { useLiveDraft } from "../proposal/live-draft.ts";39import { When } from "../shared/time.tsx";4041/** What a decider sends when they choose: the `decide` contract's payload, from its one schema. */42export type DecideInput = typeof Decide.payloadSchema.Type;
71 unmodified lines
114 decline: "Decline",115 revert: "Revert",116} as const satisfies Record<Choice, string>;117118/** Whether a decision opens a proposed ask. */119const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);120121/** Whether a draft is still being written. */122const isDraftingNow = DraftState.isAnyOf(["Drafting"]);123124/**125 * Whether an evidence line holds a file: its label is a path (one word with126 * a slash or a dot, as the ask file under the config folder, or a check127 * at the root, `offset.test.ts`), where every other label is words.128 */129const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);130131/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */132const filesOf = (decision: Decision): readonly Fact[] =>133 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];134135const Facts = ({ facts }: { readonly facts: readonly Fact[] }) => (136 <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">137 {facts.map(({ href, label, value }) => (138 <div className="contents" key={`${label}:${value}`}>139 <dt className={`${LABEL} pt-0.5`}>{label}</dt>140 <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">141 {href === undefined ? (142 value143 ) : (144 <a145 className="decoration-rule underline hover:decoration-current"146 href={href}147 >148 {value}149 </a>150 )}151 </dd>152 </div>153 ))}154 </dl>155);156157const Evidence = ({ decision }: { readonly decision: Decision }) => {108 // The diff is the finish page's; here it is only counted.109 const facts = decision.evidence.filter(({ label }) => label !== PATCH_LABEL);158 // The diff is the finish page's; here it is only counted. A proposal's159 // files are drawn as code below the facts.160 const files = filesOf(decision);161111 if (facts.length === 0) {112 return null;113 }162 const facts = decision.evidence.filter(163 (fact) => fact.label !== PATCH_LABEL && !files.includes(fact)164 );165166 return (116 <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">117 {facts.map(({ href, label, value }) => (118 <div className="contents" key={`${label}:${value}`}>119 <dt className={`${LABEL} pt-0.5`}>{label}</dt>120 <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">121 {href === undefined ? (122 value123 ) : (124 <a125 className="decoration-rule underline hover:decoration-current"126 href={href}127 >128 {value}129 </a>130 )}131 </dd>132 </div>167 <>168 {facts.length === 0 ? null : <Facts facts={facts} />}169 {files.map(({ label, value }) => (170 <DraftedCode content={value} heading="h4" key={label} path={label} />171 ))}134 </dl>172 </>173 );174};175176/** The way from a `Finish` decision on Today to its answer's diff. */
17 unmodified lines
194 </a>195 );196};197198/** The way from an `OpenProposal` decision to the proposal's page: its draft and files. */199const ProposalLink = ({200 project,201 proposal,202}: {203 readonly project: ProjectName;204 readonly proposal: ProposalId;205}) => (206 <a207 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"208 href={`/${project}/proposals/${proposal}`}209 >210 <FileText aria-hidden="true" className="size-4 shrink-0" />211 Read the proposal212 </a>213);214215interface ChoicesProps {216 readonly busy: boolean;217 readonly choose: (choice: Choice) => void;218 readonly decision: Decision;219 readonly subject: string;220}221222/** One button per choice; Accept waits while the proposal is drafting. */223const Choices = ({224 busy,225 choose,226 decision,227 drafting,228 subject,229}: ChoicesProps & { readonly drafting: boolean }) => (230 <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">231 <legend className="sr-only">Your choice: {subject}</legend>232 {allowedChoices(decision.subject).map((choice) => {233 const isDefault = choice === decision.default;234 const held = drafting && choice === "accept";235236 return (237 <Button238 className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"239 data-choice={choice}240 disabled={busy || held}241 key={choice}242 onClick={() => {243 choose(choice);244 }}245 type="button"246 variant={isDefault ? "outline" : "default"}247 >248 {held ? (249 <>250 <Spinner />251 Drafting…252 </>253 ) : (254 words[choice]255 )}256 {isDefault ? (257 <span className="text-muted-foreground font-normal">default</span>258 ) : null}259 </Button>260 );261 })}262 </fieldset>263);264265/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */266const ProposalChoices = ({267 proposal,268 ...props269}: ChoicesProps & { readonly proposal: ProposalId }) => {270 const draft = useLiveDraft(props.decision.project, proposal);271272 return <Choices {...props} drafting={Option.exists(draft, isDraftingNow)} />;273};274275export const DecisionCard = ({276 busy = false,277 children,278 decision,279 draft,280 now,281 onDecide,282 soon = false,283 standalone = false,
8 unmodified lines
292 /** Whether it is shown on its own page, so its title needs no link there. */293 readonly standalone?: boolean;294 /** What its own page shows before the choices: for a finish, the diff. */295 readonly children?: ReactNode;296 /**297 * For an `OpenProposal`, where the proposal's draft stands: Accept waits298 * while it is drafting. Read from `showProposal` when not passed.299 */300 readonly draft?: DraftState | undefined;301}) => {302 const [note, setNote] = useState("");303 const noteId = useId();304 const subject = describeSubject(decision.subject);
66 unmodified lines
371 {isFinishDecision(decision) && !standalone ? (372 <FinishLink decision={decision} />373 ) : null}374375 {opensAsk(decision.subject) ? (376 <ProposalLink377 project={decision.project}378 proposal={decision.subject.proposal}379 />380 ) : null}381382 {children === undefined ? null : (383 <div className="border-rule mt-3 flex flex-col gap-8 border-t pt-6">384 {children}385 </div>
15 unmodified lines
401 value={note}402 />403 </details>404277 <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">278 <legend className="sr-only">Your choice: {subject}</legend>279 {allowedChoices(decision.subject).map((choice) => {280 const isDefault = choice === decision.default;281282 return (283 <Button284 className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"285 data-choice={choice}286 disabled={busy}287 key={choice}288 onClick={() => {289 choose(choice);290 }}291 type="button"292 variant={isDefault ? "outline" : "default"}293 >294 {words[choice]}295 {isDefault ? (296 <span className="text-muted-foreground font-normal">297 default298 </span>299 ) : null}300 </Button>301 );302 })}303 </fieldset>405 {opensAsk(decision.subject) && draft === undefined ? (406 <ProposalChoices407 busy={busy}408 choose={choose}409 decision={decision}410 proposal={decision.subject.proposal}411 subject={subject}412 />413 ) : (414 <Choices415 busy={busy}416 choose={choose}417 decision={decision}418 drafting={draft !== undefined && isDraftingNow(draft)}419 subject={subject}420 />421 )}422 </article>423 );424};
modified:apps/web/src/features/project/project-page.tsx+10 added-4 removed
1/**2 * A project's page: its posture, how to take part, its open asks, and its3 * recent landings with their credit trailers. Props in, markup out: the4 * route reads the listing, the asks and the landings (`src/client/project.ts`)5 * and the platform URL (the root loader), and hands them here.5 * and the platform URL (the root loader), and hands them here. "Propose an6 * ask" shows for signed-in members only, once the browser knows who that is7 * (`features/propose/propose-link.tsx`).8 */9import { Brand } from "@repo/brand";10import type { AskListing } from "@repo/protocol/domain/ask";11import type { FileView, TreeListing } from "@repo/protocol/domain/code";
2 unmodified lines
14import type { ProjectName } from "@repo/protocol/ids";15import type { DateTime } from "effect";1617import { EntriesTable, ReadmeSection } from "../code/tree-view.tsx";18import { SignedInProposeLink } from "../propose/propose-link.tsx";19import { CommandLine } from "../shared/command.tsx";20import { EmptyState } from "../shared/empty.tsx";21import { PageShell } from "../shared/layout.tsx";22import { PostureBadge } from "../shared/posture.tsx";
161 unmodified lines
184 <section185 aria-labelledby="open-asks"186 className="flex min-w-0 flex-col gap-3 lg:col-start-1"187 >188 <div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1">185 <h2 className={SECTION} id="open-asks">186 Open asks187 </h2>189 <h2 className={SECTION} id="open-asks">190 Open asks191 </h2>192 <SignedInProposeLink project={project} />193 </div>194 {asks.length === 0 ? (195 <EmptyState196 command={`${Brand.cli} ask open <ask> --files <files>`}197 title="No open asks. A decider opens one from an ask file."
47 unmodified lines
added:apps/web/src/features/proposal/client-file.tsx+53 added
added:apps/web/src/features/proposal/drafted-file.tsx+41 added
added:apps/web/src/features/proposal/live-draft.ts+23 added
added:apps/web/src/features/proposal/proposal-view.tsx+288 added
1/**2 * One proposal, as its proposer and its deciders follow it: the want and3 * who proposed it, where the platform's draft of its ask stands (drafting,4 * ready after its check ran red first, or failed with the last refusal),5 * the drafted files, and the way to the decision that would open the ask.6 * "Draft again" (with an optional note for the agent) is the proposer's or7 * a decider's while the proposal is open and not drafting. Props in, markup8 * out: the route reads `showProposal`, who is signed in and the decider's9 * Today, and sends `draftAsk`.10 *11 * Nothing here edits the drafted files: a member proposes again, or a12 * decider sends the draft back with a note.13 */14import type { ConfigFile } from "@repo/protocol/domain/common";15import { DraftState } from "@repo/protocol/domain/proposal";16import type { Proposal } from "@repo/protocol/domain/proposal";17import type { DecisionId, ProjectName } from "@repo/protocol/ids";18import { Option } from "effect";19import { constVoid } from "effect/Function";20import { CircleCheck, OctagonX, Scale } from "lucide-react";21import { useId, useState } from "react";22import type { ReactNode } from "react";2324import { Badge } from "../../components/ui/badge.tsx";25import { Button } from "../../components/ui/button.tsx";26import { Spinner } from "../../components/ui/spinner.tsx";27import { Textarea } from "../../components/ui/textarea.tsx";28import { HandleLink } from "../shared/handle.tsx";29import { DraftedCode } from "./client-file.tsx";3031/**32 * How many attempts a draft round makes before it fails: the platform's33 * `DRAFT_ROUNDS` (`@repo/project/draft-runs`), which the web's production34 * code does not import; `test/proposal.test.tsx` holds the two equal.35 */36export const DRAFT_ATTEMPTS = 3;3738/** The longest note `draftAsk` takes. */39const NOTE_LIMIT = 2000;4041/** Where a proposal stands in one word: its draft's while it is open, else its own. */42export const standing = (proposal: Proposal) =>43 proposal.state === "open" && proposal.draft !== undefined44 ? proposal.draft._tag45 : proposal.state;4647const draftingNow = DraftState.isAnyOf(["Drafting"]);4849/** Whether the platform's agent is drafting the proposal's ask right now. */50export const isDrafting = (proposal: Proposal) =>51 proposal.draft !== undefined && draftingNow(proposal.draft);5253const LABEL = "text-muted-foreground text-xs font-medium";5455/** The badge each standing wears: an ending that opened nothing reads as refused. */56const badgeVariant = {57 Drafting: "outline",58 Failed: "destructive",59 Ready: "secondary",60 accepted: "secondary",61 declined: "destructive",62 expired: "destructive",63 open: "secondary",64} as const satisfies Record<ReturnType<typeof standing>, string>;6566const StateBadge = ({ proposal }: { readonly proposal: Proposal }) => {67 const word = standing(proposal);6869 return (70 <Badge data-standing={word} variant={badgeVariant[word]}>71 {word === "Drafting" ? <Spinner className="size-3" /> : null}72 {word}73 </Badge>74 );75};7677/** What the draft says: in progress, ready with its red-first run, or failed. */78const DraftFacts = ({ draft }: { readonly draft: DraftState }) =>79 DraftState.match(draft, {80 Drafting: ({ round }) => (81 <p className="flex items-start gap-2 text-sm" data-draft="Drafting">82 <Spinner className="text-checking mt-0.5 shrink-0" />83 <span>84 Drafting (round {round}): the platform&apos;s agent is writing the ask85 and a check, then running the check on main, where it must fail twice86 the same way. This takes a few minutes; the page follows it.87 </span>88 </p>89 ),90 Failed: ({ attempts, model, refusal, round }) => (91 <div className="flex flex-col gap-1 text-sm" data-draft="Failed">92 <p className="flex items-start gap-2">93 <OctagonX94 aria-hidden="true"95 className="text-refused mt-0.5 size-4 shrink-0"96 />97 <span>98 The draft failed (round {round}), after {attempts} of{" "}99 {DRAFT_ATTEMPTS} attempts by {model}. The last refusal:{" "}100 <b className="text-refused font-mono font-semibold">{refusal}</b>101 </span>102 </p>103 </div>104 ),105 Ready: ({ attempts, model, red }) => (106 <dl107 className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[minmax(8rem,auto)_1fr]"108 data-draft="Ready"109 >110 <dt className={`${LABEL} pt-0.5`}>Red first</dt>111 <dd className="mb-1.5 flex items-start gap-2 [overflow-wrap:anywhere] sm:mb-0">112 <CircleCheck113 aria-hidden="true"114 className="text-landed mt-0.5 size-4 shrink-0"115 />116 <span>117 fails twice the same way in lane {red.lane}: {red.signature}118 </span>119 </dd>120 <dt className={`${LABEL} pt-0.5`}>Drafted by</dt>121 <dd className="mb-1.5 [overflow-wrap:anywhere] sm:mb-0">122 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}123 </dd>124 </dl>125 ),126 });127128/** "Draft again", with a note the agent reads. */129const Redraft = ({130 again,131 busy,132 onRedraft,133}: {134 readonly again: boolean;135 readonly busy: boolean;136 readonly onRedraft: (note: string | undefined) => void;137}) => {138 const [note, setNote] = useState("");139 const noteId = useId();140141 return (142 <section143 aria-label="Draft again"144 className="border-rule flex flex-col gap-3 border-t pt-4"145 >146 <details className="text-sm">147 <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">148 Add a note for the agent149 </summary>150 <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>151 What the next draft should do differently152 </label>153 <Textarea154 className="mt-1 text-sm md:text-sm"155 id={noteId}156 maxLength={NOTE_LIMIT}157 onChange={(event) => {158 setNote(event.target.value);159 }}160 value={note}161 />162 </details>163 <Button164 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"165 disabled={busy}166 onClick={() => {167 const written = note.trim();168169 onRedraft(written.length === 0 ? undefined : written);170 }}171 type="button"172 variant="outline"173 >174 {again ? "Draft again" : "Let the platform's agent draft it"}175 </Button>176 </section>177 );178};179180/** The way to the open decision that would open the ask. */181const DecisionLink = ({182 decision,183 project,184}: {185 readonly decision: DecisionId;186 readonly project: ProjectName;187}) => (188 <a189 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"190 data-decision={decision}191 href={`/${project}/decisions/${decision}`}192 >193 <Scale aria-hidden="true" className="size-4 shrink-0" />194 Decide it: {decision}195 </a>196);197198export const ProposalView = ({199 busy = false,200 children,201 decision,202 files,203 mayRedraft,204 onRedraft = constVoid,205 project,206 proposal,207}: {208 readonly project: ProjectName;209 readonly proposal: Proposal;210 /** The files the proposal holds (the ask file and its check), as `showProposal` read them. */211 readonly files: readonly ConfigFile[];212 /** The open decision on the proposal, when the reader's Today holds it. */213 readonly decision: Option.Option<DecisionId>;214 /** Whether the reader is its proposer or one of the project's deciders. */215 readonly mayRedraft: boolean;216 readonly onRedraft?: (note: string | undefined) => void;217 /** Whether a "Draft again" is on its way: the button waits. */218 readonly busy?: boolean;219 /** What the last "Draft again" came back with, when it was refused. */220 readonly children?: ReactNode;221}): ReactNode => {222 const open = proposal.state === "open";223224 return (225 <article226 aria-labelledby={`${proposal.id}-want`}227 className="flex max-w-[90ch] min-w-0 flex-col gap-5"228 data-proposal={proposal.id}229 >230 <header className="flex flex-col gap-2">231 <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">232 <span className="font-mono">{project}</span>233 <span aria-hidden="true">·</span>234 <span className="font-mono">{proposal.id}</span>235 <StateBadge proposal={proposal} />236 </p>237 <h2238 className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"239 id={`${proposal.id}-want`}240 >241 {proposal.want}242 </h2>243 <p className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">244 <span>245 Proposed by <HandleLink handle={proposal.proposer} />246 </span>247 {proposal.territory === undefined ? null : (248 <span>249 in <code className="font-mono">{proposal.territory}</code>250 </span>251 )}252 </p>253 </header>254255 {proposal.draft === undefined ? null : (256 <DraftFacts draft={proposal.draft} />257 )}258259 {Option.isSome(decision) ? (260 <DecisionLink decision={decision.value} project={project} />261 ) : null}262263 {files.length === 0 ? null : (264 <section265 aria-labelledby={`${proposal.id}-files`}266 className="flex min-w-0 flex-col gap-4"267 >268 <h2 className="text-base font-semibold" id={`${proposal.id}-files`}>269 {proposal.draft === undefined ? "Proposed files" : "Drafted files"}270 </h2>271 {files.map(({ content, path }) => (272 <DraftedCode content={content} key={path} path={path} />273 ))}274 </section>275 )}276277 {children}278279 {mayRedraft && open && !isDrafting(proposal) ? (280 <Redraft281 again={proposal.draft !== undefined}282 busy={busy}283 onRedraft={onRedraft}284 />285 ) : null}286 </article>287 );288};
added:apps/web/src/features/propose/propose-link.tsx+35 added
added:apps/web/src/features/propose/propose-view.tsx+232 added
1/**2 * The propose form: a signed-in member writes a want, may name the3 * territory it belongs to (one of the project's top folders), and lets the4 * platform's agent draft the ask file and its failing check from it,5 * checked by default. A line from the why page (`?about&line&at`) starts the6 * want with where it points. Props in, markup out: the route reads who is7 * signed in and the project's paths, sends the payload, and goes to the8 * proposal once it is made.9 *10 * Only the want, the territory and the draft box: the files are the11 * agent's to write, or a person's through `propose --files` in the CLI.12 */13import { Brand } from "@repo/brand";14import type { ProposeAsk } from "@repo/protocol/contracts";15import type { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";16import { Option } from "effect";17import { LogIn } from "lucide-react";18import { useId, useState } from "react";19import type { ReactNode } from "react";2021import { Button } from "../../components/ui/button.tsx";22import { Checkbox } from "../../components/ui/checkbox.tsx";23import { Label } from "../../components/ui/label.tsx";24import { Spinner } from "../../components/ui/spinner.tsx";25import { Textarea } from "../../components/ui/textarea.tsx";26import { CommandLine } from "../shared/command.tsx";2728/** What `proposeAsk` takes, from its one schema. */29export type ProposePayload = typeof ProposeAsk.payloadSchema.Type;3031/** A line a why page points at: the file, the line and the commit it was read at. */32export interface About {33 readonly path: RepoPath;34 readonly line: number;35 readonly at: CommitSha;36}3738/**39 * The form's fields as `proposeAsk`'s payload: the want trimmed, the40 * territory when one is named, and `draft: true` only when the box is41 * checked (the contract takes no `draft: false`).42 */43export const proposalPayload = (form: {44 readonly project: ProjectName;45 readonly want: string;46 readonly territory?: RepoPath;47 readonly draft: boolean;48}): ProposePayload => {49 const want = form.want.trim();5051 const named =52 form.territory === undefined53 ? { project: form.project, want }54 : { project: form.project, territory: form.territory, want };5556 return form.draft ? { ...named, draft: true } : named;57};5859/** How a want about one line starts: `In \`src/format.ts\` line 12 at 4c2e6a8: `. */60export const wantAbout = ({ at, line, path }: About) =>61 `In \`${path}\` line ${line} at ${at.slice(0, 7)}: `;6263/**64 * The form's address for `project`, at the line a why page names when it65 * names one: where the project page links, and where sign-in comes back to.66 */67export const proposeFormPath = (68 project: ProjectName,69 about: Option.Option<About> = Option.none()70) =>71 Option.match(about, {72 onNone: () => `/${project}/proposals/new`,73 onSome: ({ at, line, path }) =>74 `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,75 });7677const LABEL = "text-muted-foreground text-xs font-medium";7879const SignInFirst = ({80 about,81 project,82}: {83 readonly about: Option.Option<About>;84 readonly project: ProjectName;85}) => (86 <section87 aria-label="Sign in to propose"88 className="border-rule flex flex-col gap-3 border-t pt-4"89 >90 <p className="flex items-start gap-2 text-sm">91 <LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />92 <span>93 Proposing an ask is for signed-in members.{" "}94 <a95 className="decoration-rule font-medium underline hover:decoration-current"96 href={`/auth/signin?${new URLSearchParams({ return: proposeFormPath(project, about) }).toString()}`}97 >98 Sign in99 </a>{" "}100 to propose one, or propose from your clone:101 </span>102 </p>103 <CommandLine command={`${Brand.cli} propose --draft "<want>"`} />104 </section>105);106107export const ProposeView = ({108 about,109 busy = false,110 children,111 modules,112 onPropose,113 project,114 signedIn,115}: {116 readonly project: ProjectName;117 readonly signedIn: boolean;118 readonly about: Option.Option<About>;119 /** The project's top folders, each a territory to choose. */120 readonly modules: readonly RepoPath[];121 /** Sends the payload; the route goes to the proposal once it is made. */122 readonly onPropose?: (payload: ProposePayload) => void;123 /** Whether a proposal is on its way: the button waits. */124 readonly busy?: boolean;125 /** What the last proposal came back with, when it was refused. */126 readonly children?: ReactNode;127}): ReactNode => {128 const id = useId();129130 const [want, setWant] = useState(() =>131 Option.match(about, { onNone: () => "", onSome: wantAbout })132 );133134 const [territory, setTerritory] = useState("");135 const [draft, setDraft] = useState(true);136137 if (!signedIn) {138 return <SignInFirst about={about} project={project} />;139 }140141 const chosen = modules.find((module) => module === territory);142 const written = want.trim().length > 0;143144 return (145 <form146 aria-label="Propose an ask"147 className="flex max-w-[70ch] flex-col gap-5"148 onSubmit={(event) => {149 event.preventDefault();150151 if (written) {152 onPropose?.(153 proposalPayload(154 chosen === undefined155 ? { draft, project, want }156 : { draft, project, territory: chosen, want }157 )158 );159 }160 }}161 >162 <div className="flex flex-col gap-1.5">163 <label className={LABEL} htmlFor={`${id}-want`}>164 What should the project do that it does not do now?165 </label>166 <Textarea167 className="min-h-32 text-sm md:text-sm"168 id={`${id}-want`}169 name="want"170 onChange={(event) => {171 setWant(event.target.value);172 }}173 required174 value={want}175 />176 </div>177178 <div className="flex flex-col gap-1.5">179 <label className={LABEL} htmlFor={`${id}-territory`}>180 Territory (optional)181 </label>182 <select183 className="border-input bg-background h-9 w-full max-w-xs rounded-none border px-2 text-sm"184 id={`${id}-territory`}185 name="territory"186 onChange={(event) => {187 setTerritory(event.target.value);188 }}189 value={territory}190 >191 <option value="">Let the agent choose</option>192 {modules.map((module) => (193 <option key={module} value={module}>194 {module}195 </option>196 ))}197 </select>198 </div>199200 <div className="flex items-start gap-2">201 <Checkbox202 checked={draft}203 className="mt-0.5"204 id={`${id}-draft`}205 name="draft"206 onCheckedChange={(checked) => {207 setDraft(checked);208 }}209 />210 <Label className="text-sm leading-snug" htmlFor={`${id}-draft`}>211 Let the platform&apos;s agent draft the ask212 </Label>213 </div>214 <p className="text-muted-foreground -mt-3 pl-6 text-xs">215 It writes the ask file and a check that fails on main, runs it red216 first, and puts the draft to a decider. Clear the box to propose the217 want alone.218 </p>219220 {children}221222 <Button223 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"224 disabled={busy || !written}225 type="submit"226 >227 {busy ? <Spinner /> : null}228 Propose229 </Button>230 </form>231 );232};
modified:apps/web/src/routes/$project/proposals/$proposal.tsx+186 added-11 removed
1import {2 RegistryProvider,3 useAtom,4 useAtomMount,5 useAtomValue,6} from "@effect/atom-react";7import { Client, ShowProposal } from "@repo/protocol/contracts";8import { DecisionSubject } from "@repo/protocol/domain/decision";9import type { Today } from "@repo/protocol/domain/decision";10import type { Proposal } from "@repo/protocol/domain/proposal";11import { ProjectName, ProposalId } from "@repo/protocol/ids";12import type { DecisionId, Handle } from "@repo/protocol/ids";1import { createFileRoute } from "@tanstack/react-router";13import { createFileRoute, notFound } from "@tanstack/react-router";14import { createServerFn } from "@tanstack/react-start";15import { env } from "cloudflare:workers";16import { Array, Effect, Option, Schema } from "effect";17import { AsyncResult, Atom } from "effect/reactivity";183import { pageTitle } from "../../../features/shared/layout.tsx";4import { NotBuilt } from "../../../features/shared/not-built.tsx";19import {20 draftAtom,21 projectTodayAtom,22 proposalAtom,23} from "../../../client/proposal.ts";24import { watchAtom } from "../../../client/watch.ts";25import { whoAtom } from "../../../features/auth/who.ts";26import { ProjectNav } from "../../../features/project/project-nav.tsx";27import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";28import { ProposalView } from "../../../features/proposal/proposal-view.tsx";29import { EmptyState } from "../../../features/shared/empty.tsx";30import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";31import { FailureView } from "../../../features/today/today-page.tsx";32import { serverClient } from "../../../server/client.ts";336// A proposal: its draft, the drafted files and the red-first evidence. A stub until 911 builds it.34// `/$project/proposals/$proposal`: one proposal and the platform's draft of35// its ask. The loader reads `showProposal` on the server, so the page36// arrives whole and an address naming no project or proposal is a 404; in37// the browser it reads again on each `ProposalDrafted` (the project's38// watch), so a draft moves from Drafting to Ready or Failed on screen.39// Who is signed in and the reader's Today (a decider's: it holds the open40// decision on the proposal) are read in the browser only.418const Page = () => {9 const { project, proposal } = Route.useParams();42type Shown = typeof ShowProposal.successSchema.Type;4344/** The proposal `name/id` names, encoded for the page; a not-found when there is none. */45export const readProposal = (name: string, id: string) =>46 Effect.gen(function* () {47 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(48 Effect.mapError(() => notFound())49 );5051 const proposal = yield* Schema.decodeEffect(ProposalId)(id).pipe(52 Effect.mapError(() => notFound())53 );5455 const client = yield* Client;5657 const shown = yield* client.showProposal({ project, proposal }).pipe(58 Effect.catchTags({59 UnknownProject: () => Effect.fail(notFound()),60 UnknownProposal: () => Effect.fail(notFound()),61 })62 );6364 return yield* Schema.encodeEffect(ShowProposal.successSchema)(shown);65 });6667const proposalPage = createServerFn({ method: "GET" })68 .validator(69 (params: { readonly project: string; readonly proposal: string }) => params70 )71 .handler(({ data }) =>72 Effect.runPromise(73 readProposal(data.project, data.proposal).pipe(74 Effect.provide(serverClient(env))75 )76 )77 );7879/** The open decision on `proposal` in the reader's Today, if it is there. */80const decisionOn = (81 today: AsyncResult.AsyncResult<Today, unknown>,82 proposal: Proposal83): Option.Option<DecisionId> =>84 Option.flatMap(AsyncResult.value(today), ({ decisions }) =>85 Array.findFirst(86 decisions,87 ({ decided, project, subject }) =>88 decided === undefined &&89 project === proposal.project &&90 DecisionSubject.guards.OpenProposal(subject) &&91 subject.proposal === proposal.id92 ).pipe(Option.map(({ id }) => id))93 );9495/** Whether `who` is the proposer, or the reader decides in the project (their Today answered). */96const mayRedraftAs = (97 who: AsyncResult.AsyncResult<Option.Option<Handle>, unknown>,98 today: AsyncResult.AsyncResult<Today, unknown>,99 proposal: Proposal100) =>101 AsyncResult.isSuccess(today) ||102 Option.exists(103 Option.flatten(AsyncResult.value(who)),104 (handle) => handle.toLowerCase() === proposal.proposer.toLowerCase()105 );106107/** The page over the proposal's atom, which starts from what the loader read. */108const FreshProposal = ({109 project,110 read,111}: {112 readonly project: ProjectName;113 readonly read: Shown;114}) => {115 // Live: a `ProposalDrafted` re-reads the proposal.116 useAtomMount(watchAtom(project));117118 const { files, proposal } = Option.getOrElse(119 AsyncResult.value(useAtomValue(proposalAtom(project)(read.proposal.id))),120 () => read121 );122123 const who = useAtomValue(whoAtom);124 const today = useAtomValue(projectTodayAtom(project));125 const [redrafted, redraft] = useAtom(draftAtom);126127 return (12 <NotBuilt13 issue="911"128 <ProposalView129 busy={redrafted.waiting}130 decision={decisionOn(today, proposal)}131 files={files}132 mayRedraft={mayRedraftAs(who, today, proposal)}133 onRedraft={(note) => {134 redraft(135 note === undefined136 ? { project, proposal: proposal.id }137 : { note, project, proposal: proposal.id }138 );139 }}140 project={project}15 title={`${project}: proposal ${proposal}`}16 />141 proposal={proposal}142 >143 {AsyncResult.isFailure(redrafted) ? (144 <div aria-live="polite">145 <FailureView cause={redrafted.cause} />146 </div>147 ) : null}148 </ProposalView>149 );150};151152const ProposalPage = () => {153 const read = Schema.decodeSync(ShowProposal.successSchema)(154 Route.useLoaderData()155 );156157 const { id, project } = read.proposal;158159 return (160 <PageShell title={`${project}: proposal ${id}`}>161 <ProjectNav project={project} />162 <RegistryProvider163 initialValues={[164 Atom.initialValue(165 proposalAtom(project)(id),166 AsyncResult.success(read)167 ),168 ]}169 key={`${project}/${id}`}170 >171 <FreshProposal project={project} read={read} />172 </RegistryProvider>173 </PageShell>174 );175};176177const Unknown = () => {178 const { project, proposal } = Route.useParams();179180 return Option.match(Schema.decodeUnknownOption(ProjectName)(project), {181 onNone: () => <UnknownProjectView name={project} />,182 onSome: (name) => (183 <PageShell title={`${name}: proposal ${proposal}`}>184 <ProjectNav project={name} />185 <EmptyState186 title={`${name} has no proposal ${proposal}, or no such project exists.`}187 />188 </PageShell>189 ),190 });191};192193export const Route = createFileRoute("/$project/proposals/$proposal")({21 component: Page,194 loader: ({ params }) => proposalPage({ data: params }),195 head: ({ params: { project, proposal } }) => ({196 meta: [{ title: pageTitle(`${project}: proposal ${proposal}`) }],197 }),198 component: ProposalPage,199 notFoundComponent: Unknown,200});
modified:apps/web/src/routes/$project/proposals/new.tsx+125 added-10 removed
1import { useAtom, useAtomValue } from "@effect/atom-react";2import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";1import { createFileRoute } from "@tanstack/react-router";3import { createFileRoute, useNavigate } from "@tanstack/react-router";4import { Option, Schema } from "effect";5import { AsyncResult } from "effect/reactivity";6import { useEffect, useState } from "react";73import { pageTitle } from "../../../features/shared/layout.tsx";4import { NotBuilt } from "../../../features/shared/not-built.tsx";8import {9 modulesAtom,10 proposalMade,11 proposeAtom,12} from "../../../client/propose.ts";13import { whoAtom } from "../../../features/auth/who.ts";14import { ProjectNav } from "../../../features/project/project-nav.tsx";15import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";16import { ProposeView } from "../../../features/propose/propose-view.tsx";17import type { About } from "../../../features/propose/propose-view.tsx";18import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";19import { FailureView } from "../../../features/today/today-page.tsx";206// The propose form: a want, for the platform's agent to draft into an ask. A stub until 911 builds it.21// `/$project/proposals/new`: the propose form. Who is signed in and the22// project's top folders are read in the browser (the server paints the23// page while it checks); a proposal made goes to its own page, a refusal24// shows under the form. `?about=<path>&line=<n>&at=<sha>` (the why page's25// "Propose an ask about this line") starts the want at that line.268const Page = () => {9 const { project } = Route.useParams();27const decodeProject = Schema.decodeUnknownOption(ProjectName);2829/** The line a why page points at, when the address names all three parts. */30const AboutParts = Schema.Struct({31 about: RepoPath,32 at: CommitSha,33 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),34});3536const decodeAbout = Schema.decodeUnknownOption(AboutParts);3738const decodeText = Schema.decodeUnknownOption(Schema.String);3940const decodeLine = Schema.decodeUnknownOption(Schema.Int);4142/** The address's line, as the form takes it. */43const aboutOf = (search: {44 readonly about?: string | undefined;45 readonly at?: string | undefined;46 readonly line?: number | undefined;47}): Option.Option<About> =>48 Option.map(decodeAbout(search), ({ about, at, line }) => ({49 at,50 line,51 path: about,52 }));5354const Checking = () => (55 <output className="text-muted-foreground block text-sm">56 Checking who is signed in57 </output>58);5960/** The form for `project`, once the browser knows who is signed in. */61const Propose = ({ project }: { readonly project: ProjectName }) => {62 const navigate = useNavigate();63 const search = Route.useSearch();64 const who = useAtomValue(whoAtom);6566 const modules = Option.getOrElse(67 AsyncResult.value(useAtomValue(modulesAtom(project))),68 () => []69 );7071 const [proposed, propose] = useAtom(proposeAtom);72 // Set once this form sends: a proposal the atom still holds from an73 // earlier visit never moves the page.74 const [sent, setSent] = useState(false);7576 const made = sent ? Option.getOrUndefined(proposalMade(proposed)) : undefined;7778 useEffect(() => {79 if (made !== undefined) {80 void navigate({81 params: { project, proposal: made },82 to: "/$project/proposals/$proposal",83 });84 }85 }, [made, navigate, project]);8687 if (!AsyncResult.isSuccess(who)) {88 return <Checking />;89 }9091 return (12 <NotBuilt13 issue="911"92 <ProposeView93 about={aboutOf(search)}94 busy={proposed.waiting}95 modules={modules}96 onPropose={(payload) => {97 setSent(true);98 propose(payload);99 }}100 project={project}15 title={`${project}: propose an ask`}16 />101 signedIn={Option.isSome(who.value)}102 >103 {AsyncResult.isFailure(proposed) ? (104 <div aria-live="polite">105 <FailureView cause={proposed.cause} />106 </div>107 ) : null}108 </ProposeView>109 );110};111112const Page = () => {113 const params = Route.useParams();114115 return Option.match(decodeProject(params.project), {116 onNone: () => <UnknownProjectView name={params.project} />,117 onSome: (project) => (118 <PageShell title={`${project}: propose an ask`}>119 <ProjectNav project={project} />120 <Propose project={project} />121 </PageShell>122 ),123 });124};125126export const Route = createFileRoute("/$project/proposals/new")({127 component: Page,128 validateSearch: (search: {129 readonly about?: unknown;130 readonly at?: unknown;131 readonly line?: unknown;132 }) => ({133 about: Option.getOrUndefined(decodeText(search.about)),134 at: Option.getOrUndefined(decodeText(search.at)),135 line: Option.getOrUndefined(decodeLine(search.line)),136 }),137 head: ({ params: { project } }) => ({138 meta: [{ title: pageTitle(`${project}: propose an ask`) }],139 }),140});
modified:apps/web/test/decision.test.tsx+114 added-1 removed
8 unmodified lines
9 * own client over in-process handlers that record each call (`RpcTest`); no10 * HTTP and no platform.11 */12import { describe, expect, it } from "@effect/vitest";13import { Brand } from "@repo/brand";14import { Contracts } from "@repo/protocol/contracts";15import { RefNameText } from "@repo/protocol/domain/common";16import { DecisionSubject } from "@repo/protocol/domain/decision";17import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";17import { CommitSha, DecisionId, Handle, ProjectName } from "@repo/protocol/ids";18import { DraftState } from "@repo/protocol/domain/proposal";19import {20 CommitSha,21 DecisionId,22 Handle,23 LaneName,24 ProjectName,25 ProposalId,26} from "@repo/protocol/ids";27import { DecisionClosed } from "@repo/protocol/refusal";28import type { UnknownDecision } from "@repo/protocol/refusal";29import { asTester, unanswered } from "@repo/protocol/testing";30import { DateTime, Effect, Exit, Layer, Ref } from "effect";
4 unmodified lines
3536import { decideAtom } from "../src/client/decide.ts";37import { keys } from "../src/client/keys.ts";38import { todayAtom } from "../src/client/today.ts";39import { DecisionCard } from "../src/features/decision/decision-card.tsx";40import { RefusalView } from "../src/features/shared/refusal.tsx";41import { TodayView } from "../src/features/today/today-page.tsx";42import { ContractsClient, webContracts } from "../src/surfaces.ts";43
235 unmodified lines
279 expect(markup).not.toContain('data-decision="dec-000002"');280 })281 );282});283284/** The Accept button's opening tag. */285const acceptOf = (markup: string) =>286 /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";287288describe("DecisionCard for an OpenProposal", () => {289 const askFile = `${Brand.configDir}/asks/x.ask.ts`;290291 const proposal = ProposalId.make("prop-000007");292293 const opening: Decision = {294 deciders: [okonkwo],295 default: "decline",296 evidence: [297 { label: "want", value: "formatISO keeps the offset it was given." },298 {299 label: askFile,300 value: 'export default ask({ id: "x", kind: kinds.fix });\n',301 },302 { label: "red first", value: "unit: expected '+02:00', got 'Z'" },303 ],304 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),305 id: DecisionId.make("dec-000003"),306 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),307 project: datekit,308 subject: DecisionSubject.cases.OpenProposal.make({ proposal }),309 };310311 const card = (draft: DraftState) =>312 markupOf(313 <DecisionCard314 decision={opening}315 draft={draft}316 now={now}317 onDecide={() => {}}318 />319 );320321 const drafting = DraftState.cases.Drafting.make({322 round: 2,323 startedAt: now,324 });325326 const ready = DraftState.cases.Ready.make({327 attempts: 1,328 model: "@cf/moonshotai/kimi-k2.7-code",329 red: { lane: LaneName.make("unit"), signature: "expected '+02:00'" },330 round: 1,331 });332333 it("shows a file's path as a heading and its content in a pre", () => {334 const markup = card(ready);335336 expect(markup).toMatch(new RegExp(`<h4[^>]*>${askFile}</h4>`, "u"));337 expect(markup).toMatch(338 /<pre[^>]*>export default ask\(\{ id: &quot;x&quot;, kind: kinds\.fix \}\);\n<\/pre>/u339 );340 expect(markup).not.toMatch(new RegExp(`<dt[^>]*>${askFile}</dt>`, "u"));341 expect(markup).toMatch(/<dt[^>]*>red first<\/dt>/u);342 });343344 it("holds Accept while the proposal's draft is drafting", () => {345 const markup = card(drafting);346347 expect(acceptOf(markup)).toContain('disabled=""');348 expect(markup).toContain("Drafting…");349 expect(350 /<button[^>]*data-choice="decline"[^>]*>/u.exec(markup)?.[0]351 ).not.toContain('disabled=""');352 });353354 it("offers Accept once the draft is ready", () => {355 const markup = card(ready);356357 expect(acceptOf(markup)).not.toContain('disabled=""');358 expect(markup).not.toContain("Drafting…");359 });360361 it("shows a check at the repo's root as code too", () => {362 const markup = markupOf(363 <DecisionCard364 decision={{365 ...opening,366 evidence: [367 ...opening.evidence,368 { label: "offset.test.ts", value: "test('keeps +02:00');\n" },369 ],370 }}371 draft={ready}372 now={now}373 onDecide={() => {}}374 />375 );376377 expect(markup).toMatch(/<h4[^>]*>offset\.test\.ts<\/h4>/u);378 expect(markup).not.toMatch(/<dt[^>]*>offset\.test\.ts<\/dt>/u);379 expect(markup).toMatch(/<dt[^>]*>want<\/dt>/u);380 });381382 it("links the proposal's page", () => {383 expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');384 });385});
added:apps/web/test/proposal.test.tsx+367 added
1/**2 * A proposal's page, rendered to HTML with `react-dom/server` from a3 * `showProposal` answer decoded with the protocol's own schema: the want and4 * its proposer, where the platform's draft stands, the drafted files, the5 * red-first evidence and who drafted it, the last refusal when it failed,6 * "Draft again" for the proposer or a decider while it is open and not7 * drafting, and the way to its decision when one is open.8 */9import { describe, expect, it } from "@effect/vitest";10import { Brand } from "@repo/brand";11import { DRAFT_ROUNDS } from "@repo/project/draft-runs";12import { Client, Contracts, ShowProposal } from "@repo/protocol/contracts";13import { ProjectEvent } from "@repo/protocol/domain/event";14import { DraftState } from "@repo/protocol/domain/proposal";15import { DecisionId, Handle, LaneName, ProjectName } from "@repo/protocol/ids";16import { UnknownProject, UnknownProposal } from "@repo/protocol/refusal";17import { asTester, unanswered } from "@repo/protocol/testing";18import { isNotFound } from "@tanstack/react-router";19import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";20import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";21import { RpcTest } from "effect/rpc";2223import { projectTodayAtom } from "../src/client/proposal.ts";24import { keysOf } from "../src/client/watch.ts";25import {26 DRAFT_ATTEMPTS,27 ProposalView,28} from "../src/features/proposal/proposal-view.tsx";29import { readProposal } from "../src/routes/$project/proposals/$proposal.tsx";30import { ContractsClient, webContracts } from "../src/surfaces.ts";31import { markupOf, plainText } from "./ask-fixtures.ts";3233const datekit = ProjectName.make("datekit");3435const decodeShown = Schema.decodeUnknownSync(ShowProposal.successSchema);3637const model = "@cf/moonshotai/kimi-k2.7-code";3839const askFile = `${Brand.configDir}/asks/format-keeps-offset.ask.ts`;4041const testFile = "src/format.offset.test.ts";4243type Shown = typeof ShowProposal.successSchema.Type;4445/** A proposal with no draft yet, as `showProposal` answers it, holding `files`. */46const shownWith = (files: readonly string[]): Shown =>47 decodeShown({48 files: files.map((path) => ({ content: `// ${path}\n`, path })),49 proposal: {50 expiresAt: "2026-10-21T09:00:00.000Z",51 files,52 id: "prop-000007",53 openedAt: "2026-10-07T09:00:00.000Z",54 project: "datekit",55 proposer: "lin-h",56 state: "open",57 want: "formatISO keeps the offset it was given.",58 },59 });6061/** `base` with its proposal's draft at `draft`. */62const withDraft = (base: Shown, draft: DraftState): Shown => ({63 ...base,64 proposal: { ...base.proposal, draft },65});6667const drafting = withDraft(68 shownWith([]),69 DraftState.cases.Drafting.make({70 round: 1,71 startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),72 })73);7475const ready = withDraft(76 shownWith([askFile, testFile]),77 DraftState.cases.Ready.make({78 attempts: 2,79 model,80 red: {81 lane: LaneName.make("unit"),82 signature: "expected '+02:00', got 'Z'",83 },84 round: 1,85 })86);8788const failed = withDraft(89 shownWith([]),90 DraftState.cases.Failed.make({91 attempts: 3,92 model,93 refusal: "NotRedFirst",94 round: 2,95 })96);9798const decision = DecisionId.make("dec-000003");99100const view = (101 { files, proposal }: Shown,102 linked: Option.Option<DecisionId> = Option.none()103) =>104 markupOf(105 <ProposalView106 decision={linked}107 files={files}108 mayRedraft109 project={datekit}110 proposal={proposal}111 />112 );113114const DRAFT_AGAIN = /<button[^>]*>[^<]*Draft again/u;115116describe(ProposalView, () => {117 it("shows the want and the proposer", () => {118 const text = plainText(view(drafting));119120 expect(text).toContain("formatISO keeps the offset it was given.");121 expect(text).toContain("lin-h");122 });123124 it("while drafting, shows the spinner and no Draft again", () => {125 const markup = view(drafting);126127 expect(markup).toContain('data-slot="spinner"');128 expect(plainText(markup)).toContain("Drafting");129 expect(markup).not.toMatch(DRAFT_AGAIN);130 });131132 it("once ready, shows both files, the red-first run, who drafted it and its decision", () => {133 const markup = view(ready, Option.some(decision));134 const text = plainText(markup);135136 expect(text).toContain(askFile);137 expect(text).toContain(testFile);138 expect(text).toContain(139 "fails twice the same way in lane unit: expected '+02:00', got 'Z'"140 );141 expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);142 expect(markup).toContain('href="/datekit/decisions/dec-000003"');143 });144145 it("once ready, shows no spinner", () => {146 expect(view(ready)).not.toContain('data-slot="spinner"');147 });148149 it("once failed, shows the last refusal's headline and Draft again", () => {150 const markup = view(failed);151152 expect(plainText(markup)).toContain("NotRedFirst");153 expect(markup).toMatch(DRAFT_AGAIN);154 });155156 it("offers Draft again only to the proposer or a decider", () => {157 const markup = markupOf(158 <ProposalView159 decision={Option.none()}160 files={[]}161 mayRedraft={false}162 project={datekit}163 proposal={failed.proposal}164 />165 );166167 expect(markup).not.toMatch(DRAFT_AGAIN);168 });169170 it("counts attempts out of the platform's own number of draft attempts", () => {171 expect(DRAFT_ATTEMPTS).toBe(DRAFT_ROUNDS);172 });173174 it("once accepted, offers no button", () => {175 const accepted: Shown = {176 ...ready,177 proposal: { ...ready.proposal, state: "accepted" },178 };179180 const markup = view(accepted);181182 expect(plainText(markup)).toContain("accepted");183 expect(markup).not.toContain("<button");184 });185});186187/** A platform that knows datekit's prop-000007 only, counting what it is asked. */188const platformHandlers = (189 asked: Ref.Ref<{ proposal: number; today: number }>190) =>191 Layer.mergeAll(192 unanswered,193 Contracts.toLayerHandler("showProposal", ({ project, proposal }) =>194 Effect.gen(function* () {195 yield* Ref.update(asked, (seen) => ({196 ...seen,197 proposal: seen.proposal + 1,198 }));199200 if (project !== datekit) {201 return yield* new UnknownProject({ project });202 }203204 if (proposal !== ready.proposal.id) {205 return yield* new UnknownProposal({ proposal });206 }207208 return ready;209 })210 ),211 Contracts.toLayerHandler("today", () =>212 Ref.update(asked, (seen) => ({ ...seen, today: seen.today + 1 })).pipe(213 Effect.as({214 budget: { finishes: 0, total: 5, used: 0 },215 decider: Handle.make("okonkwo"),216 decisions: [],217 expiringSoon: [],218 newcomers: [],219 overflow: 0,220 unattended: [],221 })222 )223 ),224 asTester225 );226227const counted = () => Ref.make({ proposal: 0, today: 0 });228229describe(readProposal, () => {230 it.effect("reads the proposal and its files, encoded for the page", () =>231 Effect.gen(function* () {232 const asked = yield* counted();233234 const read = yield* readProposal("datekit", "prop-000007").pipe(235 Effect.provide(236 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(237 Layer.provide(platformHandlers(asked))238 )239 )240 );241242 expect(decodeShown(read).files.map(({ path }) => path)).toStrictEqual([243 askFile,244 testFile,245 ]);246 })247 );248249 it.effect(250 "is a not-found for a proposal or a project the platform does not know",251 () =>252 Effect.gen(function* () {253 const asked = yield* counted();254255 const platform = Layer.effect(256 Client,257 RpcTest.makeClient(Contracts)258 ).pipe(Layer.provide(platformHandlers(asked)));259260 const noProposal = yield* Effect.flip(261 readProposal("datekit", "prop-000099").pipe(Effect.provide(platform))262 );263264 const noProject = yield* Effect.flip(265 readProposal("burrow", "prop-000007").pipe(Effect.provide(platform))266 );267268 expect(isNotFound(noProposal)).toBeTruthy();269 expect(isNotFound(noProject)).toBeTruthy();270 expect((yield* Ref.get(asked)).proposal).toBe(2);271 })272 );273274 it.effect(275 "is a not-found, asking nothing, for an address that names no proposal",276 () =>277 Effect.gen(function* () {278 const asked = yield* counted();279280 const refused = yield* Effect.flip(281 readProposal("datekit", "not a proposal").pipe(282 Effect.provide(283 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(284 Layer.provide(platformHandlers(asked))285 )286 )287 )288 );289290 expect(isNotFound(refused)).toBeTruthy();291 expect((yield* Ref.get(asked)).proposal).toBe(0);292 })293 );294});295296/** Lets the atoms' fibers run until `done` holds, or long enough that it would have. */297const runUntil = (done: Effect.Effect<boolean>) =>298 Effect.yieldNow.pipe(299 Effect.andThen(done),300 Effect.repeat({ times: 200, until: (held) => held })301 );302303describe("the proposal page's Today", () => {304 it.effect(305 "reads again when the proposal's draft settles, so its new decision is linked",306 () =>307 Effect.gen(function* () {308 const asked = yield* counted();309310 // One browser tab whose `ContractsClient` reaches the stub platform in process.311 const registry = yield* Effect.acquireRelease(312 Effect.sync(() =>313 AtomRegistry.make({314 initialValues: [315 Atom.initialValue(316 ContractsClient.runtime.layer,317 Layer.effect(318 ContractsClient,319 RpcTest.makeClient(webContracts, { flatten: true })320 ).pipe(321 Layer.provide(platformHandlers(asked)),322 Layer.provideMerge(Reactivity.layer)323 )324 ),325 ],326 })327 ),328 (made) =>329 Effect.sync(() => {330 made.dispose();331 })332 );333334 const today = projectTodayAtom(datekit);335336 registry.mount(today);337 yield* AtomRegistry.getResult(registry, today, {338 suspendOnWaiting: true,339 });340341 // What the watch does on `ProposalDrafted` (`keysOf` in `watch.ts`).342 yield* AtomRegistry.getResult(343 registry,344 ContractsClient.runtime.atom(345 Reactivity.invalidate(346 keysOf(347 datekit,348 ProjectEvent.cases.ProposalDrafted.make({349 at: DateTime.makeUnsafe("2026-10-07T09:05:00Z"),350 proposal: ready.proposal.id,351 ready: true,352 seq: 4,353 })354 )355 )356 ),357 { suspendOnWaiting: true }358 );359360 expect(361 yield* runUntil(362 Ref.get(asked).pipe(Effect.map(({ today: seen }) => seen > 1))363 )364 ).toBeTruthy();365 })366 );367});
added:apps/web/test/propose.test.tsx+211 added
1/**2 * The propose form, rendered to HTML with `react-dom/server`: a signed-in3 * member writes a want, may name a territory from the project's top4 * folders, and lets the platform's agent draft the ask (checked by5 * default). A line from the why page arrives as `?about&line&at` and starts6 * the want. Signed out, the page offers sign-in and no form. What the form7 * sends is the `proposeAsk` contract's own payload.8 */9import { describe, expect, it } from "@effect/vitest";10import { Brand } from "@repo/brand";11import { ProposeAsk } from "@repo/protocol/contracts";12import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";13import { CapReached } from "@repo/protocol/refusal";14import { Option, Schema } from "effect";15import { AsyncResult } from "effect/reactivity";1617import { proposalMade, topFolders } from "../src/client/propose.ts";18import {19 ProposeView,20 proposalPayload,21} from "../src/features/propose/propose-view.tsx";22import type { About } from "../src/features/propose/propose-view.tsx";23import { markupOf, plainText } from "./ask-fixtures.ts";2425const datekit = ProjectName.make("datekit");2627const at = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");2829const modules = [RepoPath.make("docs"), RepoPath.make("src")];3031const signedIn = (about: Option.Option<About> = Option.none()) =>32 markupOf(33 <ProposeView about={about} modules={modules} project={datekit} signedIn />34 );3536/** The want's textarea, as the server renders it: its opening tag and text. */37const textareaOf = (markup: string) =>38 /<textarea[^>]*>(?<text>[^<]*)<\/textarea>/u.exec(markup);3940describe(ProposeView, () => {41 it("signed in, offers a want and the draft box, checked", () => {42 const markup = signedIn();4344 expect(textareaOf(markup)?.[0]).toContain('name="want"');45 expect(markup).toMatch(46 /role="checkbox"[^>]*aria-checked="true"|aria-checked="true"[^>]*role="checkbox"/u47 );48 expect(plainText(markup)).toContain(49 "Let the platform's agent draft the ask"50 );51 expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Propose/u);52 });5354 it("offers each of the project's top folders as the territory", () => {55 const markup = signedIn();5657 expect(markup).toContain('name="territory"');58 expect(markup).toContain('<option value="src">src</option>');59 expect(markup).toContain('<option value="docs">docs</option>');60 });6162 it("starts the want at the line a why page names", () => {63 const markup = signedIn(64 Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })65 );6667 expect(textareaOf(markup)?.groups?.text).toBe(68 "In `src/format.ts` line 12 at 4c2e6a8: "69 );70 });7172 it("signed out, shows no form and links to sign in", () => {73 const markup = markupOf(74 <ProposeView75 about={Option.none()}76 modules={modules}77 project={datekit}78 signedIn={false}79 />80 );8182 expect(markup).not.toContain("<form");83 expect(markup).not.toContain("<textarea");84 expect(markup).toMatch(/<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in/u);85 });86});8788describe(proposalPayload, () => {89 const isPayload = Schema.is(ProposeAsk.payloadSchema);9091 it("asks for a draft when the box is checked", () => {92 const payload = proposalPayload({93 draft: true,94 project: datekit,95 want: " formatISO keeps the offset. ",96 });9798 expect(payload).toStrictEqual({99 draft: true,100 project: "datekit",101 want: "formatISO keeps the offset.",102 });103 expect(isPayload(payload)).toBeTruthy();104 });105106 it("carries no draft key when the box is clear, and the territory when named", () => {107 const payload = proposalPayload({108 draft: false,109 project: datekit,110 territory: RepoPath.make("src"),111 want: "formatISO keeps the offset.",112 });113114 expect(payload).toStrictEqual({115 project: "datekit",116 territory: "src",117 want: "formatISO keeps the offset.",118 });119 expect(Object.hasOwn(payload, "draft")).toBeFalsy();120 });121});122123describe(topFolders, () => {124 it("offers each top folder once, sorted, and no dot folder or root file", () => {125 expect(126 topFolders(127 [128 "src/format.ts",129 "README.md",130 `${Brand.configDir}/asks/x.ask.ts`,131 "test/format.test.ts",132 "src/parse/iso.ts",133 ".github/workflows/ci.yml",134 "docs/guide.md",135 ].map((path) => RepoPath.make(path))136 )137 ).toStrictEqual(["docs", "src", "test"]);138 });139});140141/** `proposeAsk`'s answer: the proposal `id`, made. */142const made = (id: string) =>143 Schema.decodeUnknownSync(ProposeAsk.successSchema)({144 proposal: {145 expiresAt: "2026-10-21T09:00:00.000Z",146 files: [],147 id,148 openedAt: "2026-10-07T09:00:00.000Z",149 project: "datekit",150 proposer: "lin-h",151 state: "open",152 want: "formatISO keeps the offset.",153 },154 });155156describe(proposalMade, () => {157 const earlier = AsyncResult.success(made("prop-000004"));158159 it("names the proposal a send made, once it answered", () => {160 expect(161 proposalMade(AsyncResult.success(made("prop-000005")))162 ).toStrictEqual(Option.some("prop-000005"));163 });164165 it("names none while a later send is on its way, or after it was refused", () => {166 expect(proposalMade(AsyncResult.waiting(earlier))).toStrictEqual(167 Option.none()168 );169 expect(170 proposalMade(171 AsyncResult.fail(new CapReached({ cap: 3 }), {172 previousSuccess: Option.some(earlier),173 })174 )175 ).toStrictEqual(Option.none());176 });177});178179describe("the sign-in link", () => {180 it("comes back to the form, at the line a why page named", () => {181 const markup = markupOf(182 <ProposeView183 about={Option.some({184 at,185 line: 12,186 path: RepoPath.make("src/format.ts"),187 })}188 modules={modules}189 project={datekit}190 signedIn={false}191 />192 );193194 const href = /href="(?<href>\/auth\/signin[^"]*)"/u195 .exec(markup)196 ?.groups?.href?.replaceAll("&amp;", "&");197198 const back = new URL(href ?? "/", "https://web.test").searchParams.get(199 "return"200 );201202 const there = new URL(back ?? "/", "https://web.test");203204 expect(there.pathname).toBe("/datekit/proposals/new");205 expect(Object.fromEntries(there.searchParams)).toStrictEqual({206 about: "src/format.ts",207 at,208 line: "12",209 });210 });211});