Skip to content
Myr

Add the web's propose form and proposal page, and show a proposal's files in its decision

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

- /$project/proposals/new: a want, an optional territory (the project's top folders from listPaths, dot folders excluded) and "Let the platform's agent draft the ask", checked by default; prefilled from ?about&line&at as "In `<path>` line <n> at <short sha>: ". Signed out it offers sign-in and the CLI line, no form. Propose sends proposeAsk (draft: true only when checked; the contract has no draft: false) and goes to the proposal page once it is made; a refusal shows through RefusalView under the form. - /$project/proposals/$proposal: the loader reads showProposal on the server (404 for an unknown project or proposal); in the browser the project's watch re-reads it on ProposalDrafted. Shows the want, the proposer, the state badge, the drafted files (client-only Pierre File over a <pre> fallback), the red-first line, "drafted by <model>, attempt n of 3", the last refusal's tag when Failed, a link to the open decision from the reader's Today, and "Draft again" (draftAsk, optional note) for the proposer or a decider while open and not drafting. - DecisionCard: for an OpenProposal, evidence whose label is a path is a heading over its code instead of a <dt>, the card links the proposal page, and Accept is disabled with "Drafting..." while the draft is Drafting (a passed `draft`, else read live from showProposal). - Project page: "Propose an ask" beside Open asks, for signed-in people. - Decision: the live reads (who is signed in, a proposal's draft) live in features/propose/propose-link.tsx and features/proposal/live-draft.ts, because the routes that render ProjectView and DecisionCard are outside this issue's territory and features/project must import no transport (test/project.test.tsx). - Decision: navigation after Propose waits on a local "sent" flag, so a proposal the atom still holds from an earlier visit never moves the page. - Tests: test/propose.test.tsx, test/proposal.test.tsx, four new cases in test/decision.test.tsx; each red by assertion over empty views first. - ASSUMPTION: DRAFT_ATTEMPTS = 3 mirrors @repo/project's DRAFT_ROUNDS, which the web cannot import. - ASSUMPTION: a decision's evidence label is a file when it is one word with a slash (909 labels files by path, everything else by words).

authored by oscabriel · committed by oscabriel · parent bbe1442 · Browse files · 15 files+1642 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+1642 added−77 removed

  • tests:+377 added−1 removed
  • other:+1265 added−76 removed

15 files+1642 added−77 removed

added:apps/web/src/client/proposal.ts+61 added
added:apps/web/src/client/propose.ts+60 added
modified:apps/web/src/features/decision/decision-card.tsx+168 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, as the ask file's), where every other label is words.127 */128export const isFileFact = ({ label }: Fact) => /^\S+\/\S+$/u.test(label);129130/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */131const filesOf = (decision: Decision): readonly Fact[] =>132 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];133134const Facts = ({ facts }: { readonly facts: readonly Fact[] }) => (135 <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">136 {facts.map(({ href, label, value }) => (137 <div className="contents" key={`${label}:${value}`}>138 <dt className={`${LABEL} pt-0.5`}>{label}</dt>139 <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">140 {href === undefined ? (141 value142 ) : (143 <a144 className="decoration-rule underline hover:decoration-current"145 href={href}146 >147 {value}148 </a>149 )}150 </dd>151 </div>152 ))}153 </dl>154);155156const 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);157 // The diff is the finish page's; here it is only counted. A proposal's158 // files are drawn as code below the facts.159 const files = filesOf(decision);160111 if (facts.length === 0) {112 return null;113 }161 const facts = decision.evidence.filter(162 (fact) => fact.label !== PATCH_LABEL && !files.includes(fact)163 );164165 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>166 <>167 {facts.length === 0 ? null : <Facts facts={facts} />}168 {files.map(({ label, value }) => (169 <DraftedCode content={value} heading="h4" key={label} path={label} />170 ))}134 </dl>171 </>172 );173};174175/** The way from a `Finish` decision on Today to its answer's diff. */
17 unmodified lines
193 </a>194 );195};196197/** The way from an `OpenProposal` decision to the proposal's page: its draft and files. */198const ProposalLink = ({199 project,200 proposal,201}: {202 readonly project: ProjectName;203 readonly proposal: ProposalId;204}) => (205 <a206 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"207 href={`/${project}/proposals/${proposal}`}208 >209 <FileText aria-hidden="true" className="size-4 shrink-0" />210 Read the proposal211 </a>212);213214interface ChoicesProps {215 readonly busy: boolean;216 readonly choose: (choice: Choice) => void;217 readonly decision: Decision;218 readonly subject: string;219}220221/** One button per choice; Accept waits while the proposal is drafting. */222const Choices = ({223 busy,224 choose,225 decision,226 drafting,227 subject,228}: ChoicesProps & { readonly drafting: boolean }) => (229 <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">230 <legend className="sr-only">Your choice: {subject}</legend>231 {allowedChoices(decision.subject).map((choice) => {232 const isDefault = choice === decision.default;233 const held = drafting && choice === "accept";234235 return (236 <Button237 className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"238 data-choice={choice}239 disabled={busy || held}240 key={choice}241 onClick={() => {242 choose(choice);243 }}244 type="button"245 variant={isDefault ? "outline" : "default"}246 >247 {held ? (248 <>249 <Spinner />250 Drafting…251 </>252 ) : (253 words[choice]254 )}255 {isDefault ? (256 <span className="text-muted-foreground font-normal">default</span>257 ) : null}258 </Button>259 );260 })}261 </fieldset>262);263264/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */265const ProposalChoices = ({266 proposal,267 ...props268}: ChoicesProps & { readonly proposal: ProposalId }) => {269 const draft = useLiveDraft(props.decision.project, proposal);270271 return <Choices {...props} drafting={Option.exists(draft, isDraftingNow)} />;272};273274export const DecisionCard = ({275 busy = false,276 children,277 decision,278 draft,279 now,280 onDecide,281 soon = false,282 standalone = false,
8 unmodified lines
291 /** Whether it is shown on its own page, so its title needs no link there. */292 readonly standalone?: boolean;293 /** What its own page shows before the choices: for a finish, the diff. */294 readonly children?: ReactNode;295 /**296 * For an `OpenProposal`, where the proposal's draft stands: Accept waits297 * while it is drafting. Read from `showProposal` when not passed.298 */299 readonly draft?: DraftState | undefined;300}) => {301 const [note, setNote] = useState("");302 const noteId = useId();303 const subject = describeSubject(decision.subject);
66 unmodified lines
370 {isFinishDecision(decision) && !standalone ? (371 <FinishLink decision={decision} />372 ) : null}373374 {opensAsk(decision.subject) ? (375 <ProposalLink376 project={decision.project}377 proposal={decision.subject.proposal}378 />379 ) : null}380381 {children === undefined ? null : (382 <div className="border-rule mt-3 flex flex-col gap-8 border-t pt-6">383 {children}384 </div>
15 unmodified lines
400 value={note}401 />402 </details>403277 <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>404 {opensAsk(decision.subject) && draft === undefined ? (405 <ProposalChoices406 busy={busy}407 choose={choose}408 decision={decision}409 proposal={decision.subject.proposal}410 subject={subject}411 />412 ) : (413 <Choices414 busy={busy}415 choose={choose}416 decision={decision}417 drafting={draft !== undefined && isDraftingNow(draft)}418 subject={subject}419 />420 )}421 </article>422 );423};
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+287 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 cannot import.34 */35export const DRAFT_ATTEMPTS = 3;3637/** The longest note `draftAsk` takes. */38const NOTE_LIMIT = 2000;3940/** Where a proposal stands in one word: its draft's while it is open, else its own. */41export const standing = (proposal: Proposal) =>42 proposal.state === "open" && proposal.draft !== undefined43 ? proposal.draft._tag44 : proposal.state;4546const draftingNow = DraftState.isAnyOf(["Drafting"]);4748/** Whether the platform's agent is drafting the proposal's ask right now. */49export const isDrafting = (proposal: Proposal) =>50 proposal.draft !== undefined && draftingNow(proposal.draft);5152const LABEL = "text-muted-foreground text-xs font-medium";5354/** The badge each standing wears: an ending that opened nothing reads as refused. */55const badgeVariant = {56 Drafting: "outline",57 Failed: "destructive",58 Ready: "secondary",59 accepted: "secondary",60 declined: "destructive",61 expired: "destructive",62 open: "secondary",63} as const satisfies Record<ReturnType<typeof standing>, string>;6465const StateBadge = ({ proposal }: { readonly proposal: Proposal }) => {66 const word = standing(proposal);6768 return (69 <Badge data-standing={word} variant={badgeVariant[word]}>70 {word === "Drafting" ? <Spinner className="size-3" /> : null}71 {word}72 </Badge>73 );74};7576/** What the draft says: in progress, ready with its red-first run, or failed. */77const DraftFacts = ({ draft }: { readonly draft: DraftState }) =>78 DraftState.match(draft, {79 Drafting: ({ round }) => (80 <p className="flex items-start gap-2 text-sm" data-draft="Drafting">81 <Spinner className="text-checking mt-0.5 shrink-0" />82 <span>83 Drafting (round {round}): the platform&apos;s agent is writing the ask84 and a check, then running the check on main, where it must fail twice85 the same way. This takes a few minutes; the page follows it.86 </span>87 </p>88 ),89 Failed: ({ attempts, model, refusal, round }) => (90 <div className="flex flex-col gap-1 text-sm" data-draft="Failed">91 <p className="flex items-start gap-2">92 <OctagonX93 aria-hidden="true"94 className="text-refused mt-0.5 size-4 shrink-0"95 />96 <span>97 The draft failed (round {round}), after {attempts} of{" "}98 {DRAFT_ATTEMPTS} attempts by {model}. The last refusal:{" "}99 <b className="text-refused font-mono font-semibold">{refusal}</b>100 </span>101 </p>102 </div>103 ),104 Ready: ({ attempts, model, red }) => (105 <dl106 className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[minmax(8rem,auto)_1fr]"107 data-draft="Ready"108 >109 <dt className={`${LABEL} pt-0.5`}>Red first</dt>110 <dd className="mb-1.5 flex items-start gap-2 [overflow-wrap:anywhere] sm:mb-0">111 <CircleCheck112 aria-hidden="true"113 className="text-landed mt-0.5 size-4 shrink-0"114 />115 <span>116 fails twice the same way in lane {red.lane}: {red.signature}117 </span>118 </dd>119 <dt className={`${LABEL} pt-0.5`}>Drafted by</dt>120 <dd className="mb-1.5 [overflow-wrap:anywhere] sm:mb-0">121 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}122 </dd>123 </dl>124 ),125 });126127/** "Draft again", with a note the agent reads. */128const Redraft = ({129 again,130 busy,131 onRedraft,132}: {133 readonly again: boolean;134 readonly busy: boolean;135 readonly onRedraft: (note: string | undefined) => void;136}) => {137 const [note, setNote] = useState("");138 const noteId = useId();139140 return (141 <section142 aria-label="Draft again"143 className="border-rule flex flex-col gap-3 border-t pt-4"144 >145 <details className="text-sm">146 <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">147 Add a note for the agent148 </summary>149 <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>150 What the next draft should do differently151 </label>152 <Textarea153 className="mt-1 text-sm md:text-sm"154 id={noteId}155 maxLength={NOTE_LIMIT}156 onChange={(event) => {157 setNote(event.target.value);158 }}159 value={note}160 />161 </details>162 <Button163 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"164 disabled={busy}165 onClick={() => {166 const written = note.trim();167168 onRedraft(written.length === 0 ? undefined : written);169 }}170 type="button"171 variant="outline"172 >173 {again ? "Draft again" : "Let the platform's agent draft it"}174 </Button>175 </section>176 );177};178179/** The way to the open decision that would open the ask. */180const DecisionLink = ({181 decision,182 project,183}: {184 readonly decision: DecisionId;185 readonly project: ProjectName;186}) => (187 <a188 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"189 data-decision={decision}190 href={`/${project}/decisions/${decision}`}191 >192 <Scale aria-hidden="true" className="size-4 shrink-0" />193 Decide it: {decision}194 </a>195);196197export const ProposalView = ({198 busy = false,199 children,200 decision,201 files,202 mayRedraft,203 onRedraft = constVoid,204 project,205 proposal,206}: {207 readonly project: ProjectName;208 readonly proposal: Proposal;209 /** The files the proposal holds (the ask file and its check), as `showProposal` read them. */210 readonly files: readonly ConfigFile[];211 /** The open decision on the proposal, when the reader's Today holds it. */212 readonly decision: Option.Option<DecisionId>;213 /** Whether the reader is its proposer or one of the project's deciders. */214 readonly mayRedraft: boolean;215 readonly onRedraft?: (note: string | undefined) => void;216 /** Whether a "Draft again" is on its way: the button waits. */217 readonly busy?: boolean;218 /** What the last "Draft again" came back with, when it was refused. */219 readonly children?: ReactNode;220}): ReactNode => {221 const open = proposal.state === "open";222223 return (224 <article225 aria-labelledby={`${proposal.id}-want`}226 className="flex max-w-[90ch] min-w-0 flex-col gap-5"227 data-proposal={proposal.id}228 >229 <header className="flex flex-col gap-2">230 <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">231 <span className="font-mono">{project}</span>232 <span aria-hidden="true">·</span>233 <span className="font-mono">{proposal.id}</span>234 <StateBadge proposal={proposal} />235 </p>236 <h2237 className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"238 id={`${proposal.id}-want`}239 >240 {proposal.want}241 </h2>242 <p className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">243 <span>244 Proposed by <HandleLink handle={proposal.proposer} />245 </span>246 {proposal.territory === undefined ? null : (247 <span>248 in <code className="font-mono">{proposal.territory}</code>249 </span>250 )}251 </p>252 </header>253254 {proposal.draft === undefined ? null : (255 <DraftFacts draft={proposal.draft} />256 )}257258 {Option.isSome(decision) ? (259 <DecisionLink decision={decision.value} project={project} />260 ) : null}261262 {files.length === 0 ? null : (263 <section264 aria-labelledby={`${proposal.id}-files`}265 className="flex min-w-0 flex-col gap-4"266 >267 <h2 className="text-base font-semibold" id={`${proposal.id}-files`}>268 {proposal.draft === undefined ? "Proposed files" : "Drafted files"}269 </h2>270 {files.map(({ content, path }) => (271 <DraftedCode content={content} key={path} path={path} />272 ))}273 </section>274 )}275276 {children}277278 {mayRedraft && open && !isDrafting(proposal) ? (279 <Redraft280 again={proposal.draft !== undefined}281 busy={busy}282 onRedraft={onRedraft}283 />284 ) : null}285 </article>286 );287};
added:apps/web/src/features/propose/propose-link.tsx+38 added
added:apps/web/src/features/propose/propose-view.tsx+215 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/** The form's own address, for sign-in to come back to. */64const proposePath = (project: ProjectName) => `/${project}/proposals/new`;6566const LABEL = "text-muted-foreground text-xs font-medium";6768const SignInFirst = ({ project }: { readonly project: ProjectName }) => (69 <section70 aria-label="Sign in to propose"71 className="border-rule flex flex-col gap-3 border-t pt-4"72 >73 <p className="flex items-start gap-2 text-sm">74 <LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />75 <span>76 Proposing an ask is for signed-in members.{" "}77 <a78 className="decoration-rule font-medium underline hover:decoration-current"79 href={`/auth/signin?${new URLSearchParams({ return: proposePath(project) }).toString()}`}80 >81 Sign in82 </a>{" "}83 to propose one, or propose from your clone:84 </span>85 </p>86 <CommandLine command={`${Brand.cli} propose --draft "<want>"`} />87 </section>88);8990export const ProposeView = ({91 about,92 busy = false,93 children,94 modules,95 onPropose,96 project,97 signedIn,98}: {99 readonly project: ProjectName;100 readonly signedIn: boolean;101 readonly about: Option.Option<About>;102 /** The project's top folders, each a territory to choose. */103 readonly modules: readonly RepoPath[];104 /** Sends the payload; the route goes to the proposal once it is made. */105 readonly onPropose?: (payload: ProposePayload) => void;106 /** Whether a proposal is on its way: the button waits. */107 readonly busy?: boolean;108 /** What the last proposal came back with, when it was refused. */109 readonly children?: ReactNode;110}): ReactNode => {111 const id = useId();112113 const [want, setWant] = useState(() =>114 Option.match(about, { onNone: () => "", onSome: wantAbout })115 );116117 const [territory, setTerritory] = useState("");118 const [draft, setDraft] = useState(true);119120 if (!signedIn) {121 return <SignInFirst project={project} />;122 }123124 const chosen = modules.find((module) => module === territory);125 const written = want.trim().length > 0;126127 return (128 <form129 aria-label="Propose an ask"130 className="flex max-w-[70ch] flex-col gap-5"131 onSubmit={(event) => {132 event.preventDefault();133134 if (written) {135 onPropose?.(136 proposalPayload(137 chosen === undefined138 ? { draft, project, want }139 : { draft, project, territory: chosen, want }140 )141 );142 }143 }}144 >145 <div className="flex flex-col gap-1.5">146 <label className={LABEL} htmlFor={`${id}-want`}>147 What should the project do that it does not do now?148 </label>149 <Textarea150 className="min-h-32 text-sm md:text-sm"151 id={`${id}-want`}152 name="want"153 onChange={(event) => {154 setWant(event.target.value);155 }}156 required157 value={want}158 />159 </div>160161 <div className="flex flex-col gap-1.5">162 <label className={LABEL} htmlFor={`${id}-territory`}>163 Territory (optional)164 </label>165 <select166 className="border-input bg-background h-9 w-full max-w-xs rounded-none border px-2 text-sm"167 id={`${id}-territory`}168 name="territory"169 onChange={(event) => {170 setTerritory(event.target.value);171 }}172 value={territory}173 >174 <option value="">Let the agent choose</option>175 {modules.map((module) => (176 <option key={module} value={module}>177 {module}178 </option>179 ))}180 </select>181 </div>182183 <div className="flex items-start gap-2">184 <Checkbox185 checked={draft}186 className="mt-0.5"187 id={`${id}-draft`}188 name="draft"189 onCheckedChange={(checked) => {190 setDraft(checked);191 }}192 />193 <Label className="text-sm leading-snug" htmlFor={`${id}-draft`}>194 Let the platform&apos;s agent draft the ask195 </Label>196 </div>197 <p className="text-muted-foreground -mt-3 pl-6 text-xs">198 It writes the ask file and a check that fails on main, runs it red199 first, and puts the draft to a decider. Clear the box to propose the200 want alone.201 </p>202203 {children}204205 <Button206 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"207 disabled={busy || !written}208 type="submit"209 >210 {busy ? <Spinner /> : null}211 Propose212 </Button>213 </form>214 );215};
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+123 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 { modulesAtom, proposeAtom } from "../../../client/propose.ts";9import { whoAtom } from "../../../features/auth/who.ts";10import { ProjectNav } from "../../../features/project/project-nav.tsx";11import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";12import { ProposeView } from "../../../features/propose/propose-view.tsx";13import type { About } from "../../../features/propose/propose-view.tsx";14import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";15import { FailureView } from "../../../features/today/today-page.tsx";166// The propose form: a want, for the platform's agent to draft into an ask. A stub until 911 builds it.17// `/$project/proposals/new`: the propose form. Who is signed in and the18// project's top folders are read in the browser (the server paints the19// page while it checks); a proposal made goes to its own page, a refusal20// shows under the form. `?about=<path>&line=<n>&at=<sha>` (the why page's21// "Propose an ask about this line") starts the want at that line.228const Page = () => {9 const { project } = Route.useParams();23const decodeProject = Schema.decodeUnknownOption(ProjectName);2425/** The line a why page points at, when the address names all three parts. */26const AboutParts = Schema.Struct({27 about: RepoPath,28 at: CommitSha,29 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),30});3132const decodeAbout = Schema.decodeUnknownOption(AboutParts);3334const decodeText = Schema.decodeUnknownOption(Schema.String);3536const decodeLine = Schema.decodeUnknownOption(Schema.Int);3738/** The address's line, as the form takes it. */39const aboutOf = (search: {40 readonly about?: string | undefined;41 readonly at?: string | undefined;42 readonly line?: number | undefined;43}): Option.Option<About> =>44 Option.map(decodeAbout(search), ({ about, at, line }) => ({45 at,46 line,47 path: about,48 }));4950const Checking = () => (51 <output className="text-muted-foreground block text-sm">52 Checking who is signed in53 </output>54);5556/** The form for `project`, once the browser knows who is signed in. */57const Propose = ({ project }: { readonly project: ProjectName }) => {58 const navigate = useNavigate();59 const search = Route.useSearch();60 const who = useAtomValue(whoAtom);6162 const modules = Option.getOrElse(63 AsyncResult.value(useAtomValue(modulesAtom(project))),64 () => []65 );6667 const [proposed, propose] = useAtom(proposeAtom);68 // Set once this form sends: a proposal the atom still holds from an69 // earlier visit never moves the page.70 const [sent, setSent] = useState(false);7172 const made = sent73 ? Option.getOrUndefined(AsyncResult.value(proposed))?.proposal.id74 : undefined;7576 useEffect(() => {77 if (made !== undefined) {78 void navigate({79 params: { project, proposal: made },80 to: "/$project/proposals/$proposal",81 });82 }83 }, [made, navigate, project]);8485 if (!AsyncResult.isSuccess(who)) {86 return <Checking />;87 }8889 return (12 <NotBuilt13 issue="911"90 <ProposeView91 about={aboutOf(search)}92 busy={proposed.waiting}93 modules={modules}94 onPropose={(payload) => {95 setSent(true);96 propose(payload);97 }}98 project={project}15 title={`${project}: propose an ask`}16 />99 signedIn={Option.isSome(who.value)}100 >101 {AsyncResult.isFailure(proposed) ? (102 <div aria-live="polite">103 <FailureView cause={proposed.cause} />104 </div>105 ) : null}106 </ProposeView>107 );108};109110const Page = () => {111 const params = Route.useParams();112113 return Option.match(decodeProject(params.project), {114 onNone: () => <UnknownProjectView name={params.project} />,115 onSome: (project) => (116 <PageShell title={`${project}: propose an ask`}>117 <ProjectNav project={project} />118 <Propose project={project} />119 </PageShell>120 ),121 });122};123124export const Route = createFileRoute("/$project/proposals/new")({125 component: Page,126 validateSearch: (search: {127 readonly about?: unknown;128 readonly at?: unknown;129 readonly line?: unknown;130 }) => ({131 about: Option.getOrUndefined(decodeText(search.about)),132 at: Option.getOrUndefined(decodeText(search.at)),133 line: Option.getOrUndefined(decodeLine(search.line)),134 }),135 head: ({ params: { project } }) => ({136 meta: [{ title: pageTitle(`${project}: propose an ask`) }],137 }),138});
modified:apps/web/test/decision.test.tsx+93 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("links the proposal's page", () => {362 expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');363 });364});
added:apps/web/test/proposal.test.tsx+167 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 { ShowProposal } from "@repo/protocol/contracts";12import { DraftState } from "@repo/protocol/domain/proposal";13import { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";14import { DateTime, Option, Schema } from "effect";1516import { ProposalView } from "../src/features/proposal/proposal-view.tsx";17import { markupOf, plainText } from "./ask-fixtures.ts";1819const datekit = ProjectName.make("datekit");2021const decodeShown = Schema.decodeUnknownSync(ShowProposal.successSchema);2223const model = "@cf/moonshotai/kimi-k2.7-code";2425const askFile = `${Brand.configDir}/asks/format-keeps-offset.ask.ts`;2627const testFile = "src/format.offset.test.ts";2829type Shown = typeof ShowProposal.successSchema.Type;3031/** A proposal with no draft yet, as `showProposal` answers it, holding `files`. */32const shownWith = (files: readonly string[]): Shown =>33 decodeShown({34 files: files.map((path) => ({ content: `// ${path}\n`, path })),35 proposal: {36 expiresAt: "2026-10-21T09:00:00.000Z",37 files,38 id: "prop-000007",39 openedAt: "2026-10-07T09:00:00.000Z",40 project: "datekit",41 proposer: "lin-h",42 state: "open",43 want: "formatISO keeps the offset it was given.",44 },45 });4647/** `base` with its proposal's draft at `draft`. */48const withDraft = (base: Shown, draft: DraftState): Shown => ({49 ...base,50 proposal: { ...base.proposal, draft },51});5253const drafting = withDraft(54 shownWith([]),55 DraftState.cases.Drafting.make({56 round: 1,57 startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),58 })59);6061const ready = withDraft(62 shownWith([askFile, testFile]),63 DraftState.cases.Ready.make({64 attempts: 2,65 model,66 red: {67 lane: LaneName.make("unit"),68 signature: "expected '+02:00', got 'Z'",69 },70 round: 1,71 })72);7374const failed = withDraft(75 shownWith([]),76 DraftState.cases.Failed.make({77 attempts: 3,78 model,79 refusal: "NotRedFirst",80 round: 2,81 })82);8384const decision = DecisionId.make("dec-000003");8586const view = (87 { files, proposal }: Shown,88 linked: Option.Option<DecisionId> = Option.none()89) =>90 markupOf(91 <ProposalView92 decision={linked}93 files={files}94 mayRedraft95 project={datekit}96 proposal={proposal}97 />98 );99100const DRAFT_AGAIN = /<button[^>]*>[^<]*Draft again/u;101102describe(ProposalView, () => {103 it("shows the want and the proposer", () => {104 const text = plainText(view(drafting));105106 expect(text).toContain("formatISO keeps the offset it was given.");107 expect(text).toContain("lin-h");108 });109110 it("while drafting, shows the spinner and no Draft again", () => {111 const markup = view(drafting);112113 expect(markup).toContain('data-slot="spinner"');114 expect(plainText(markup)).toContain("Drafting");115 expect(markup).not.toMatch(DRAFT_AGAIN);116 });117118 it("once ready, shows both files, the red-first run, who drafted it and its decision", () => {119 const markup = view(ready, Option.some(decision));120 const text = plainText(markup);121122 expect(text).toContain(askFile);123 expect(text).toContain(testFile);124 expect(text).toContain(125 "fails twice the same way in lane unit: expected '+02:00', got 'Z'"126 );127 expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);128 expect(markup).toContain('href="/datekit/decisions/dec-000003"');129 });130131 it("once ready, shows no spinner", () => {132 expect(view(ready)).not.toContain('data-slot="spinner"');133 });134135 it("once failed, shows the last refusal's headline and Draft again", () => {136 const markup = view(failed);137138 expect(plainText(markup)).toContain("NotRedFirst");139 expect(markup).toMatch(DRAFT_AGAIN);140 });141142 it("offers Draft again only to the proposer or a decider", () => {143 const markup = markupOf(144 <ProposalView145 decision={Option.none()}146 files={[]}147 mayRedraft={false}148 project={datekit}149 proposal={failed.proposal}150 />151 );152153 expect(markup).not.toMatch(DRAFT_AGAIN);154 });155156 it("once accepted, offers no button", () => {157 const accepted: Shown = {158 ...ready,159 proposal: { ...ready.proposal, state: "accepted" },160 };161162 const markup = view(accepted);163164 expect(plainText(markup)).toContain("accepted");165 expect(markup).not.toContain("<button");166 });167});
added:apps/web/test/propose.test.tsx+117 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 { ProposeAsk } from "@repo/protocol/contracts";11import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";12import { Option, Schema } from "effect";1314import {15 ProposeView,16 proposalPayload,17} from "../src/features/propose/propose-view.tsx";18import type { About } from "../src/features/propose/propose-view.tsx";19import { markupOf, plainText } from "./ask-fixtures.ts";2021const datekit = ProjectName.make("datekit");2223const at = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");2425const modules = [RepoPath.make("docs"), RepoPath.make("src")];2627const signedIn = (about: Option.Option<About> = Option.none()) =>28 markupOf(29 <ProposeView about={about} modules={modules} project={datekit} signedIn />30 );3132/** The want's textarea, as the server renders it: its opening tag and text. */33const textareaOf = (markup: string) =>34 /<textarea[^>]*>(?<text>[^<]*)<\/textarea>/u.exec(markup);3536describe(ProposeView, () => {37 it("signed in, offers a want and the draft box, checked", () => {38 const markup = signedIn();3940 expect(textareaOf(markup)?.[0]).toContain('name="want"');41 expect(markup).toMatch(42 /role="checkbox"[^>]*aria-checked="true"|aria-checked="true"[^>]*role="checkbox"/u43 );44 expect(plainText(markup)).toContain(45 "Let the platform's agent draft the ask"46 );47 expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Propose/u);48 });4950 it("offers each of the project's top folders as the territory", () => {51 const markup = signedIn();5253 expect(markup).toContain('name="territory"');54 expect(markup).toContain('<option value="src">src</option>');55 expect(markup).toContain('<option value="docs">docs</option>');56 });5758 it("starts the want at the line a why page names", () => {59 const markup = signedIn(60 Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })61 );6263 expect(textareaOf(markup)?.groups?.text).toBe(64 "In `src/format.ts` line 12 at 4c2e6a8: "65 );66 });6768 it("signed out, shows no form and links to sign in", () => {69 const markup = markupOf(70 <ProposeView71 about={Option.none()}72 modules={modules}73 project={datekit}74 signedIn={false}75 />76 );7778 expect(markup).not.toContain("<form");79 expect(markup).not.toContain("<textarea");80 expect(markup).toMatch(/<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in/u);81 });82});8384describe(proposalPayload, () => {85 const isPayload = Schema.is(ProposeAsk.payloadSchema);8687 it("asks for a draft when the box is checked", () => {88 const payload = proposalPayload({89 draft: true,90 project: datekit,91 want: " formatISO keeps the offset. ",92 });9394 expect(payload).toStrictEqual({95 draft: true,96 project: "datekit",97 want: "formatISO keeps the offset.",98 });99 expect(isPayload(payload)).toBeTruthy();100 });101102 it("carries no draft key when the box is clear, and the territory when named", () => {103 const payload = proposalPayload({104 draft: false,105 project: datekit,106 territory: RepoPath.make("src"),107 want: "formatISO keeps the offset.",108 });109110 expect(payload).toStrictEqual({111 project: "datekit",112 territory: "src",113 want: "formatISO keeps the offset.",114 });115 expect(Object.hasOwn(payload, "draft")).toBeFalsy();116 });117});