Skip to content
Myr

Rebuild the decider pages in the shell: Today as sections, decisions with consequences, finish as a diff reader

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

- Today is read on the server with the reader's own session (`serverClient(env, getRequest())`) and seeds its atom; its response is `private, no-store`. The budget is one sentence ("Decisions: 2 taken, 3 left today. Finishes are counted apart: none taken."), the decisions sit under sticky "Due today" and "Within your budget" headers as two-line rows linked by their subject sentence, then "Waits for tomorrow" (the overflow as a sentence), newcomers and the landings that needed nobody. Signed out or not a decider, the page says what Today is, links Sign in and gives `myr today`. - Every choice carries a consequence line, from one exhaustive table beside `describeSubject` (`features/decision/subject.ts`), written from what `attention/decisions.ts`, `deciders.ts` and `landing.ts` do; where the platform takes no step (a widened proxy, a stored value) the line says so. One tap, no confirm; a choice taken keeps its row where it was, reading what it did, and the budget sentence moves with the next read. - From the shell's width the inspector holds the selected decision whole (`?decision=project/id`); below it a row opens in place, its choices kept above the bottom bar. - A decision's page is read the same way (`features/decision/read.ts`): title the subject, status line, evidence typed by kind, the decision's facts, the ask, proposal or posture it concerns; decided, the record replaces the choices; signed out, no choices and no evidence. - A finish reads as the code browser does: changed files in the rail, territory first, then tests, then the rest, with status letters, counts, read marks and the refused cross; the diff in 1211's `DiffCode` over a server plain-text diff at its measures, with refusals from earlier rounds under their lines, "Mark read" per file, Unified/Split, Collapse all, "n of N files read", J/K, a bar at the diff's foot below 1440 px and one file at a time on phones. Read marks live in this browser only, keyed by decision, head and each file's change; a newer head says so above the diff. - `DiffCode` takes `drawn` (files already parsed): a decision's diff arrives as a patch with no whole texts. The one change in `features/code/*`. - A waiver draws the marker's file at its line when the decision carries the answer's diff (`patch`); the platform does not send it yet (asked under the issue's Comments). - Proposal: title the want; Drafting in the checking role, Ready in the waiting role, a failed round drawn by `RefusalView` when its tag makes a whole refusal, else an ink line; the draft as a guide (the ask file, the check, red first) with no numerals; facts in the inspector. - Propose: one form, the kit's select (loaded in the browser, the server draws its trigger), Propose saying "Write the want first" while empty, the want at 16 px, what makes a good want and `myr propose --draft "<want>"` beside it. - The view-free reads (`features/{today,decision}/read.ts`), the finish rail's light shell and the browser-only select and sheet keep the root preloads at 243,771 of 244,000 and the web Worker's JavaScript at 3,973,937 of 4,075,000. - `todayAtom` renders as waiting on the server, so a page that does not seed it never reads Today there. - Tests: Today's sections, rows, budget sentence, overflow, consequence lines, a taken row, signed-out and NotDecider views, the loader over the fixtures as ines-v and signed out, its headers; every subject's consequence lines; the decision page's waiver annotation, record and signed-out view; the finish's file order, refusal annotation, read count, newer head, numbered lines, and read marks with a stub and a refusing storage; the proposal's title and status lines; the propose form's select, disabled reason and command. - ASSUMPTION: an earlier round's refusal `at` still names a nearby line in the finished head; a note whose line is not drawn sits at its file's top.

authored by oscabriel · committed by oscabriel · parent e817d6c · Browse files · 41 files+6018 added−1458 removed
This commit

State

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

Diff stats

41 files+6018 added−1458 removed

  • tests:+846 added−123 removed
  • other:+5172 added−1335 removed

41 files+6018 added−1458 removed

modified:apps/web/src/client/today.ts+15 added-5 removed
modified:apps/web/src/features/code/diff-view.tsx+7 added-1 removed
62 unmodified lines
63 /** The files folded now; each file's own default when absent. */64 readonly folded?: ReadonlySet<string> | undefined;65 /** A header's fold was pressed. */66 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;67 /**68 * The files already parsed, in the order to draw them: a decision's diff69 * comes as a patch, with no whole texts to parse `files` from.70 */71 readonly drawn?: readonly DrawnFile[] | undefined;72}7374/**75 * The header's hairline, only while it is stuck at the top (where the
84 unmodified lines
160};161162export const DiffCode = ({163 annotations = NO_ANNOTATIONS,164 drawn: parsed,165 files,166 folded,167 onFold,168 slots = NO_SLOTS,
2 unmodified lines
171 const handle = useRef<CodeViewHandle<DiffAnnotation, undefined>>(null);172 const container = useRef<HTMLDivElement>(null);173 const [hash, setHash] = useState("");174169 const drawn = useMemo(() => drawnFiles(files), [files]);175 const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);176177 const items = useMemo(178 () =>179 drawn.map((file) =>
182 unmodified lines
added:apps/web/src/features/decision/choices.tsx+190 added
1/**2 * A decider's choices on one decision: one button per choice its subject3 * allows, each taken with one tap (there is no confirm and no undo, as the4 * platform has none), and under each, in a muted line, what the platform5 * then does. The default (what happens if nobody decides) is the outline6 * button, with the word "default" beside its name.7 *8 * Once taken, the record replaces the buttons: who chose what, when, the9 * note, and what it did, in the landed role only for a choice that made10 * something happen.11 */12import type { Choice, Decision } from "@repo/protocol/domain/decision";13import type { DateTime } from "effect";14import { Option } from "effect";15import { useId } from "react";16import type { ReactNode } from "react";1718import { Button } from "../../components/ui/button.tsx";19import { Spinner } from "../../components/ui/spinner.tsx";20import { HandleLink } from "../shared/handle.tsx";21import { StateMarkIcon } from "../shared/marks.tsx";22import { When } from "../shared/time.tsx";23import {24 allowedChoices,25 choiceWords,26 consequenceOf,27 describeSubject,28 takenWords,29 tookEffect,30} from "./subject.ts";3132/** Why a choice waits, and whether it waits on something that will come. */33export interface Held {34 readonly reason: string;35 readonly waiting: boolean;36}3738/** How the choices sit: two to a row (main, a phone's open row), or one under another (the inspector). */39export type ChoicesLayout = "grid" | "stack";4041const LAYOUTS = {42 grid: "grid grid-cols-2 gap-x-3 gap-y-3",43 stack: "grid grid-cols-1 gap-3",44} as const satisfies Record<ChoicesLayout, string>;4546export const Choices = ({47 busy,48 decision,49 held = Option.none(),50 layout = "grid",51 onChoose,52}: {53 readonly decision: Decision;54 /** A choice on its way: every button waits. */55 readonly busy: boolean;56 /** Why Accept waits, when it does (a proposal whose draft is not read yet). */57 readonly held?: Option.Option<Held>;58 readonly layout?: ChoicesLayout;59 readonly onChoose: (choice: Choice) => void;60}) => {61 const id = useId();6263 return (64 <fieldset className="m-0 min-w-0 border-0 p-0" data-choices="">65 <legend className="sr-only">66 Your choice: {describeSubject(decision.subject)}67 </legend>68 <div className={LAYOUTS[layout]}>69 {allowedChoices(decision.subject).map((choice) => {70 const isDefault = choice === decision.default;71 const waits = Option.filter(held, () => choice === "accept");72 const consequence = consequenceOf(decision.subject, choice);7374 return (75 <div className="flex min-w-0 flex-col gap-1.5" key={choice}>76 <Button77 aria-describedby={`${id}-${choice}`}78 className="tablet:h-9 h-11 w-full px-4"79 data-choice={choice}80 disabled={busy || Option.isSome(waits)}81 onClick={() => {82 onChoose(choice);83 }}84 type="button"85 variant={isDefault ? "outline" : "default"}86 >87 {Option.isSome(waits) ? (88 <>89 {waits.value.waiting ? <Spinner /> : null}90 {waits.value.reason}91 </>92 ) : (93 choiceWords[choice]94 )}95 {isDefault ? (96 <span className="text-muted-foreground font-normal">97 default98 </span>99 ) : null}100 </Button>101 <p102 className="text-label text-muted-foreground font-normal"103 data-consequence={choice}104 id={`${id}-${choice}`}105 >106 {consequence}107 </p>108 </div>109 );110 })}111 </div>112 </fieldset>113 );114};115116/** A choice taken, in one line: its word in its role, then what it did. */117export const TakenLine = ({118 choice,119 decision,120 stamp = false,121}: {122 readonly decision: Decision;123 readonly choice: Choice;124 /** Settle the mark once: the decider took it while the page was open. */125 readonly stamp?: boolean;126}) => {127 const effect = tookEffect(decision, choice);128129 return (130 <p className="text-ui flex items-start gap-2" data-decided={choice}>131 <StateMarkIcon132 className="mt-0.5"133 mark={effect ? "landed" : "notNeeded"}134 stamp={stamp && effect}135 />136 <span className="min-w-0">137 <strong138 className={`font-semibold ${effect ? "text-landed" : "text-foreground"}`}139 >140 {takenWords[choice]}141 </strong>142 <span className="text-muted-foreground">143 {" · "}144 {consequenceOf(decision.subject, choice)}145 </span>146 </span>147 </p>148 );149};150151/** The record of a taken decision: the line, then who, when and the note. */152export const DecisionRecord = ({153 decided,154 decision,155 now,156 stamp = false,157}: {158 readonly decision: Decision;159 readonly decided: NonNullable<Decision["decided"]>;160 readonly now: DateTime.Utc;161 readonly stamp?: boolean;162}) => (163 <section aria-label="Decided" className="flex flex-col gap-2">164 <TakenLine choice={decided.choice} decision={decision} stamp={stamp} />165 <p className="text-ui text-muted-foreground pl-6">166 By <HandleLink handle={decided.by} /> <When at={decided.at} now={now} />167 </p>168 {decided.note === undefined ? null : (169 <p170 className="text-ui pl-6 [overflow-wrap:anywhere] whitespace-pre-line"171 data-note=""172 >173 {decided.note}174 </p>175 )}176 </section>177);178179/**180 * Choices kept in sight while their decision is: on a phone, a bar above181 * the bottom bar; from a tablet's width, where they sit.182 */183export const stuckAboveBar = (node: ReactNode) => (184 <div185 className="border-rule bg-background tablet:static tablet:border-t-0 tablet:p-0 tablet:mx-0 sticky bottom-[calc(3.5rem+env(safe-area-inset-bottom))] z-[6] -mx-4 border-t px-4 pt-3 pb-3"186 data-choices-bar=""187 >188 {node}189 </div>190);
modified:apps/web/src/features/decision/decision-card.tsx+205 added-344 removed
1/**2 * One decision, as a decider takes it: what it is about in plain words, the3 * evidence, what happens if nobody decides (the decision's own `default`)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.2 * One decision, as a decider takes it: when it expires and what happens if3 * nobody decides (the decision's own `default`), its evidence typed by its4 * subject, a note to keep with the choice, and the choices with what each5 * does. Once taken, the record replaces the choices. Today's inspector, a6 * phone's open row and the decision's own page each draw this one card.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 until its draft has been read, and while the platform's agent is11 * drafting the proposal again: the draft is passed in, or read from12 * `showProposal` in the browser when it is not, so the server never renders13 * an Accept the browser might then hold.8 * An `OpenProposal` holds Accept until its draft has been read, and while9 * the platform's agent is drafting it again: the draft is passed in, or10 * read from `showProposal` in the browser when it is not, so the server11 * never renders an Accept the browser might then hold.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";20import type { Evidence as Fact } from "@repo/protocol/domain/common";18import { DecisionSubject } from "@repo/protocol/domain/decision";19import type { Choice, Decision } from "@repo/protocol/domain/decision";20import { DraftState } from "@repo/protocol/domain/proposal";24import type { ProjectName, ProposalId } from "@repo/protocol/ids";25import { DateTime, Option } from "effect";26import { FileDiff, FileText, Hourglass, ShieldCheck } from "lucide-react";21import type { ProposalId } from "@repo/protocol/ids";22import type { DateTime } from "effect";23import { Option } from "effect";24import { ChevronDown, Hourglass, Shield } from "lucide-react";25import { useId, useState } from "react";26import type { ReactNode } from "react";2730import { Button } from "../../components/ui/button.tsx";31import { Spinner } from "../../components/ui/spinner.tsx";28import { Textarea } from "../../components/ui/textarea.tsx";33import {34 changedFiles,35 isFinishDecision,36 PATCH_LABEL,37 patchOf,38} from "../finish/patch.ts";39import { DraftedCode } from "../proposal/client-file.tsx";29import { changedFiles, isFinishDecision, patchOf } from "../finish/patch.ts";30import { DraftRead, useLiveDraft } from "../proposal/live-draft.ts";41import { LABEL } from "../shared/classes.ts";31import { When } from "../shared/time.tsx";32import { Choices, DecisionRecord } from "./choices.tsx";33import type { ChoicesLayout, Held } from "./choices.tsx";34import { DecisionEvidence, FinishLink } from "./evidence.tsx";35import { describeDefault } from "./subject.ts";3637export {38 allowedChoices,39 consequenceOf,40 describeDefault,41 describeSubject,42} from "./subject.ts";4344/** What a decider sends when they choose: the `decide` contract's payload, from its one schema. */45export type DecideInput = typeof Decide.payloadSchema.Type;4647const yesOrNo: readonly Choice[] = ["accept", "decline"];4849/**50 * The choices a subject's deciders have: a stray push is adopted or51 * reverted, anything else accepted or declined. The platform reads `accept`52 * on a stray push as `adopt` too, but the page offers each subject its own53 * words only.54 */55export const allowedChoices = DecisionSubject.match({56 Finish: () => yesOrNo,57 OpenProposal: () => yesOrNo,58 PostureChange: () => yesOrNo,59 ProxyWidened: () => yesOrNo,60 RaiseRatchet: () => yesOrNo,61 SecretInTree: () => yesOrNo,62 StrayPush: (): readonly Choice[] => ["adopt", "revert"],63 Vouch: () => yesOrNo,64 Waiver: () => yesOrNo,65});6667const short = (sha: string) => sha.slice(0, 7);6869/** A ref as people say it: `main` for `refs/heads/main`. */70const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");7172/** What a decision is about, in one plain sentence. */73export const describeSubject = DecisionSubject.match({74 Finish: ({ ask, head }) =>75 `Finish the passing answer to ${ask}, at ${short(head)}`,76 OpenProposal: ({ proposal }) => `Open the ask proposed in ${proposal}`,77 PostureChange: ({ from, to }) =>78 `Change the project's posture from ${from} to ${to}`,79 ProxyWidened: ({ hosts, item }) =>80 `Let ${item} be sent to ${hosts.length === 0 ? "more hosts" : hosts.join(", ")} through the platform's proxy`,81 RaiseRatchet: ({ after, ask, before, ratchet, territory }) =>82 `Raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}, for the answer to ${ask}`,83 SecretInTree: ({ ask, item }) =>84 `A stored value of ${item} turned up in the answer to ${ask}, which is held aside`,85 StrayPush: ({ after, before, ref }) =>86 `${refWords(ref)} moved without a landing, from ${short(before)} to ${short(after)}`,87 Vouch: ({ handle }) => `Vouch for ${handle}, so they may claim asks`,88 Waiver: ({ ask, at, marker, reason }) =>89 `Allow ${marker} at ${at.path}:${at.line} in the answer to ${ask}: ${reason}`,90});9192/** An expiry as a decider reads it on any phone: weekday, date and time, in UTC. */93const byWhen = (at: DateTime.Utc) =>94 `${DateTime.formatUtc(at, {95 day: "numeric",96 hour: "2-digit",97 hourCycle: "h23",98 locale: "en-GB",99 minute: "2-digit",100 month: "short",101 weekday: "short",102 })} UTC`;103104/** What happens when nobody decides in time: the decision's own default, and by when. */105export const describeDefault = (decision: Decision) =>106 `If nobody decides by ${byWhen(decision.expiresAt)}: ${decision.default}`;107108/** A decision's own page: for a `Finish`, the answer's diff and how to finish it. */109export const decisionPath = (decision: Decision) =>110 `/${decision.project}/decisions/${decision.id}`;111112const words = {113 accept: "Accept",114 adopt: "Adopt",115 decline: "Decline",116 revert: "Revert",117} as const satisfies Record<Choice, string>;11847/** Whether a decision opens a proposed ask. */48const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);4950/** Whether a draft is still being written. */51const isDraftingNow = DraftState.isAnyOf(["Drafting"]);52125/** Why Accept waits, and whether it is still waiting on something that will come. */126interface Held {127 readonly reason: string;128 readonly waiting: boolean;129}13053/**54 * Why Accept on a proposal waits, if it does: its draft not read yet, its55 * read failed, or the draft being written. Once read it may be accepted: a56 * ready draft, a want alone, or a failed round (which keeps an earlier
12 unmodified lines
69 : { reason: "Reading the draft…", waiting: true }70 ),71 });72151/**152 * Whether an evidence line holds a file: its label is a path (one word with153 * a slash or a dot, as the ask file under the config folder, or a check154 * at the root, `offset.test.ts`), where every other label is words.155 */156const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);157158/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */159const filesOf = (decision: Decision): readonly Fact[] =>160 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];161162const Facts = ({ facts }: { readonly facts: readonly Fact[] }) => (163 <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">164 {facts.map(({ href, label, value }) => (165 <div className="contents" key={`${label}:${value}`}>166 <dt className={`${LABEL} pt-0.5`}>{label}</dt>167 <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">168 {href === undefined ? (169 value170 ) : (171 <a172 className="decoration-rule underline hover:decoration-current"173 href={href}174 >175 {value}176 </a>177 )}178 </dd>179 </div>180 ))}181 </dl>73/** When it expires, and what happens if nobody decides. */74export const ExpiryLines = ({75 decision,76 now,77 soon,78}: {79 readonly decision: Decision;80 readonly now: DateTime.Utc;81 readonly soon: boolean;82}) => (83 <div className="text-ui flex flex-col gap-1">84 <p85 className={`flex items-start gap-2 ${soon ? "text-waiting font-medium" : "text-muted-foreground"}`}86 data-soon={soon}87 >88 <Hourglass89 aria-hidden="true"90 className="mt-0.5 size-4 shrink-0"91 strokeWidth={1.75}92 />93 <span>94 Expires <When at={decision.expiresAt} now={now} />95 {soon ? ", within the day" : null}96 </span>97 </p>98 <p className="flex items-start gap-2" data-default={decision.default}>99 <Shield100 aria-hidden="true"101 className="text-muted-foreground mt-0.5 size-4 shrink-0"102 strokeWidth={1.75}103 />104 <span>{describeDefault(decision)}</span>105 </p>106 </div>107);108184const Evidence = ({ decision }: { readonly decision: Decision }) => {185 // The diff is the finish page's; here it is only counted. A proposal's186 // files are drawn as code below the facts.187 const files = filesOf(decision);109/** A note kept with the choice, behind a disclosure. */110const NoteField = ({111 note,112 onNote,113}: {114 readonly note: string;115 readonly onNote: (note: string) => void;116}) => {117 const id = useId();118189 const facts = decision.evidence.filter(190 (fact) => fact.label !== PATCH_LABEL && !files.includes(fact)191 );192119 return (194 <>195 {facts.length === 0 ? null : <Facts facts={facts} />}196 {files.map(({ label, value }) => (197 <DraftedCode content={value} heading="h4" key={label} path={label} />198 ))}199 </>120 <details className="group text-ui">121 <summary className="text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 py-1 select-none [&::-webkit-details-marker]:hidden">122 Add a note to your choice123 <ChevronDown124 aria-hidden="true"125 className="size-3.5 transition-transform duration-150 group-open:rotate-180"126 strokeWidth={1.75}127 />128 </summary>129 <label130 className="text-label text-muted-foreground mt-2 block"131 htmlFor={id}132 >133 Note, kept with the decision134 </label>135 <Textarea136 className="tablet:text-ui mt-1 text-base"137 id={id}138 onChange={(event) => {139 onNote(event.target.value);140 }}141 value={note}142 />143 </details>144 );145};146203/** The way from a `Finish` decision on Today to its answer's diff. */204const FinishLink = ({ decision }: { readonly decision: Decision }) => {205 const files = Option.match(patchOf(decision), {206 onNone: () => "",207 onSome: (patch) => {208 const count = changedFiles(patch).length;209210 return ` (${count} ${count === 1 ? "file" : "files"} changed)`;211 },212 });213214 return (215 <a216 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"217 href={decisionPath(decision)}218 >219 <FileDiff aria-hidden="true" className="size-4 shrink-0" />220 Read the answer&apos;s diff and finish it{files}221 </a>222 );223};224225/** The way from an `OpenProposal` decision to the proposal's page: its draft and files. */226const ProposalLink = ({227 project,228 proposal,229}: {230 readonly project: ProjectName;231 readonly proposal: ProposalId;232}) => (233 <a234 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"235 href={`/${project}/proposals/${proposal}`}236 >237 <FileText aria-hidden="true" className="size-4 shrink-0" />238 Read the proposal239 </a>240);241242interface ChoicesProps {147interface ChoiceProps {148 readonly busy: boolean;244 readonly choose: (choice: Choice) => void;149 readonly handleChoose: (choice: Choice) => void;150 readonly decision: Decision;246 readonly subject: string;151 readonly layout: ChoicesLayout;152}153249/** One button per choice; Accept waits, saying why, while `held` says it should. */250const Choices = ({251 busy,252 choose,253 decision,254 held,255 subject,256}: ChoicesProps & { readonly held: Option.Option<Held> }) => (257 <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">258 <legend className="sr-only">Your choice: {subject}</legend>259 {allowedChoices(decision.subject).map((choice) => {260 const isDefault = choice === decision.default;261262 const waits = Option.filter(held, () => choice === "accept");263264 return (265 <Button266 className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"267 data-choice={choice}268 disabled={busy || Option.isSome(waits)}269 key={choice}270 onClick={() => {271 choose(choice);272 }}273 type="button"274 variant={isDefault ? "outline" : "default"}275 >276 {Option.isSome(waits) ? (277 <>278 {waits.value.waiting ? <Spinner /> : null}279 {waits.value.reason}280 </>281 ) : (282 words[choice]283 )}284 {isDefault ? (285 <span className="text-muted-foreground font-normal">default</span>286 ) : null}287 </Button>288 );289 })}290 </fieldset>291);292154/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */155const ProposalChoices = ({156 proposal,157 ...props297}: ChoicesProps & { readonly proposal: ProposalId }) => {158}: ChoiceProps & { readonly proposal: ProposalId }) => {159 const read = useLiveDraft(props.decision.project, proposal);160300 return <Choices {...props} held={acceptHeld(read)} />;161 return (162 <Choices163 busy={props.busy}164 decision={props.decision}165 held={acceptHeld(read)}166 layout={props.layout}167 onChoose={props.handleChoose}168 />169 );170};171172/**173 * What ends the card: the choices while the decision is open (a174 * proposal's held until its draft is read), the record once it is taken.175 */176const Ending = ({177 draft,178 now,179 stamp,180 ...props181}: ChoiceProps & {182 readonly draft: DraftRead | undefined;183 readonly now: DateTime.Utc;184 readonly stamp: boolean;185}) => {186 const { decision } = props;187188 if (decision.decided !== undefined) {189 return (190 <DecisionRecord191 decided={decision.decided}192 decision={decision}193 now={now}194 stamp={stamp}195 />196 );197 }198199 if (opensAsk(decision.subject)) {200 return draft === undefined ? (201 <ProposalChoices {...props} proposal={decision.subject.proposal} />202 ) : (203 <Choices204 busy={props.busy}205 decision={decision}206 held={acceptHeld(draft)}207 layout={props.layout}208 onChoose={props.handleChoose}209 />210 );211 }212213 return (214 <Choices215 busy={props.busy}216 decision={decision}217 layout={props.layout}218 onChoose={props.handleChoose}219 />220 );221};222223/** How many files a finish's diff changes, when it carries one. */224export const finishFileCount = (decision: Decision): number | undefined =>225 Option.getOrUndefined(226 Option.map(patchOf(decision), (patch) => changedFiles(patch).length)227 );228229export const DecisionCard = ({230 busy = false,231 children,232 choices,233 decision,234 draft,235 expiry = true,236 finishLink = true,237 layout = "grid",238 now,239 onDecide,240 soon = false,311 standalone = false,241 stamp = false,242}: {243 readonly decision: Decision;244 readonly now: DateTime.Utc;245 readonly onDecide: (input: DecideInput) => void;246 /** Whether it expires within the day (Today's `expiringSoon`). */247 readonly soon?: boolean;248 /** Whether a choice on it is on its way: its buttons wait. */249 readonly busy?: boolean;320 /** Whether it is shown on its own page, so its title needs no link there. */321 readonly standalone?: boolean;322 /** What its own page shows before the choices: for a finish, the diff. */250 /** What a page shows after the evidence, before the note (a waiver's diff). */251 readonly children?: ReactNode;252 /**253 * Where the choices go: in place (the default), or handed to the page,254 * which puts them where they stay in sight (a phone's sticky bar).255 */256 readonly choices?: (node: ReactNode) => ReactNode;257 /** Whether it says when it expires and its default (off where the page says so already). */258 readonly expiry?: boolean;259 /** Whether a finish links to its own page, where its diff is (off on that page). */260 readonly finishLink?: boolean;261 readonly layout?: ChoicesLayout;262 /** Settle the record's mark once: the choice was taken while the page was open. */263 readonly stamp?: boolean;264 /**265 * For an `OpenProposal`, what has been read of the proposal's draft:266 * Accept waits until it is read, and while it is drafting. Read from267 * `showProposal` in the browser when not passed.268 */269 readonly draft?: DraftRead | undefined;270}) => {271 const [note, setNote] = useState("");332 const noteId = useId();333 const subject = describeSubject(decision.subject);334 const Title = standalone ? "h2" : "h3";272336 const choose = (choice: Choice) => {273 const handleChoose = (choice: Choice) => {274 const written = note.trim();275276 const input = {277 choice,
3 unmodified lines
281282 onDecide(written.length === 0 ? input : { ...input, note: written });283 };284285 const chosen = (286 <Ending287 busy={busy}288 decision={decision}289 draft={draft}290 handleChoose={handleChoose}291 layout={layout}292 now={now}293 stamp={stamp}294 />295 );296297 return (298 <article350 aria-labelledby={`${noteId}-title`}351 className="flex flex-col gap-3"299 aria-label={`Decision ${decision.id}`}300 className="flex min-w-0 flex-col gap-4"301 data-decision={decision.id}302 data-project={decision.project}303 >355 <header className="flex flex-col gap-1">356 <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 text-xs">357 <span className="font-mono">{decision.project}</span>358 <span aria-hidden="true">·</span>359 <span className="font-mono">{decision.id}</span>360 </p>361 <Title362 className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"363 id={`${noteId}-title`}364 >365 {standalone ? (366 subject367 ) : (368 <a369 className="decoration-rule underline-offset-4 hover:underline"370 href={decisionPath(decision)}371 >372 {subject}373 </a>374 )}375 </Title>376 </header>377378 <div className="flex flex-col gap-1 text-sm">379 <p380 className={`flex items-start gap-2 ${soon ? "text-waiting font-medium" : "text-muted-foreground"}`}381 data-soon={soon}382 >383 <Hourglass aria-hidden="true" className="mt-0.5 size-4 shrink-0" />384 <span>385 Expires <When at={decision.expiresAt} now={now} />386 {soon ? ", within the day" : null}387 </span>388 </p>389 <p className="flex items-start gap-2" data-default={decision.default}>390 <ShieldCheck391 aria-hidden="true"392 className="text-muted-foreground mt-0.5 size-4 shrink-0"393 />394 <span>{describeDefault(decision)}</span>395 </p>396 </div>397398 <Evidence decision={decision} />399400 {isFinishDecision(decision) && !standalone ? (401 <FinishLink decision={decision} />304 {expiry && decision.decided === undefined ? (305 <ExpiryLines decision={decision} now={now} soon={soon} />306 ) : null}403404 {opensAsk(decision.subject) ? (405 <ProposalLink406 project={decision.project}407 proposal={decision.subject.proposal}408 />307 <DecisionEvidence decision={decision} />308 {finishLink && isFinishDecision(decision) ? (309 <FinishLink decision={decision} files={finishFileCount(decision)} />310 ) : null}410411 {children === undefined ? null : (412 <div className="border-rule mt-3 flex flex-col gap-8 border-t pt-6">413 {children}414 </div>415 )}416417 <details className="group text-sm">418 <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">419 Add a note to your choice420 </summary>421 <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>422 Note, kept with the decision423 </label>424 <Textarea425 className="mt-1 text-sm md:text-sm"426 id={noteId}427 onChange={(event) => {428 setNote(event.target.value);429 }}430 value={note}431 />432 </details>433434 {opensAsk(decision.subject) && draft === undefined ? (435 <ProposalChoices436 busy={busy}437 choose={choose}438 decision={decision}439 proposal={decision.subject.proposal}440 subject={subject}441 />442 ) : (443 <Choices444 busy={busy}445 choose={choose}446 decision={decision}447 held={448 draft !== undefined && opensAsk(decision.subject)449 ? acceptHeld(draft)450 : Option.none()451 }452 subject={subject}453 />454 )}311 {children}312 {decision.decided === undefined ? (313 <NoteField note={note} onNote={setNote} />314 ) : null}315 {choices === undefined ? chosen : choices(chosen)}316 </article>317 );318};
added:apps/web/src/features/decision/decision-page.tsx+352 added
1/**2 * One decision on its own page, every subject but a finish (which reads as3 * the code browser does, `features/finish/finish-view.tsx`). The title is4 * the subject in plain words; under it, when it expires, its default and5 * whose move it is. Main holds the evidence at the page's width (a6 * waiver's marker drawn at its line in the answer's diff, when the7 * decision carries the diff), a note, and the choices, each saying what8 * it does; on a phone the choices stay in a bar above the bottom bar.9 * The inspector holds the decision's own facts (its deciders, when it10 * opened and expires, its default), the ask or proposal it concerns, and,11 * for a posture change, the project's posture.12 *13 * Once taken, the record replaces the choices. Signed out, the page says14 * what a decision is and that its deciders take it on Today: no choices,15 * and nothing of its evidence.16 */17import { Brand } from "@repo/brand";18import type { Ask } from "@repo/protocol/domain/ask";19import { DecisionSubject } from "@repo/protocol/domain/decision";20import type { Decision } from "@repo/protocol/domain/decision";21import type { Proposal } from "@repo/protocol/domain/proposal";22import type { DecisionId, ProjectName } from "@repo/protocol/ids";23import type { DateTime } from "effect";24import type { ReactNode } from "react";2526import { signInHref } from "../auth/session-slot.tsx";27import { MarkerNote } from "../finish/annotation.tsx";28import type { PatchFile } from "../finish/files.ts";29import { FinishPlainDiff } from "../finish/finish-plain.tsx";30import type { LineNote } from "../finish/finish-plain.tsx";31import { CommandLine } from "../shared/command.tsx";32import { EmptyState } from "../shared/empty.tsx";33import { FactBlock, PostureFacts } from "../shared/facts.tsx";34import { HandleLink } from "../shared/handle.tsx";35import { AppLink } from "../shared/link.tsx";36import { askPath } from "../shared/paths.ts";37import { UnreachableNotice } from "../shared/pending.tsx";38import { RefusalView } from "../shared/refusal.tsx";39import { Workspace } from "../shared/shell/workspace.tsx";40import { StatusLine } from "../shared/status-line.tsx";41import { When } from "../shared/time.tsx";42import { stuckAboveBar } from "./choices.tsx";43import { DecisionCard } from "./decision-card.tsx";44import type { DecideInput } from "./decision-card.tsx";45import { DecisionRead } from "./read.ts";46import type { DecisionPageData, FoundDecision } from "./read.ts";47import { byWhen, describeSubject, subjectKind } from "./subject.ts";4849export { DecisionPageData, DecisionRead } from "./read.ts";5051export type { FoundDecision } from "./read.ts";5253const waives = DecisionSubject.isAnyOf(["Waiver"]);5455const finishes = DecisionSubject.isAnyOf(["Finish"]);5657/** No files: a decision that carries no diff. */58const NO_FILES: readonly PatchFile[] = [];5960const LINK = "decoration-rule underline hover:decoration-current";6162/** The trail to a decision: its project, Today, its id. */63const crumbsOf = (project: ProjectName, id: DecisionId) => [64 { label: project, to: `/${project}` },65 { label: "Today", to: "/today" },66 { label: id, mono: true },67];6869/** The decision's own facts: who decides it, when it opened and expires, its default. */70const DecisionFacts = ({71 decision,72 now,73 soon,74}: {75 readonly decision: Decision;76 readonly now: DateTime.Utc;77 readonly soon: boolean;78}) => (79 <FactBlock label="Decision">80 <dl className="text-ui grid grid-cols-[6rem_1fr] gap-x-3 gap-y-1.5">81 <dt className="text-label text-muted-foreground pt-0.5">Deciders</dt>82 <dd className="flex flex-wrap gap-x-2">83 {decision.deciders.map((handle) => (84 <HandleLink handle={handle} key={handle} />85 ))}86 </dd>87 <dt className="text-label text-muted-foreground pt-0.5">Opened</dt>88 <dd>89 <When at={decision.openedAt} now={now} />90 </dd>91 <dt className="text-label text-muted-foreground pt-0.5">Expires</dt>92 <dd className={soon ? "text-waiting font-medium" : ""} data-soon={soon}>93 <When at={decision.expiresAt} now={now} />94 <span className="text-muted-foreground font-normal">95 {" "}96 · {byWhen(decision.expiresAt)}97 </span>98 </dd>99 <dt className="text-label text-muted-foreground pt-0.5">Default</dt>100 <dd data-default={decision.default}>{decision.default}</dd>101 </dl>102 </FactBlock>103);104105/** The ask a decision concerns: its want and its page. */106const AskFacts = ({ ask }: { readonly ask: Ask }) => (107 <FactBlock label="The ask">108 <p className="text-ui">{ask.brief.want}</p>109 <AppLink className={`text-ui ${LINK}`} to={askPath(ask.project, ask.id)}>110 <code className="text-mono font-mono">{ask.id}</code>111 </AppLink>112 </FactBlock>113);114115/** The proposal a decision would open: its want, who proposed it, its page. */116const ProposalFacts = ({ proposal }: { readonly proposal: Proposal }) => (117 <FactBlock label="The proposal">118 <p className="text-ui">{proposal.want}</p>119 <p className="text-ui text-muted-foreground">120 Proposed by <HandleLink handle={proposal.proposer} />121 </p>122 <AppLink123 className={`text-ui ${LINK}`}124 to={`/${proposal.project}/proposals/${proposal.id}`}125 >126 Read its draft127 </AppLink>128 </FactBlock>129);130131/** The waiver's marker drawn at its line, in the answer's diff of that file. */132export const WaiverDiff = ({133 decision,134 files,135}: {136 readonly decision: Decision;137 readonly files: readonly PatchFile[];138}) => {139 if (!waives(decision.subject)) {140 return null;141 }142143 const { at, marker, reason } = decision.subject;144 const mine = files.filter(({ file }) => file.path === at.path);145146 const notes: readonly LineNote[] = [147 {148 line: at.line,149 node: <MarkerNote marker={marker} reason={reason} />,150 path: at.path,151 },152 ];153154 return mine.length === 0 ? null : (155 <section156 aria-label="The marker in the answer"157 className="flex min-w-0 flex-col gap-2"158 >159 <h2 className="text-title">The marker in the answer</h2>160 <div className="border-rule -mx-px overflow-hidden border">161 <FinishPlainDiff files={mine} notes={notes} />162 </div>163 </section>164 );165};166167/** What a decision is, for a reader who does not decide it here. */168const ForAnyone = ({169 children,170 id,171 project,172}: {173 readonly children?: ReactNode;174 readonly id: DecisionId;175 readonly project: ProjectName;176}) => (177 <div className="flex max-w-[70ch] flex-col items-start gap-3">178 <p className="text-body">179 Decision <code className="text-mono font-mono">{id}</code> is a choice put180 to {project}&apos;s deciders: the people its policy names for what it is181 about. A decider takes it on their Today, with its evidence and a safe182 default if nobody does.183 </p>184 <p className="text-ui">185 <AppLink className={LINK} to={`/${project}/people`}>186 Who decides in {project}187 </AppLink>188 </p>189 {children}190 <CommandLine command={`${Brand.cli} today --project ${project}`} />191 </div>192);193194export interface DecisionViewProps {195 readonly data: DecisionPageData;196 readonly onDecide: (input: DecideInput) => void;197 readonly busy?: boolean;198 /** The decision as the decider's choice left it, once taken here. */199 readonly taken?: Decision | undefined;200 /** The waiver's diff, parsed, when the decision carries one. */201 readonly files?: readonly PatchFile[];202 /** The page for a finish, when the decision is one (the route draws it whole). */203 readonly finish?: ReactNode;204 readonly here: string;205}206207/** A decision the reader may take, whole. */208const Found = ({209 busy,210 files,211 found,212 now,213 onDecide,214 taken,215}: {216 readonly found: FoundDecision;217 readonly now: DateTime.Utc;218 readonly onDecide: (input: DecideInput) => void;219 readonly busy: boolean;220 readonly files: readonly PatchFile[];221 readonly taken: Decision | undefined;222}) => {223 const decision = taken ?? found.decision;224225 const subject = {226 decision,227 kind: "decision",228 now,229 viewerDecides: true,230 } as const;231232 return (233 <Workspace234 crumbs={crumbsOf(decision.project, decision.id)}235 facts={236 <>237 <DecisionFacts decision={decision} now={now} soon={found.soon} />238 {found.ask === undefined ? null : <AskFacts ask={found.ask} />}239 {found.proposal === undefined ? null : (240 <ProposalFacts proposal={found.proposal} />241 )}242 {found.posture === undefined ? null : (243 <PostureFacts244 label={found.posture.label}245 posture={found.posture.posture}246 project={decision.project}247 />248 )}249 </>250 }251 factsHeading="This decision"252 meta={253 <>254 {decision.project} · {subjectKind(decision.subject)} ·{" "}255 <code className="text-mono font-mono">{decision.id}</code>256 </>257 }258 state={<StatusLine compact subject={subject} />}259 status={<StatusLine stamp={taken !== undefined} subject={subject} />}260 title={describeSubject(decision.subject)}261 >262 <DecisionCard263 busy={busy}264 choices={stuckAboveBar}265 decision={decision}266 expiry={false}267 now={now}268 onDecide={onDecide}269 soon={found.soon}270 stamp={taken !== undefined}271 >272 <WaiverDiff decision={decision} files={files} />273 </DecisionCard>274 </Workspace>275 );276};277278/** The page for a decision that cannot be shown whole, with why. */279const Apart = ({280 children,281 data,282}: {283 readonly children: ReactNode;284 readonly data: DecisionPageData;285}) => (286 <Workspace287 crumbs={crumbsOf(data.project, data.decision)}288 title={`Decision ${data.decision}`}289 >290 {children}291 </Workspace>292);293294export const DecisionView = ({295 busy = false,296 data,297 files = NO_FILES,298 finish,299 here,300 onDecide,301 taken,302}: DecisionViewProps) =>303 DecisionRead.match(data.read, {304 Found: (found) =>305 finish !== undefined && finishes(found.decision.subject) ? (306 finish307 ) : (308 <Found309 busy={busy}310 files={files}311 found={found}312 now={data.now}313 onDecide={onDecide}314 taken={taken}315 />316 ),317 NotOnToday: () => (318 <Apart data={data}>319 <EmptyState320 command={`${Brand.cli} today --project ${data.project}`}321 title={`Decision ${data.decision} is not on your Today: it was decided, it expired to its default, or it waits beyond today's budget.`}322 />323 </Apart>324 ),325 Refused: ({ refusal }) => (326 <Apart data={data}>327 <ForAnyone id={data.decision} project={data.project}>328 <RefusalView refusals={[refusal]} />329 </ForAnyone>330 </Apart>331 ),332 SignedOut: () => (333 <Apart data={data}>334 <ForAnyone id={data.decision} project={data.project}>335 <p className="text-ui">336 <a337 className="decoration-rule font-medium underline hover:decoration-current"338 href={signInHref(here)}339 >340 Sign in341 </a>{" "}342 to take it, if you decide in {data.project}.343 </p>344 </ForAnyone>345 </Apart>346 ),347 Unreachable: () => (348 <Apart data={data}>349 <UnreachableNotice />350 </Apart>351 ),352 });
added:apps/web/src/features/decision/evidence.tsx+351 added
1import type { Evidence as Fact } from "@repo/protocol/domain/common";2/**3 * A decision's evidence, typed by what it is about: the commits a stray4 * push moved between (each a link to its page), the proposal's draft and5 * files, a ratchet's before and after, a waiver's marker at its line, a6 * posture's from and to beside the ledger, the hosts a proxy may now reach,7 * the item a stored value matched, the person a vouch admits, the answer a8 * finish lands. Then whatever else the platform put on it, as label and9 * value, the diff and the fork left to the finish.10 *11 * Every value that is code is mono; every link is the router's.12 */13import { DecisionSubject } from "@repo/protocol/domain/decision";14import type { Decision } from "@repo/protocol/domain/decision";15import type { Posture } from "@repo/protocol/posture";16import { ArrowRight, FileDiff, FileText } from "lucide-react";17import type { ReactNode } from "react";1819import { commitHref, shortSha } from "../code/paths.ts";20import { FORK_LABEL, PATCH_LABEL } from "../finish/patch.ts";21import { DraftedCode } from "../proposal/client-file.tsx";22import { HandleLink } from "../shared/handle.tsx";23import { AppLink } from "../shared/link.tsx";24import { POSTURE_MARKS } from "../shared/mark-look.ts";25import { Mark } from "../shared/marks.tsx";26import { answerPath, envPath, ledgerPath } from "../shared/paths.ts";27import { refWords } from "./subject.ts";2829const LINK = "decoration-rule underline hover:decoration-current";3031const CODE = "text-mono font-mono [overflow-wrap:anywhere]";3233/**34 * Whether an evidence line holds a file: its label is a path (one word with35 * a slash or a dot, as the ask file under the config folder, or a check36 * at the root, `offset.test.ts`), where every other label is words.37 */38const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);3940const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);4142/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */43export const filesOf = (decision: Decision): readonly Fact[] =>44 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];4546/** One fact: its label over (or beside) its value. */47const FactRow = ({48 children,49 label,50}: {51 readonly children: ReactNode;52 readonly label: string;53}) => (54 <div className="contents">55 <dt className="text-label text-muted-foreground pt-0.5">{label}</dt>56 <dd className="text-ui tablet:mb-0 mb-1.5 min-w-0 [overflow-wrap:anywhere]">57 {children}58 </dd>59 </div>60);6162const FactList = ({ children }: { readonly children: ReactNode }) => (63 <dl className="tablet:grid-cols-[minmax(7rem,auto)_1fr] grid grid-cols-1 gap-x-4 gap-y-1.5">64 {children}65 </dl>66);6768/** A link to a page of the web, with its mark. */69const PageLink = ({70 children,71 icon: Icon,72 to,73}: {74 readonly children: ReactNode;75 readonly icon: typeof FileText;76 readonly to: string;77}) => (78 <AppLink79 className={`text-ui flex w-fit items-center gap-2 font-medium ${LINK}`}80 to={to}81 >82 <Icon aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />83 {children}84 </AppLink>85);8687/** A posture as a mark and its name, in its role. */88const PostureWord = ({ posture }: { readonly posture: Posture }) => (89 <span className="inline-flex items-center gap-1.5">90 <Mark look={POSTURE_MARKS[posture]} size="sm" />91 <code className={CODE}>{posture}</code>92 </span>93);9495/** From one value to another, the arrow hidden from a screen reader, which hears "to". */96const FromTo = ({97 from,98 to,99}: {100 readonly from: ReactNode;101 readonly to: ReactNode;102}) => (103 <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1 tabular-nums">104 {from}105 <ArrowRight106 aria-hidden="true"107 className="text-muted-foreground size-3.5"108 strokeWidth={1.75}109 />110 <span className="sr-only">to</span>111 {to}112 </span>113);114115const CommitLink = ({116 decision,117 sha,118}: {119 readonly decision: Decision;120 readonly sha: string;121}) => (122 <AppLink123 className={`${CODE} ${LINK}`}124 title={sha}125 to={commitHref(decision.project, sha)}126 >127 {shortSha(sha)}128 </AppLink>129);130131/** The facts each subject carries in its own fields, typed. */132const SubjectFacts = ({ decision }: { readonly decision: Decision }) =>133 DecisionSubject.match(decision.subject, {134 Finish: ({ ask, head }) => (135 <FactList>136 <FactRow label="Answer">137 <AppLink className={LINK} to={answerPath(decision.project, ask)}>138 The answer to <code className={CODE}>{ask}</code>139 </AppLink>{" "}140 at{" "}141 <code className={CODE} title={head}>142 {shortSha(head)}143 </code>144 </FactRow>145 </FactList>146 ),147 OpenProposal: ({ proposal }) => (148 <PageLink149 icon={FileText}150 to={`/${decision.project}/proposals/${proposal}`}151 >152 Read the draft of {proposal}153 </PageLink>154 ),155 PostureChange: ({ from, to }) => (156 <FactList>157 <FactRow label="Posture">158 <FromTo159 from={<PostureWord posture={from} />}160 to={<PostureWord posture={to} />}161 />162 </FactRow>163 <FactRow label="Ledger">164 <AppLink className={LINK} to={ledgerPath(decision.project)}>165 The ledger of {decision.project}166 </AppLink>167 </FactRow>168 </FactList>169 ),170 ProxyWidened: ({ hosts, item }) => (171 <FactList>172 <FactRow label="Item">173 <code className={`${CODE} text-sealed`}>{item}</code>174 </FactRow>175 <FactRow label="Hosts">176 {hosts.length === 0 ? (177 "more hosts than before"178 ) : (179 <ul className="flex flex-col">180 {hosts.map((host) => (181 <li className={CODE} key={host}>182 {host}183 </li>184 ))}185 </ul>186 )}187 </FactRow>188 </FactList>189 ),190 RaiseRatchet: ({ after, ask, before, ratchet, territory }) => (191 <FactList>192 <FactRow label="Ratchet">193 <code className={CODE}>{ratchet}</code> in{" "}194 <code className={CODE}>{territory}</code>195 </FactRow>196 <FactRow label="Count">197 <FromTo from={before} to={after} />198 </FactRow>199 <FactRow label="Answer">200 <AppLink className={LINK} to={answerPath(decision.project, ask)}>201 The answer to <code className={CODE}>{ask}</code>202 </AppLink>203 </FactRow>204 </FactList>205 ),206 SecretInTree: ({ ask, item }) => (207 <FactList>208 <FactRow label="Item">209 <AppLink210 className={`${CODE} text-sealed ${LINK}`}211 to={envPath(decision.project)}212 >213 {item}214 </AppLink>215 </FactRow>216 <FactRow label="Answer">217 <AppLink className={LINK} to={answerPath(decision.project, ask)}>218 The answer to <code className={CODE}>{ask}</code>219 </AppLink>220 </FactRow>221 </FactList>222 ),223 StrayPush: ({ after, before, ref }) => (224 <FactList>225 <FactRow label="Ref">226 <code className={CODE}>{refWords(ref)}</code>227 </FactRow>228 <FactRow label="Moved">229 <FromTo230 from={<CommitLink decision={decision} sha={before} />}231 to={<CommitLink decision={decision} sha={after} />}232 />233 </FactRow>234 </FactList>235 ),236 Vouch: ({ handle }) => (237 <FactList>238 <FactRow label="Person">239 <HandleLink handle={handle} />240 </FactRow>241 </FactList>242 ),243 Waiver: ({ ask, at, marker, reason }) => (244 <FactList>245 <FactRow label="Marker">246 <code className={`${CODE} text-waiting font-medium`}>{marker}</code>{" "}247 at{" "}248 <code className={CODE}>249 {at.path}:{at.line}250 </code>251 </FactRow>252 <FactRow label="Reason">{reason}</FactRow>253 <FactRow label="Answer">254 <AppLink className={LINK} to={answerPath(decision.project, ask)}>255 The answer to <code className={CODE}>{ask}</code>256 </AppLink>257 </FactRow>258 </FactList>259 ),260 });261262/** A whole commit id in running evidence. */263const WHOLE_SHA = /\b[0-9a-f]{40}\b/u;264265/** `text` with each whole commit id cut to its first seven, whole in its title. */266const ShortShas = ({ text }: { readonly text: string }) =>267 text.split(/(?<sha>\b[0-9a-f]{40}\b)/u).map((part, index) =>268 WHOLE_SHA.test(part) ? (269 <code className={CODE} key={`${index}:${part}`} title={part}>270 {shortSha(part)}271 </code>272 ) : (273 part274 )275 );276277/** The labels the subject's own facts already say, or the finish draws. */278const SHOWN_ELSEWHERE: ReadonlySet<string> = new Set([PATCH_LABEL, FORK_LABEL]);279280/** The rest of what the platform put on the decision, as label and value. */281const OtherFacts = ({282 decision,283 files,284}: {285 readonly decision: Decision;286 readonly files: readonly Fact[];287}) => {288 const facts = decision.evidence.filter(289 (fact) => !SHOWN_ELSEWHERE.has(fact.label) && !files.includes(fact)290 );291292 return facts.length === 0 ? null : (293 <FactList>294 {facts.map(({ href, label, value }) => (295 <FactRow key={`${label}:${value}`} label={label}>296 {href === undefined ? (297 <ShortShas text={value} />298 ) : (299 <a className={LINK} href={href}>300 {value}301 </a>302 )}303 </FactRow>304 ))}305 </FactList>306 );307};308309/** The way from a `Finish` decision to its answer's diff, with how many files it changes. */310export const FinishLink = ({311 decision,312 files,313}: {314 readonly decision: Decision;315 readonly files: number | undefined;316}) => (317 <PageLink318 icon={FileDiff}319 to={`/${decision.project}/decisions/${decision.id}`}320 >321 Read the answer&apos;s diff322 {files === undefined ? "" : ` (${files} ${files === 1 ? "file" : "files"})`}323 </PageLink>324);325326/** A decision's evidence: its subject's facts, the rest, and a proposal's files as code. */327export const DecisionEvidence = ({328 decision,329 heading = "h4",330}: {331 readonly decision: Decision;332 /** The heading level a proposal's file paths take. */333 readonly heading?: "h3" | "h4";334}) => {335 const files = filesOf(decision);336337 return (338 <div className="flex min-w-0 flex-col gap-3" data-evidence="">339 <SubjectFacts decision={decision} />340 <OtherFacts decision={decision} files={files} />341 {files.map(({ label, value }) => (342 <DraftedCode343 content={value}344 heading={heading}345 key={label}346 path={label}347 />348 ))}349 </div>350 );351};
added:apps/web/src/features/decision/read.ts+256 added
1/**2 * What a decision's page reads, in a module with no view of its own: a3 * route's loader runs before its page's view loads, so the route reaches4 * these without carrying the page.5 *6 * The decision comes from the reader's Today in its project alone, read7 * with their own session: someone who decides nothing there gets why, and8 * no evidence. Beside it, what it concerns, each read on its own (one that9 * fails is left out): the ask, the proposal, the project's posture; for a10 * finish, the verdict on its head and, from the project's events, where11 * the answer's earlier rounds were refused and whether a newer head came.12 */13import { Client } from "@repo/protocol/contracts";14import { Verdict } from "@repo/protocol/domain/answer";15import { Ask } from "@repo/protocol/domain/ask";16import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";17import type { ProjectEvent } from "@repo/protocol/domain/event";18import { Outcome } from "@repo/protocol/domain/outcome";19import { Proposal } from "@repo/protocol/domain/proposal";20import { CommitSha, DecisionId, ProjectName } from "@repo/protocol/ids";21import type { AskId } from "@repo/protocol/ids";22import { Posture } from "@repo/protocol/posture";23import { Refusal } from "@repo/protocol/refusal";24import { notFound } from "@tanstack/react-router";25import { DateTime, Effect, Exit, Option, Schema, Stream } from "effect";2627import { askStates } from "../shared/ask-progress.ts";28import { findDecision, readOfCause, TodayRead } from "../today/read.ts";2930/** A refusal from an answer's round that points at a line, as the page's loader sends it. */31export const Placed = Schema.Struct({32 line: Schema.Int,33 path: Schema.String,34 refusal: Refusal,35 round: Schema.Int,36});3738/** What the page read for its reader: the decision and what it concerns, or why there is none. */39export const DecisionRead = Schema.TaggedUnion({40 Found: {41 /** The ask it concerns, when it concerns one. */42 ask: Schema.optionalKey(Ask),43 decision: Decision,44 /** A head pushed to the answer after the one a finish names. */45 newerHead: Schema.optionalKey(CommitSha),46 /** Refusals from the answer's rounds that point at a line. */47 placed: Schema.Array(Placed),48 /** The project's posture, for a posture change. */49 posture: Schema.optionalKey(50 Schema.Struct({ label: Schema.String, posture: Posture })51 ),52 /** The proposal it would open, for an `OpenProposal`. */53 proposal: Schema.optionalKey(Proposal),54 soon: Schema.Boolean,55 /** The verdict on a finish's head. */56 verdict: Schema.optionalKey(Verdict),57 },58 NotOnToday: {},59 Refused: { refusal: Refusal },60 SignedOut: {},61 Unreachable: {},62});6364export type DecisionRead = typeof DecisionRead.Type;6566export type FoundDecision = Extract<DecisionRead, { readonly _tag: "Found" }>;6768/** What a decision's loader sends: whose page, what it read, and when. */69export const DecisionPageData = Schema.Struct({70 decision: DecisionId,71 now: Schema.DateTimeUtcFromString,72 project: ProjectName,73 read: DecisionRead,74});7576export type DecisionPageData = typeof DecisionPageData.Type;7778/** The refusals among an outcome, when it refused. */79const refusalsOf = (outcome: Outcome): readonly Refusal[] =>80 Outcome.guards.Refused(outcome) ? outcome.refusals : [];8182/** Every refusal of an ask's rounds that points at a line, with the round it came from. */83const placedIn = (events: readonly ProjectEvent[], ask: AskId) =>84 (askStates(events).get(ask)?.rounds ?? []).flatMap(({ outcome }, index) =>85 refusalsOf(outcome).flatMap((refusal) =>86 refusal.at === undefined87 ? []88 : [89 {90 line: refusal.at.line,91 path: refusal.at.path,92 refusal,93 round: index + 1,94 },95 ]96 )97 );9899/** The head last pushed to `ask`, when it is not `head`. */100export const newerThan = (101 events: readonly ProjectEvent[],102 ask: AskId,103 head: CommitSha104): CommitSha | undefined => {105 const last = askStates(events).get(ask)?.lastPush?.head;106107 return last === undefined || last === head ? undefined : last;108};109110/** The ask a subject concerns, when it concerns one. */111const askOf = DecisionSubject.match({112 Finish: ({ ask }) => Option.some(ask),113 OpenProposal: () => Option.none(),114 PostureChange: () => Option.none(),115 ProxyWidened: () => Option.none(),116 RaiseRatchet: ({ ask }) => Option.some(ask),117 SecretInTree: ({ ask }) => Option.some(ask),118 StrayPush: () => Option.none(),119 Vouch: () => Option.none(),120 Waiver: ({ ask }) => Option.some(ask),121});122123/** What a decision concerns, each read on its own: one that fails is left out. */124const concerning = (decision: Decision, soon: boolean) =>125 Effect.gen(function* () {126 const client = yield* Client;127 const { project, subject } = decision;128129 const ask = yield* Option.match(askOf(subject), {130 onNone: () => Effect.succeedNone,131 onSome: (asked) =>132 client.showAsk({ ask: asked, project }).pipe(133 Effect.map(({ ask: shown }) => Option.some(shown)),134 Effect.orElseSucceed(() => Option.none())135 ),136 });137138 const proposal = DecisionSubject.guards.OpenProposal(subject)139 ? yield* client140 .showProposal({ project, proposal: subject.proposal })141 .pipe(142 Effect.map(({ proposal: shown }) => Option.some(shown)),143 Effect.orElseSucceed(() => Option.none())144 )145 : Option.none();146147 const posture = DecisionSubject.guards.PostureChange(subject)148 ? yield* client.ledger({ project }).pipe(149 Effect.map((ledger) =>150 Option.some({ label: ledger.postureLabel, posture: ledger.posture })151 ),152 Effect.orElseSucceed(() => Option.none())153 )154 : Option.none();155156 const finish = DecisionSubject.guards.Finish(subject)157 ? Option.some(subject)158 : Option.none();159160 const verdict = yield* Option.match(finish, {161 onNone: () => Effect.succeedNone,162 onSome: ({ ask: asked, head }) =>163 client.verdict({ ask: asked, head, project }).pipe(164 Effect.map(({ verdict: judged }) => Option.fromUndefinedOr(judged)),165 Effect.orElseSucceed(() => Option.none())166 ),167 });168169 // A finish's rounds, from the project's events: where earlier rounds170 // were refused, and whether a newer head was pushed.171 const events = Option.isSome(finish)172 ? yield* Stream.runCollect(client.watch({ project, since: 0 })).pipe(173 Effect.map((all): readonly ProjectEvent[] => all),174 Effect.orElseSucceed((): readonly ProjectEvent[] => [])175 )176 : [];177178 return DecisionRead.cases.Found.make({179 decision,180 placed: Option.match(finish, {181 onNone: () => [],182 onSome: ({ ask: asked }) => placedIn(events, asked),183 }),184 soon,185 ...Option.match(ask, {186 onNone: () => ({}),187 onSome: (shown) => ({ ask: shown }),188 }),189 ...Option.match(proposal, {190 onNone: () => ({}),191 onSome: (shown) => ({ proposal: shown }),192 }),193 ...Option.match(posture, {194 onNone: () => ({}),195 onSome: (shown) => ({ posture: shown }),196 }),197 ...Option.match(verdict, {198 onNone: () => ({}),199 onSome: (shown) => ({ verdict: shown }),200 }),201 ...Option.match(finish, {202 onNone: () => ({}),203 onSome: ({ ask: asked, head }) => {204 const newer = newerThan(events, asked, head);205206 return newer === undefined ? {} : { newerHead: newer };207 },208 }),209 });210 });211212/** The decision for its page, and what it concerns, read with the reader's session. */213export const readDecision = (params: {214 readonly project: string;215 readonly decision: string;216}) =>217 Effect.gen(function* () {218 const project = yield* Schema.decodeEffect(ProjectName)(219 params.project220 ).pipe(Effect.mapError(() => notFound()));221222 const id = yield* Schema.decodeEffect(DecisionId)(params.decision).pipe(223 Effect.mapError(() => notFound())224 );225226 const client = yield* Client;227 const now = yield* DateTime.now;228 const today = yield* Effect.exit(client.today({ project }));229230 const read = yield* Exit.match(today, {231 onFailure: (cause) =>232 Effect.succeed(233 TodayRead.match(readOfCause(cause), {234 Read: (): DecisionRead => DecisionRead.cases.Unreachable.make({}),235 Refused: ({ refusal }): DecisionRead =>236 DecisionRead.cases.Refused.make({ refusal }),237 SignedOut: (): DecisionRead =>238 DecisionRead.cases.SignedOut.make({}),239 Unreachable: (): DecisionRead =>240 DecisionRead.cases.Unreachable.make({}),241 })242 ),243 onSuccess: (listed) =>244 Option.match(findDecision(listed, project, id), {245 onNone: () => Effect.succeed(DecisionRead.cases.NotOnToday.make({})),246 onSome: ({ decision, soon }) => concerning(decision, soon),247 }),248 });249250 return yield* Schema.encodeEffect(DecisionPageData)({251 decision: id,252 now,253 project,254 read,255 });256 });
added:apps/web/src/features/decision/subject.ts+212 added
1/**2 * What a decision is about and what each choice on it does, in words, with3 * no view of its own: Today's rows, the inspector, a decision's page and4 * its finish all say a subject the same way.5 *6 * - `describeSubject`: the subject as one plain sentence, the row's link.7 * - `allowedChoices`: the choices its deciders have, in its own words.8 * - `consequenceOf`: what the platform does once a choice is taken, one9 * line under each button, written from what the platform's code does for10 * that subject. Where a choice changes nothing anyone can see, the line11 * says so rather than promising something.12 *13 * Each table names every subject, so a new kind fails to compile until it14 * has its sentence, its choices and its lines.15 */16import { DecisionSubject } from "@repo/protocol/domain/decision";17import type { Choice, Decision } from "@repo/protocol/domain/decision";18import { DateTime, Match } from "effect";1920const yesOrNo: readonly Choice[] = ["accept", "decline"];2122/**23 * The choices a subject's deciders have: a stray push is adopted or24 * reverted, anything else accepted or declined. The platform reads `accept`25 * on a stray push as `adopt` too, but the page offers each subject its own26 * words only.27 */28export const allowedChoices = DecisionSubject.match({29 Finish: () => yesOrNo,30 OpenProposal: () => yesOrNo,31 PostureChange: () => yesOrNo,32 ProxyWidened: () => yesOrNo,33 RaiseRatchet: () => yesOrNo,34 SecretInTree: () => yesOrNo,35 StrayPush: (): readonly Choice[] => ["adopt", "revert"],36 Vouch: () => yesOrNo,37 Waiver: () => yesOrNo,38});3940const short = (sha: string) => sha.slice(0, 7);4142/** A ref as people say it: `main` for `refs/heads/main`. */43export const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");4445/** What a decision is about, in one plain sentence. */46export const describeSubject = DecisionSubject.match({47 Finish: ({ ask, head }) =>48 `Finish the passing answer to ${ask}, at ${short(head)}`,49 OpenProposal: ({ proposal }) => `Open the ask proposed in ${proposal}`,50 PostureChange: ({ from, to }) =>51 `Change the project's posture from ${from} to ${to}`,52 ProxyWidened: ({ hosts, item }) =>53 `Let ${item} be sent to ${hosts.length === 0 ? "more hosts" : hosts.join(", ")} through the platform's proxy`,54 RaiseRatchet: ({ after, ask, before, ratchet, territory }) =>55 `Raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}, for the answer to ${ask}`,56 SecretInTree: ({ ask, item }) =>57 `A stored value of ${item} turned up in the answer to ${ask}, which is held aside`,58 StrayPush: ({ after, before, ref }) =>59 `${refWords(ref)} moved without a landing, from ${short(before)} to ${short(after)}`,60 Vouch: ({ handle }) => `Vouch for ${handle}, so they may claim asks`,61 Waiver: ({ ask, at, marker, reason }) =>62 `Allow ${marker} at ${at.path}:${at.line} in the answer to ${ask}: ${reason}`,63});6465/** A subject's kind as a row's metadata names it. */66export const subjectKind = DecisionSubject.match({67 Finish: () => "finish",68 OpenProposal: () => "proposal",69 PostureChange: () => "posture change",70 ProxyWidened: () => "proxy",71 RaiseRatchet: () => "ratchet",72 SecretInTree: () => "stored value",73 StrayPush: () => "stray push",74 Vouch: () => "vouch",75 Waiver: () => "waiver",76});7778/** What saying yes and saying no do, for one subject. */79interface Lines {80 readonly yes: string;81 readonly no: string;82}8384/** What the platform takes no step on: the choice is kept, and nothing else moves. */85const RECORDED =86 "Your choice is kept on the decision; the platform takes no other step on it.";8788/**89 * What each choice does, by subject, as the platform's code does it:90 *91 * - an accepted proposal opens its ask (its files land on main, decided by92 * the decider); a declined one closes;93 * - an accepted finish lands the answer at its head with the decider as94 * `Finished-by`; a declined one leaves it waiting;95 * - a waiver, a ratchet raise or a posture change holds an answer: yes lets96 * it go on with the decider as `Decided-by`, no refuses it with the97 * refusal the decision stood for;98 * - a stray push to main is adopted as a landing, or reverted by one, with99 * the decider as `Decided-by`; a push to another ref moves nothing;100 * - a vouch lands a line in the vouch file;101 * - a widened proxy or a stored value found in an answer is recorded, and102 * nothing else follows yet.103 */104const linesOf = (subject: DecisionSubject): Lines =>105 Match.value(subject).pipe(106 Match.tagsExhaustive({107 Finish: (): Lines => ({108 no: "Nothing lands; the answer keeps waiting for a finish.",109 yes: "Lands the answer as it is, with you as Finished-by.",110 }),111 OpenProposal: (): Lines => ({112 no: "The proposal closes; nothing lands.",113 yes: "Opens the ask: its file and check land on main, with you as Decided-by.",114 }),115 PostureChange: ({ from }): Lines => ({116 no: `The answer that changes it is refused; the posture stays ${from}.`,117 yes: "The answer that changes it goes on through the gate, with you as Decided-by.",118 }),119 ProxyWidened: (): Lines => ({ no: RECORDED, yes: RECORDED }),120 RaiseRatchet: ({ after, before }): Lines => ({121 no: `The answer is refused; the ratchet stays at ${before}.`,122 yes: `The answer goes on through the gate with the ratchet at ${after}, with you as Decided-by.`,123 }),124 SecretInTree: (): Lines => ({ no: RECORDED, yes: RECORDED }),125 StrayPush: ({ after, before, ref }): Lines =>126 refWords(ref) === "main"127 ? {128 no: `A landing puts back the tree at ${short(before)}, with you as Decided-by.`,129 yes: `main stays at ${short(after)}, kept as a landing with you as Decided-by.`,130 }131 : {132 no: `Only main is reverted: ${refWords(ref)} stays where it is.`,133 yes: `${refWords(ref)} stays where it is; only a push to main becomes a landing.`,134 },135 Vouch: ({ handle }): Lines => ({136 no: `Nothing lands; ${handle} stays unvouched.`,137 yes: `Lands ${handle} in the vouch file, with you as Decided-by.`,138 }),139 Waiver: ({ marker }): Lines => ({140 no: "The answer is refused at that line.",141 yes: `The answer goes on through the gate with ${marker} allowed there, with you as Decided-by.`,142 }),143 })144 );145146/** Whether a choice says yes, in any subject's words. */147const saysYes = {148 accept: true,149 adopt: true,150 decline: false,151 revert: false,152} as const satisfies Record<Choice, boolean>;153154/** What taking `choice` on `subject` does, in one line. */155export const consequenceOf = (156 subject: DecisionSubject,157 choice: Choice158): string => {159 const lines = linesOf(subject);160161 return saysYes[choice] ? lines.yes : lines.no;162};163164/** Each choice as its button says it. */165export const choiceWords = {166 accept: "Accept",167 adopt: "Adopt",168 decline: "Decline",169 revert: "Revert",170} as const satisfies Record<Choice, string>;171172/** Each choice once taken. */173export const takenWords = {174 accept: "Accepted",175 adopt: "Adopted",176 decline: "Declined",177 revert: "Reverted",178} as const satisfies Record<Choice, string>;179180/**181 * Whether a taken choice made something happen: what lands, opens or is182 * put back is drawn in the landed role; a choice that leaves things as they183 * were is ink.184 */185export const tookEffect = (decision: Decision, choice: Choice): boolean =>186 saysYes[choice]187 ? consequenceOf(decision.subject, choice) !== RECORDED188 : DecisionSubject.guards.StrayPush(decision.subject) &&189 refWords(decision.subject.ref) === "main";190191/** An expiry as a decider reads it on any phone: weekday, date and time, in UTC. */192export const byWhen = (at: DateTime.Utc) =>193 `${DateTime.formatUtc(at, {194 day: "numeric",195 hour: "2-digit",196 hourCycle: "h23",197 locale: "en-GB",198 minute: "2-digit",199 month: "short",200 weekday: "short",201 })} UTC`;202203/** What happens when nobody decides in time: the decision's own default, and by when. */204export const describeDefault = (decision: Decision) =>205 `If nobody decides by ${byWhen(decision.expiresAt)}: ${decision.default}`;206207/** A decision's own page. */208export const decisionHref = (decision: Decision) =>209 `/${decision.project}/decisions/${decision.id}`;210211/** A decision's place in a Today that may hold several projects. */212export const decisionKey = ({ id, project }: Decision) => `${project}/${id}`;
added:apps/web/src/features/finish/annotation.tsx+83 added
1/**2 * What a decider's diff marks under one of its lines: a refusal that3 * pointed there (in the rubric, its lines as `explain` printed them, the4 * round it came from), or a marker that waits on a decision (in ochre, the5 * marker and its reason). Compact, one block under the line, the same in6 * the server's plain diff and in the browser's drawing.7 */8import type { Refusal } from "@repo/protocol/refusal";9import { explain } from "@repo/protocol/render";10import { Hourglass, OctagonX, RotateCcw } from "lucide-react";1112/** A refusal placed in a diff: its file and line, and the round it came from. */13export interface PlacedRefusal {14 readonly refusal: Refusal;15 readonly path: string;16 readonly line: number;17 /** The round it refused, counting from 1. */18 readonly round: number;19}2021/** A refusal under its line, as git printed it. */22export const RefusalNote = ({ placed }: { readonly placed: PlacedRefusal }) => {23 const [first = "", ...rest] = explain([placed.refusal]).filter(24 (line) => !line.startsWith(" at: ")25 );2627 const prefix = `${placed.refusal._tag}:`;28 const Mark = placed.refusal.retryable ? RotateCcw : OctagonX;2930 return (31 <div32 className="border-y-refused/40 bg-background flex items-start gap-2 border-y px-4 py-2 font-sans"33 data-refusal={placed.refusal._tag}34 data-retryable={placed.refusal.retryable}35 >36 <Mark37 aria-hidden="true"38 className={`mt-0.5 size-3.5 shrink-0 ${placed.refusal.retryable ? "text-waiting" : "text-refused"}`}39 strokeWidth={1.75}40 />41 <div className="flex min-w-0 flex-col gap-0.5">42 <p className="text-label text-muted-foreground font-normal">43 Refused here in round {placed.round}44 </p>45 <samp className="text-mono leading-terminal block font-mono [overflow-wrap:anywhere] whitespace-pre-wrap">46 <span className="block">47 <b className="text-refused font-semibold">{prefix}</b>48 {first.slice(prefix.length)}49 </span>50 {rest.map((line) => (51 <span className="text-muted-foreground block" key={line}>52 {line}53 </span>54 ))}55 </samp>56 </div>57 </div>58 );59};6061/** A marker that waits on a decider, under its line. */62export const MarkerNote = ({63 marker,64 reason,65}: {66 readonly marker: string;67 readonly reason: string;68}) => (69 <div70 className="border-y-waiting/40 bg-background flex items-start gap-2 border-y px-4 py-2 font-sans"71 data-marker={marker}72 >73 <Hourglass74 aria-hidden="true"75 className="text-waiting mt-0.5 size-3.5 shrink-0"76 strokeWidth={1.75}77 />78 <p className="text-ui min-w-0">79 <span className="text-waiting font-medium">Waits on this decision:</span>{" "}80 <code className="text-mono font-mono">{marker}</code>, {reason}81 </p>82 </div>83);
deleted:apps/web/src/features/finish/client-diff.tsx-32 removed
added:apps/web/src/features/finish/files.ts+202 added
1/**2 * The files a decision's diff changes, as its page draws them: parsed once3 * by the drawing's own parser (`@pierre/diffs`' `parsePatchFiles`), so the4 * server's plain text and the browser's drawing hold the same hunks; each5 * file's `+n −m`, its id for the read marks, and its part of the change.6 *7 * The order is a rule, never a model's: the ask's territory first, then8 * tests, then anything else, each part by path in the order a tree lists9 * them.10 *11 * A diff's lines are numbered from its hunk headers (a patch holds only12 * the hunks, not the whole files), so a refusal's `at` line finds the line13 * it names.14 *15 * No React and no DOM: the server's render and the browser's both read it.16 */17import { parsePatchFiles } from "@pierre/diffs";18import type { FileDiffMetadata } from "@pierre/diffs";19import type { ChangedFile } from "@repo/protocol/domain/code";20import { RepoPath } from "@repo/protocol/ids";21import { Option, Schema } from "effect";2223import {24 countsOf,25 globTest,26 isTestPath,27 LONG_FILE,28 treeOrder,29} from "../code/diff-model.ts";30import type { DrawnFile } from "../code/diff-model.ts";31import { fileBlocks, patchIdOf } from "./patch.ts";3233/** Which part of the change a file is in. */34export type Part = "territory" | "tests" | "other";3536/** A changed file as the finish page holds it. */37export interface PatchFile extends DrawnFile {38 readonly part: Part;39 /** This file's change, as an id: what a read mark is kept against. */40 readonly patchId: string;41}4243const STATUS = {44 change: "modified",45 deleted: "deleted",46 new: "added",47 "rename-changed": "modified",48 "rename-pure": "modified",49} as const satisfies Record<FileDiffMetadata["type"], ChangedFile["status"]>;5051const PART_ORDER = {52 other: 2,53 territory: 0,54 tests: 1,55} as const satisfies Record<Part, number>;5657const decodePath = Schema.decodeUnknownOption(RepoPath);5859/** The part a path is in: the territory's, the tests', or the rest. */60export const partOf =61 (territory: readonly string[]) =>62 (path: string): Part => {63 if (isTestPath(path)) {64 return "tests";65 }6667 return territory.some((glob) => globTest(glob)(path))68 ? "territory"69 : "other";70 };7172/** Whether a file's block holds no text lines to draw: git's binary notes. */73const isBinary = (block: string) =>74 /^(?:Binary files .* differ|GIT binary patch)$/mu.test(block);7576/**77 * The files `patch` changes, parsed and counted, territory first, then78 * tests, then the rest. `key` names the change, so the drawing caches each79 * file's highlighting once.80 */81export const patchFiles = (82 patch: string,83 territory: readonly string[],84 key: string85): readonly PatchFile[] => {86 const blocks = fileBlocks(patch);87 const part = partOf(territory);8889 const parsed = parsePatchFiles(patch).flatMap(({ files }) => files);9091 return parsed92 .flatMap((diff): readonly PatchFile[] => {93 const path = decodePath(diff.name);9495 if (Option.isNone(path)) {96 return [];97 }9899 const block = blocks.get(diff.name) ?? "";100 const binary = isBinary(block);101 const patchId = patchIdOf(block);102103 diff.cacheKey = `finish:${key}:${diff.name}:${patchId}`;104105 const shown = binary ? Option.none() : Option.some(diff);106 const counts = countsOf(shown);107 const status = STATUS[diff.type];108109 return [110 {111 counts,112 diff: shown,113 file: { binary, path: path.value, status },114 folded:115 status !== "modified" &&116 counts.additions + counts.deletions > LONG_FILE,117 part: part(diff.name),118 patchId,119 },120 ];121 })122 .toSorted(123 (a, b) =>124 PART_ORDER[a.part] - PART_ORDER[b.part] ||125 treeOrder(a.file.path, b.file.path)126 );127};128129/** One numbered line of a patch, on its side. */130export interface PatchLine {131 readonly kind: "addition" | "context" | "deletion";132 /** Its number in the new file (context and additions) or the old one (deletions). */133 readonly number: number;134 readonly text: string;135}136137/** One row of a patch's unified view: a line, or the unchanged lines a hunk skips. */138export type PatchRow =139 | { readonly kind: "separator"; readonly lines: number }140 | PatchLine;141142/** A line as the diff stores it, without its line ending. */143const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");144145/**146 * `diff` as unified rows, each line numbered from its hunk's header: a147 * context line and an addition by the new file, a deletion by the old.148 */149export const patchRows = (diff: FileDiffMetadata): readonly PatchRow[] => {150 const rows: PatchRow[] = [];151152 for (const hunk of diff.hunks) {153 if (hunk.collapsedBefore > 0) {154 rows.push({ kind: "separator", lines: hunk.collapsedBefore });155 }156157 let next = hunk.additionStart;158 let old = hunk.deletionStart;159160 for (const content of hunk.hunkContent) {161 if (content.type === "context") {162 for (let line = 0; line < content.lines; line += 1) {163 rows.push({164 kind: "context",165 number: next,166 text: bare(diff.additionLines[content.additionLineIndex + line]),167 });168 next += 1;169 old += 1;170 }171 } else {172 for (let line = 0; line < content.deletions; line += 1) {173 rows.push({174 kind: "deletion",175 number: old,176 text: bare(diff.deletionLines[content.deletionLineIndex + line]),177 });178 old += 1;179 }180181 for (let line = 0; line < content.additions; line += 1) {182 rows.push({183 kind: "addition",184 number: next,185 text: bare(diff.additionLines[content.additionLineIndex + line]),186 });187 next += 1;188 }189 }190 }191 }192193 return rows;194};195196/** The new file's line numbers a diff draws: where an annotation at a line can sit. */197export const drawnLines = (diff: FileDiffMetadata): ReadonlySet<number> =>198 new Set(199 patchRows(diff).flatMap((row) =>200 row.kind === "addition" || row.kind === "context" ? [row.number] : []201 )202 );
added:apps/web/src/features/finish/finish-files-button.tsx+40 added
added:apps/web/src/features/finish/finish-files-sheet.tsx+44 added
added:apps/web/src/features/finish/finish-files.tsx+135 added
1/**2 * A finish's changed files as a list the rail (or, below the shell's3 * width, a sheet) holds: the ask's territory first, then tests, then the4 * rest, each a row with its change as a letter (A, M or D, in the diff's5 * tints), its path, its `+n −m`, whether this reader marked it read (a6 * muted check, the word for a screen reader) and whether a refusal pointed7 * into it (the refused cross). Choosing one scrolls the diff to it.8 */9import { Check, OctagonX } from "lucide-react";1011import { diffAnchor } from "../code/paths.ts";12import { ChangeCounts } from "../code/plain-diff.tsx";13import { AppLink } from "../shared/link.tsx";14import type { Part, PatchFile } from "./files.ts";1516const LETTERS = {17 added: { letter: "A", tone: "text-diff-add-sign", word: "added" },18 deleted: { letter: "D", tone: "text-diff-del-sign", word: "deleted" },19 modified: { letter: "M", tone: "text-muted-foreground", word: "modified" },20} as const;2122const PART_NAMES = {23 other: "Everything else",24 territory: "In the territory",25 tests: "Tests",26} as const satisfies Record<Part, string>;2728/** A path as two parts: its name first, then its folder, muted, which gives way first. */29const PathWords = ({ path }: { readonly path: string }) => {30 const slash = path.lastIndexOf("/");3132 return (33 <span className="flex min-w-0 flex-1 items-baseline gap-1.5" title={path}>34 <span className="shrink-0">{path.slice(slash + 1)}</span>35 {slash === -1 ? null : (36 <span className="text-label text-muted-foreground min-w-0 truncate font-normal">37 {path.slice(0, slash)}38 </span>39 )}40 </span>41 );42};4344export const FinishFileList = ({45 current,46 files,47 href,48 read,49 refused,50}: {51 readonly files: readonly PatchFile[];52 /** The page's own address, which each row adds its file's anchor to. */53 readonly href: string;54 readonly read: ReadonlySet<string>;55 readonly refused: ReadonlySet<string>;56 /** The file the diff stands at. */57 readonly current?: string | undefined;58}) => (59 <nav60 aria-label="Changed files"61 className="flex min-h-0 flex-col overflow-y-auto py-2"62 >63 {(["territory", "tests", "other"] as const).map((part) => {64 const mine = files.filter((file) => file.part === part);6566 return mine.length === 0 ? null : (67 <section68 aria-label={PART_NAMES[part]}69 className="flex flex-col"70 key={part}71 >72 <h3 className="text-label text-muted-foreground px-3 pt-2 pb-1">73 {PART_NAMES[part]}74 </h3>75 <ul className="flex flex-col">76 {mine.map((file) => {77 const { letter, tone, word } = LETTERS[file.file.status];78 const isRead = read.has(file.file.path);79 const isRefused = refused.has(file.file.path);8081 return (82 <li83 data-file={file.file.path}84 data-read={isRead}85 key={file.file.path}86 >87 <AppLink88 aria-current={89 current === file.file.path ? "true" : undefined90 }91 className="text-ui hover:bg-surface aria-[current=true]:bg-surface flex h-8 items-center gap-2 px-3 no-underline transition-colors duration-[120ms]"92 hash={diffAnchor(file.file.path)}93 replace94 resetScroll={false}95 to={href}96 >97 <span98 aria-hidden="true"99 className={`text-mono w-3 shrink-0 font-mono font-semibold ${tone}`}100 >101 {letter}102 </span>103 <span className="sr-only">{word}:</span>104 <PathWords path={file.file.path} />105 {isRefused ? (106 <span className="text-refused flex shrink-0 items-center">107 <OctagonX108 aria-hidden="true"109 className="size-3.5"110 strokeWidth={1.75}111 />112 <span className="sr-only">, refused here</span>113 </span>114 ) : null}115 {isRead ? (116 <span className="text-muted-foreground flex shrink-0 items-center">117 <Check118 aria-hidden="true"119 className="size-3.5"120 strokeWidth={1.75}121 />122 <span className="sr-only">, read</span>123 </span>124 ) : null}125 <ChangeCounts {...file.counts} header />126 </AppLink>127 </li>128 );129 })}130 </ul>131 </section>132 );133 })}134 </nav>135);
added:apps/web/src/features/finish/finish-plain.tsx+209 added
1/**2 * A decider's diff as plain text: what the server sends, and what a reader3 * sees until the browser has drawn the highlighted diff over it (or, on a4 * phone, the one file being read). It takes the code browser's measures5 * (a 44 px sticky file header, 13 px code on 20 px lines, the gutter, the6 * sign column, the diff's own tints), so the drawing arrives in place.7 *8 * Under a line it draws what the page puts there (a refusal that pointed9 * at it, a marker waiting on a decision); a note whose line the diff does10 * not show sits at the top of its file, saying which line it means.11 */12import { Option } from "effect";13import type { ReactNode } from "react";1415import { diffAnchor } from "../code/paths.ts";16import { FileHeaderLine } from "../code/plain-diff.tsx";17import { drawnLines, patchRows } from "./files.ts";18import type { PatchFile, PatchLine } from "./files.ts";19import { MarkRead } from "./mark-read.tsx";20import type { MarkedFile } from "./read-marks.ts";2122/** Something drawn under one line of one file. */23export interface LineNote {24 readonly path: string;25 readonly line: number;26 readonly node: ReactNode;27}2829const TONES = {30 addition: {31 line: "bg-diff-add-bg",32 number: "bg-diff-add-bg text-diff-add-sign",33 },34 context: { line: "", number: "text-muted-foreground" },35 deletion: {36 line: "bg-diff-del-bg",37 number: "bg-diff-del-bg text-diff-del-sign",38 },39} as const satisfies Record<40 PatchLine["kind"],41 { readonly line: string; readonly number: string }42>;4344const SIGNS = { addition: "+", context: " ", deletion: "-" } as const;4546const GUTTER =47 "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";4849/** The notes on one file: under a line it draws, and those it does not. */50const notesFor = (file: PatchFile, notes: readonly LineNote[]) => {51 const mine = notes.filter(({ path }) => path === file.file.path);5253 const shown = Option.match(file.diff, {54 onNone: () => new Set<number>(),55 onSome: drawnLines,56 });5758 return {59 at: (line: number) =>60 mine.filter((note) => note.line === line && shown.has(line)),61 elsewhere: mine.filter(({ line }) => !shown.has(line)),62 };63};6465/** One file's lines, with its notes under theirs. */66const Lines = ({67 file,68 notes,69}: {70 readonly file: PatchFile;71 readonly notes: ReturnType<typeof notesFor>;72}) =>73 Option.match(file.diff, {74 onNone: () => (75 <p className="text-ui text-muted-foreground px-4 pb-3 font-sans">76 {file.file.binary ? "A binary file" : "No lines changed"},{" "}77 {file.file.status}.78 </p>79 ),80 onSome: (diff) => (81 <div className="overflow-x-auto pb-2">82 <code className="grid min-w-full grid-cols-[min-content_1fr]">83 {patchRows(diff).map((row, index) =>84 row.kind === "separator" ? (85 <div86 className="bg-surface text-muted-foreground col-span-2 my-2 flex h-8 items-center px-[2ch] font-sans first:mt-0"87 data-separator="line-info"88 key={`s${index}`}89 >90 {row.lines} unmodified {row.lines === 1 ? "line" : "lines"}91 </div>92 ) : (93 <span94 className="contents"95 key={`${row.kind}${row.number}:${index}`}96 >97 <span className={`${GUTTER} ${TONES[row.kind].number}`}>98 {row.number}99 </span>100 <span101 className={`pr-[1ch] whitespace-pre ${TONES[row.kind].line}`}102 data-line={row.number}103 data-line-type={row.kind}104 >105 <span106 aria-hidden="true"107 className="inline-block w-[2ch] select-none"108 >109 {SIGNS[row.kind]}110 </span>111 {row.text}112 </span>113 {row.kind === "deletion"114 ? null115 : notes.at(row.number).map((note) => (116 <div117 className="col-span-2 whitespace-normal"118 data-note-line={note.line}119 key={`${note.path}:${note.line}`}120 >121 {note.node}122 </div>123 ))}124 </span>125 )126 )}127 </code>128 </div>129 ),130 });131132export const FinishPlainDiff = ({133 files,134 folded,135 notes,136 onFold,137 onMark,138 read,139 refused,140}: {141 readonly files: readonly PatchFile[];142 readonly notes: readonly LineNote[];143 /** The files this reader marked read; each header offers "Mark read" when given. */144 readonly read?: ReadonlySet<string> | undefined;145 readonly onMark?: ((file: MarkedFile, read: boolean) => void) | undefined;146 /** The files a refusal points into, marked in their headers. */147 readonly refused?: ReadonlySet<string> | undefined;148 readonly folded?: ReadonlySet<string> | undefined;149 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;150}) => (151 <div className="text-mono leading-code font-mono" data-diff="plain">152 {files.map((file) => {153 const { path } = file.file;154 const closed = folded === undefined ? file.folded : folded.has(path);155 const mine = notesFor(file, notes);156157 return (158 <section159 aria-label={path}160 data-file={path}161 data-folded={closed}162 data-part={file.part}163 data-refused={refused?.has(path) === true ? "" : undefined}164 id={diffAnchor(path)}165 key={path}166 >167 <details168 className="group/file"169 onToggle={(event) => {170 onFold?.(path, !event.currentTarget.open);171 }}172 open={!closed}173 >174 <summary175 className="border-rule bg-background text-mono hover:bg-surface sticky top-0 z-[1] flex h-11 cursor-pointer list-none items-center gap-2 border-y px-4 font-sans [&::-webkit-details-marker]:hidden"176 data-diffs-header=""177 >178 <FileHeaderLine179 end={180 read === undefined ? undefined : (181 <MarkRead182 file={file}183 onMark={onMark}184 read={read.has(path)}185 />186 )187 }188 file={file}189 />190 </summary>191 {mine.elsewhere.map((note) => (192 <div193 className="font-sans"194 data-note-line={note.line}195 key={`${note.path}:${note.line}:elsewhere`}196 >197 <p className="text-label text-muted-foreground px-4 pt-2 font-normal">198 At line {note.line}, outside the lines this diff shows:199 </p>200 {note.node}201 </div>202 ))}203 <Lines file={file} notes={mine} />204 </details>205 </section>206 );207 })}208 </div>209);
added:apps/web/src/features/finish/finish-rail-body.tsx+111 added
1/**2 * A finish's changed files, for the rail (`finish-rail.tsx`, which loads3 * this in the browser) and, below the shell's width, a sheet behind a4 * Files button in the diff's toolbar: territory first, each with its5 * change, its counts, this reader's read mark and the refused cross.6 *7 * Both read the page's own loader data (its match), so the list and the8 * diff come from one read, and the read marks from one store.9 */10import { DecisionSubject } from "@repo/protocol/domain/decision";11import { useLocation, useMatch } from "@tanstack/react-router";12import { Option, Schema } from "effect";13import { useMemo } from "react";1415import { parseDiffHash } from "../code/line-hash.ts";16import { DecisionPageData, DecisionRead } from "../decision/decision-page.tsx";17import { patchFiles } from "./files.ts";18import { FinishFileList } from "./finish-files.tsx";19import { patchOf } from "./patch.ts";20import { marksKey, useReadMarks } from "./read-marks.ts";2122const decode = Schema.decodeUnknownOption(DecisionPageData);2324/** The finish on the page, its files in order; none for any other page. */25export const useFinish = () => {26 const data: unknown = useMatch({27 from: "/$project/decisions/$decision",28 select: (match) => match.loaderData,29 shouldThrow: false,30 });3132 return useMemo(33 () =>34 Option.flatMap(decode(data), ({ read }) => {35 if (!DecisionRead.guards.Found(read)) {36 return Option.none();37 }3839 const { decision } = read;4041 if (!DecisionSubject.guards.Finish(decision.subject)) {42 return Option.none();43 }4445 const { head } = decision.subject;4647 return Option.map(patchOf(decision), (patch) => ({48 files: patchFiles(49 patch,50 read.ask?.territory.paths ?? [],51 `${decision.project}/${decision.id}/${head}`52 ),53 head,54 key: marksKey(decision.project, decision.id),55 refused: new Set(read.placed.map(({ path }) => path)),56 }));57 }),58 [data]59 );60};6162export type Finish = Option.Option.Value<ReturnType<typeof useFinish>>;6364/** The finish's files, with this reader's marks and the file the diff stands at. */65export const FinishFiles = ({ finish }: { readonly finish: Finish }) => {66 const marked = useMemo(67 () =>68 finish.files.map(({ file, patchId }) => ({ patchId, path: file.path })),69 [finish.files]70 );7172 const { read } = useReadMarks(finish.key, finish.head, marked);73 const href = useLocation({ select: ({ pathname }) => pathname });7475 const current = useLocation({76 select: ({ hash }) =>77 Option.getOrUndefined(78 Option.map(parseDiffHash(hash), ({ path }) => path)79 ),80 });8182 const readCount = finish.files.filter(({ file }) =>83 read.has(file.path)84 ).length;8586 return (87 <>88 <p className="border-rule text-label text-muted-foreground flex h-10 shrink-0 items-center border-b px-3 font-normal tabular-nums">89 {finish.files.length} {finish.files.length === 1 ? "file" : "files"}{" "}90 changed · {readCount} read91 </p>92 <FinishFileList93 current={current}94 files={finish.files}95 href={href}96 read={read}97 refused={finish.refused}98 />99 </>100 );101};102103/** The finish's changed files, in the rail's slot. */104export const FinishRailFiles = () =>105 Option.match(useFinish(), {106 onNone: () => null,107 onSome: (found) => <FinishFiles finish={found} />,108 });109110// `React.lazy` takes a module's default export.111export default FinishRailFiles;
added:apps/web/src/features/finish/finish-rail.tsx+82 added
1/**2 * The rail of a decision's page. A route's `staticData` loads with every3 * page, so this module stays light: it tells a finish from any other4 * decision by the shape of the page's data alone, holds the way back to5 * Today and to who decides for any other, and for a finish loads its6 * changed files in the browser7 * (`finish-rail-body.tsx`), with the list's place held until they come.8 */9import { ClientOnly, useMatch } from "@tanstack/react-router";10import { Option, Schema } from "effect";11import { lazy, Suspense } from "react";1213import { AppLink } from "../shared/link.tsx";14import { RailSlot } from "../shared/shell/rail-slot.tsx";1516/** A finish's page data, by its shape: found, and about a finish. */17const FinishPageData = Schema.Struct({18 read: Schema.TaggedStruct("Found", {19 decision: Schema.Struct({20 subject: Schema.TaggedStruct("Finish", {}),21 }),22 }),23});2425const isFinishPage = Schema.decodeUnknownOption(FinishPageData);2627/** A row of the slot, as the rail draws its rows. */28const ROW =29 "text-ui text-foreground hover:bg-surface mx-2 flex h-8 min-w-0 items-center px-2 no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px]";3031const Body = import.meta.env.SSR32 ? undefined33 : lazy(() => import("./finish-rail-body.tsx"));3435/** The list's place: its count line's height, until the list is drawn. */36const Placeholder = () => (37 <div aria-hidden="true" className="border-rule h-10 shrink-0 border-b" />38);3940export const FinishRail = () => {41 const data: unknown = useMatch({42 from: "/$project/decisions/$decision",43 select: (match) => match.loaderData,44 shouldThrow: false,45 });4647 const project = useMatch({48 from: "/$project/decisions/$decision",49 select: (match) => match.params.project,50 shouldThrow: false,51 });5253 return Option.match(isFinishPage(data), {54 onNone: () => (55 <RailSlot label="Decisions">56 <div className="flex flex-col py-2">57 <AppLink className={ROW} to="/today">58 Today59 </AppLink>60 {project === undefined ? null : (61 <AppLink className={ROW} to={`/${project}/people`}>62 Who decides in {project}63 </AppLink>64 )}65 </div>66 </RailSlot>67 ),68 onSome: () => (69 <RailSlot label="Changed files">70 {Body === undefined ? (71 <Placeholder />72 ) : (73 <ClientOnly fallback={<Placeholder />}>74 <Suspense fallback={<Placeholder />}>75 <Body />76 </Suspense>77 </ClientOnly>78 )}79 </RailSlot>80 ),81 });82};
modified:apps/web/src/features/finish/finish-view.tsx+589 added-143 removed
1/**2 * A `Finish` decision's page: the answer's diff beside the ask's want and the3 * verdict, and the git lines a decider runs to finish it from their own4 * clone. The web shows the diff and the commands; it never calls `finish`5 * (that contract's surfaces are RPC, MCP and the CLI).2 * A `Finish` decision's page: the one page where a decider reads an3 * answer's diff, laid out as the code browser is. The changed files sit in4 * the rail (territory first, then tests, then the rest); the diff fills5 * main, file by file under sticky headers, each with a "Mark read" button,6 * and a refusal from an earlier round sits under the line it pointed at.7 * The want, the verdict, the choices and the three lines that finish it8 * from a clone sit in the inspector from 1440 px; below that, the choices9 * stay in a bar at the foot of the diff. On a phone the page reads the10 * want, the verdict and the choices first, then the diff one file at a11 * time.12 *7 * What the page reads from the decision's evidence (ASSUMPTION: the platform's8 * `Finish` decisions carry these; nothing opens one yet): `patch`, the answer's13 * The read marks are this browser's alone (`read-marks.ts`). A head pushed14 * to the answer while the page is open says so above the diff, and the15 * diff stays as it was until the reader reloads it.16 *17 * What the page reads from the decision's evidence: `patch`, the answer's18 * unified diff, and `fork`, the name of the answer's fork19 * (`<project>--<ask>--<handle>`), where a finish fetches the head and pushes11 * its commits. Without a patch the page shows the lines and no diff; without a12 * fork it names the fork by the claim fork's pattern and leaves the answerer's13 * handle for the decider to fill in.20 * its commits. Without a patch the page shows the lines and no diff;21 * without a fork it names the fork by the claim fork's pattern and leaves22 * the answerer's handle for the decider to fill in. The web never calls23 * `finish` itself.24 */25import { Brand } from "@repo/brand";26import type { Verdict } from "@repo/protocol/domain/answer";27import type { Ask } from "@repo/protocol/domain/ask";28import type { ChangedFile } from "@repo/protocol/domain/code";29import type { CommitSha } from "@repo/protocol/ids";30import { Array as Arr, Option } from "effect";19import { FileDiff } from "lucide-react";31import type { DateTime } from "effect";32import { ChevronLeft, ChevronRight, FileDiff, RotateCw } from "lucide-react";33import { useState } from "react";34import type { ReactNode } from "react";3522import { LABEL } from "../shared/classes.ts";36import { Button } from "../../components/ui/button.tsx";37import { ClientDiffs } from "../code/client-code.tsx";38import { DiffStatsFacts, DiffToolbar } from "../code/commit-view.tsx";39import { statsOf } from "../code/diff-model.ts";40import { DiffPane, PANE_SCROLLER } from "../code/diff-pane.tsx";41import type { DiffAnnotation, DiffFileSlot } from "../code/diff-view.tsx";42import { shortSha } from "../code/paths.ts";43import { Choices, stuckAboveBar } from "../decision/choices.tsx";44import { DecisionCard, ExpiryLines } from "../decision/decision-card.tsx";45import type { DecideInput } from "../decision/decision-card.tsx";46import { describeSubject } from "../decision/subject.ts";47import { CommandLine } from "../shared/command.tsx";24import { OutcomeView, StageStrip } from "../shared/outcome.tsx";25import { ClientPatchDiffs } from "./client-diff.tsx";26import { changedFiles, FORK_LABEL, patchOf } from "./patch.ts";48import { FactBlock, GateFacts } from "../shared/facts.tsx";49import { AppLink } from "../shared/link.tsx";50import { askPath } from "../shared/paths.ts";51import { GUTTER, Workspace } from "../shared/shell/workspace.tsx";52import { StatusLine } from "../shared/status-line.tsx";53import type { PlacedRefusal } from "./annotation.tsx";54import { RefusalNote } from "./annotation.tsx";55import type { PatchFile } from "./files.ts";56import { FinishPlainDiff } from "./finish-plain.tsx";57import type { LineNote } from "./finish-plain.tsx";58import { MarkRead } from "./mark-read.tsx";59import { FORK_LABEL } from "./patch.ts";60import type { FinishDecision } from "./patch.ts";61import type { MarkedFile } from "./read-marks.ts";6263export { patchOf } from "./patch.ts";6465export type { FinishDecision } from "./patch.ts";6667const LINK = "decoration-rule underline hover:decoration-current";6869/** Where the answer's head lives: its fork's git URL on the platform. */70const remoteOf = (decision: FinishDecision, platformUrl: string) =>71 Arr.findFirst(decision.evidence, ({ label }) => label === FORK_LABEL).pipe(72 Option.map(
4 unmodified lines
77 `${platformUrl}/${decision.project}--${decision.subject.ask}--<answerer>.git`78 )79 );8045/** The lines that take the answer's head into a clone, put the decider's commits on it, and finish it. */46const finishLines = (81/** The three lines that take the answer's head into a clone, put the decider's commits on it, and finish it. */82export const finishLines = (83 decision: FinishDecision,84 platformUrl: string,85 verdict: Verdict | undefined86) => {87 const remote = remoteOf(decision, platformUrl);88 const { ask, head } = decision.subject;89 const base = verdict?.base ?? "<base>";9055 return {56 fetch: [`git fetch ${remote} ${head}`, "git switch --detach FETCH_HEAD"],57 finish: `${Brand.cli} finish ${ask} --project ${decision.project} --base ${base} --head $(git rev-parse HEAD) --requestId finish-$(git rev-parse HEAD) --yes`,58 push: `git push ${remote} HEAD:main`,59 };91 return [92 {93 command: `git fetch ${remote} ${head} && git switch --detach FETCH_HEAD`,94 label: "Fetch the answer's head and stand on it",95 },96 {97 command: `git push ${remote} HEAD:main`,98 label: "Commit your changes on top, then push them onto its fork",99 },100 {101 command: `${Brand.cli} finish ${ask} --project ${decision.project} --base ${base} --head $(git rev-parse HEAD) --requestId finish-$(git rev-parse HEAD) --yes`,102 label: "Hand the finish to the gate: it lands with you as Finished-by",103 },104 ] as const;105};10662const SECTION = "flex flex-col gap-3";107/** The three finish lines, numbered, each under what it does. */108const FinishLines = ({109 decision,110 platformUrl,111 verdict,112}: {113 readonly decision: FinishDecision;114 readonly platformUrl: string;115 readonly verdict: Verdict | undefined;116}) => (117 <FactBlock label="Finish it from your clone">118 <ol className="flex flex-col gap-3" data-finish-lines="">119 {finishLines(decision, platformUrl, verdict).map(({ command, label }) => (120 <li className="flex min-w-0 flex-col gap-1" key={command}>121 <p className="text-label text-muted-foreground font-normal">122 {label}123 </p>124 <CommandLine command={command} numbered />125 </li>126 ))}127 </ol>128 <p className="text-ui text-muted-foreground">129 To land the answer as it is, accept the decision instead.130 </p>131 </FactBlock>132);13364const TITLE = "text-base font-semibold";134/** What the ask wants, in one paragraph, and the way to it. */135const WantFacts = ({ ask }: { readonly ask: Ask }) => (136 <FactBlock label="The ask wants">137 <p className="text-want font-normal">{ask.brief.want}</p>138 <AppLink className={`text-ui ${LINK}`} to={askPath(ask.project, ask.id)}>139 The ask <code className="text-mono font-mono">{ask.id}</code>140 </AppLink>141 </FactBlock>142);14366/** How the diff is drawn by default: in the browser, after the page loads. */67const inBrowser = (patch: string) => (68 <ClientPatchDiffs69 fallback={70 <output className="text-muted-foreground block text-sm">71 The diff is drawn in your browser.72 </output>73 }74 patch={patch}75 />144/** The verdict on the head: its line, and the gate's stages in a strip. */145const VerdictFacts = ({ verdict }: { readonly verdict: Verdict }) => (146 <FactBlock label={`Verdict at ${shortSha(verdict.head)}`}>147 <div className="flex flex-col gap-2" data-outcome={verdict.outcome._tag}>148 <StatusLine149 command={false}150 subject={{151 kind: "answer",152 outcome: verdict.outcome,153 project: verdict.project,154 stage: verdict.stage,155 }}156 />157 </div>158 </FactBlock>159);16078const Want = ({ ask }: { readonly ask: Ask }) => (79 <section aria-labelledby="finish-want" className={SECTION}>80 <h3 className={TITLE} id="finish-want">81 What the ask wants82 </h3>83 <p className="max-w-[70ch] text-base">{ask.brief.want}</p>84 <p className="text-sm">85 <a86 className="decoration-rule underline hover:decoration-current"87 href={`/${ask.project}/asks/${ask.id}`}88 >89 The ask <span className="font-mono text-[0.8125rem]">{ask.id}</span> in90 full91 </a>161export interface FinishViewProps {162 readonly decision: FinishDecision;163 readonly ask?: Ask | undefined;164 readonly verdict?: Verdict | undefined;165 readonly platformUrl: string;166 readonly now: DateTime.Utc;167 readonly onDecide: (input: DecideInput) => void;168 readonly busy?: boolean;169 readonly soon?: boolean;170 /** The diff's files, territory first (`patchFiles`); none without a patch. */171 readonly files: readonly PatchFile[];172 /** Refusals from the answer's rounds that point into its files. */173 readonly placed?: readonly PlacedRefusal[];174 /** The head last pushed to the answer, when it is not the one decided on. */175 readonly newerHead?: CommitSha | undefined;176 /** The files this reader marked read. */177 readonly read?: ReadonlySet<string>;178 readonly onMark?: (file: MarkedFile, read: boolean) => void;179 readonly split?: boolean;180 readonly onSplit?: (split: boolean) => void;181 readonly folded?: ReadonlySet<string> | undefined;182 readonly onFold?: (path: string, folded: boolean) => void;183 readonly onFoldAll?: (folded: boolean) => void;184 /** Draw the diff in the browser over the plain text (the page does; a test reads the plain text). */185 readonly draw?: boolean;186 /** The Files button, below the shell's width. */187 readonly filesButton?: ReactNode;188 /** Settle the record's mark: the choice was taken while the page was open. */189 readonly stamp?: boolean;190}191192const NO_FILES: ReadonlySet<string> = new Set();193194const NO_REFUSALS: readonly PlacedRefusal[] = [];195196/** No whole files: a decision's diff comes parsed from its patch. */197const NO_CHANGED: readonly ChangedFile[] = [];198199/** A file's state in its header: a refusal pointed into it, or this reader read it. */200const slotOf = (201 path: string,202 header: ReactNode,203 refused: ReadonlySet<string>,204 read: ReadonlySet<string>205): DiffFileSlot => {206 if (refused.has(path)) {207 return { header, path, status: "refused" };208 }209210 return read.has(path) ? { header, path, status: "read" } : { header, path };211};212213/** The refusals among `placed`, as notes under their lines. */214const refusalNotes = (placed: readonly PlacedRefusal[]): readonly LineNote[] =>215 placed.map((each) => ({216 line: each.line,217 node: <RefusalNote placed={each} />,218 path: each.path,219 }));220221/** A head pushed after the one the decision names: said above the diff, never swapped in. */222const NewerHead = ({ head }: { readonly head: CommitSha }) => (223 <output224 className={`border-rule bg-surface flex flex-wrap items-center gap-x-3 gap-y-2 border-b py-2 ${GUTTER}`}225 data-newer-head={head}226 >227 <p className="text-ui">228 A new answer was pushed, at{" "}229 <code className="text-mono font-mono">{shortSha(head)}</code>. This diff230 is the one the decision names.231 </p>93 </section>232 <Button233 onClick={() => {234 globalThis.location.reload();235 }}236 size="sm"237 variant="outline"238 >239 <RotateCw aria-hidden="true" strokeWidth={1.75} />240 Reload the diff241 </Button>242 </output>243);24496const VerdictPart = ({ verdict }: { readonly verdict: Verdict }) => (97 <section aria-labelledby="finish-verdict" className={SECTION}>98 <h3 className={TITLE} id="finish-verdict">99 Verdict at{" "}100 <code className="font-mono text-base">{verdict.head.slice(0, 7)}</code>101 </h3>102 <OutcomeView outcome={verdict.outcome} />103 <StageStrip outcome={verdict.outcome} stage={verdict.stage} />245/** The choices kept at the foot of the diff below 1440 px, where the inspector is a sheet. */246const DecisionBar = ({247 busy,248 decision,249 now,250 onDecide,251 soon,252}: {253 readonly decision: FinishDecision;254 readonly busy: boolean;255 readonly now: DateTime.Utc;256 readonly onDecide: (input: DecideInput) => void;257 readonly soon: boolean;258}) => (259 <section260 aria-label="Your choice"261 className="border-rule bg-background codefacts:hidden flex shrink-0 flex-wrap items-start gap-x-6 gap-y-2 border-t px-4 py-3"262 data-decision-bar=""263 >264 <div className="min-w-0 flex-1 basis-56">265 <ExpiryLines decision={decision} now={now} soon={soon} />266 </div>267 <div className="max-w-[34rem] min-w-0 flex-[2] basis-80">268 <Choices269 busy={busy}270 decision={decision}271 onChoose={(choice) => {272 onDecide({273 choice,274 decision: decision.id,275 project: decision.project,276 });277 }}278 />279 </div>280 </section>281);282107const Diff = ({108 diff,109 patch,283/** On a phone: the diff one file at a time, with the way to the next and the one before. */284const OneFileAtATime = ({285 files,286 notes,287 onMark,288 read,289}: {111 readonly diff: (patch: string) => ReactNode;112 readonly patch: string;290 readonly files: readonly PatchFile[];291 readonly notes: readonly LineNote[];292 readonly read: ReadonlySet<string>;293 readonly onMark?: ((file: MarkedFile, read: boolean) => void) | undefined;294}) => {114 const files = changedFiles(patch);295 const [open, setOpen] = useState(false);296 const [at, setAt] = useState(0);297 const file = files[at];298299 if (!open || file === undefined) {300 return (301 <Button302 className="h-11 w-full"303 disabled={files.length === 0}304 onClick={() => {305 setOpen(true);306 }}307 variant="outline"308 >309 <FileDiff aria-hidden="true" strokeWidth={1.75} />310 Read the diff ({files.length} {files.length === 1 ? "file" : "files"})311 </Button>312 );313 }314315 return (117 <section aria-labelledby="finish-diff" className={SECTION}>118 <h3 className={TITLE} id="finish-diff">119 The answer&apos;s diff120 </h3>121 <div className="flex flex-col gap-1.5">122 <h4 className={LABEL}>123 {files.length} {files.length === 1 ? "file" : "files"} changed124 </h4>125 <ul126 className="flex flex-col gap-0.5 font-mono text-[0.8125rem] leading-6"127 data-diff="files"316 <section317 aria-label="The diff, one file at a time"318 className="-mx-4 flex flex-col"319 >320 <div className="flex items-center justify-between gap-2 px-4 pb-2">321 <Button322 className="h-11"323 disabled={at === 0}324 onClick={() => {325 setAt(at - 1);326 }}327 variant="outline"328 >129 {files.map((file) => (130 <li131 className="flex items-start gap-2 [overflow-wrap:anywhere]"132 key={file}133 >134 <FileDiff135 aria-hidden="true"136 className="text-muted-foreground mt-1 size-3.5 shrink-0"137 />138 {file}139 </li>140 ))}141 </ul>329 <ChevronLeft aria-hidden="true" strokeWidth={1.75} />330 Previous file331 </Button>332 <p className="text-label text-muted-foreground tabular-nums">333 {at + 1} of {files.length}334 </p>335 <Button336 className="h-11"337 disabled={at === files.length - 1}338 onClick={() => {339 setAt(at + 1);340 }}341 variant="outline"342 >343 Next file344 <ChevronRight aria-hidden="true" strokeWidth={1.75} />345 </Button>346 </div>143 {diff(patch)}347 <FinishPlainDiff348 files={[file]}349 folded={NO_FILES}350 notes={notes}351 onMark={onMark}352 read={read}353 />354 </section>355 );356};357148const Lines = ({358/** The diff from a tablet's width: plain from the server, drawn over in the browser, the choices at its foot. */359const WideDiff = ({360 busy,361 decision,150 platformUrl,151 verdict,152}: {153 readonly decision: FinishDecision;154 readonly platformUrl: string;155 readonly verdict: Verdict | undefined;156}) => {157 const lines = finishLines(decision, platformUrl, verdict);362 draw,363 files,364 folded,365 newerHead,366 now,367 onDecide,368 onFold,369 onMark,370 placed,371 read,372 soon,373 split,374}: Required<375 Pick<376 FinishViewProps,377 | "busy"378 | "decision"379 | "draw"380 | "files"381 | "now"382 | "onDecide"383 | "placed"384 | "read"385 | "soon"386 | "split"387 >388> &389 Pick<FinishViewProps, "folded" | "newerHead" | "onFold" | "onMark">) => {390 const refused = new Set(placed.map(({ path }) => path));391392 const plain = (393 <div className={PANE_SCROLLER}>394 <FinishPlainDiff395 files={files}396 folded={folded}397 notes={refusalNotes(placed)}398 onFold={onFold}399 onMark={onMark}400 read={read}401 refused={refused}402 />403 </div>404 );405406 const annotations = placed.map((each): DiffAnnotation => ({407 line: each.line,408 path: each.path,409 render: () => <RefusalNote placed={each} />,410 side: "additions",411 }));412413 const slots = files.map((each) =>414 slotOf(415 each.file.path,416 <MarkRead file={each} onMark={onMark} read={read.has(each.file.path)} />,417 refused,418 read419 )420 );421422 return (160 <section aria-labelledby="finish-lines" className={SECTION}>161 <h3 className={TITLE} id="finish-lines">162 Finish it from your clone163 </h3>164 <ol className="flex flex-col gap-4 text-sm">165 <li className="flex flex-col gap-2">166 <p>Fetch the answer&apos;s head and stand on it:</p>167 {lines.fetch.map((line) => (168 <CommandLine command={line} key={line} />169 ))}170 </li>171 <li className="flex flex-col gap-2">172 <p>173 Commit your changes on top, then push them onto the answer&apos;s174 fork:175 </p>176 <CommandLine command={lines.push} />177 </li>178 <li className="flex flex-col gap-2">179 <p>180 Hand the finish to the gate. It is checked again, and lands with you181 as <span className="font-mono">Finished-by</span>:182 </p>183 <CommandLine command={lines.finish} />184 </li>185 </ol>186 <p className="text-muted-foreground text-sm">187 To land the answer as it is, accept the decision instead.188 </p>189 </section>423 <div className="tablet:contents hidden">424 {newerHead === undefined ? null : <NewerHead head={newerHead} />}425 <DiffPane>426 {draw ? (427 <ClientDiffs428 annotations={annotations}429 drawn={files}430 fallback={plain}431 files={NO_CHANGED}432 folded={folded}433 onFold={onFold}434 slots={slots}435 split={split}436 />437 ) : (438 plain439 )}440 <DecisionBar441 busy={busy}442 decision={decision}443 now={now}444 onDecide={onDecide}445 soon={soon}446 />447 </DiffPane>448 </div>449 );450};451193export const FinishView = ({452/** On a phone: the want, the verdict and the choices first, then the diff a file at a time. */453const PhoneFinish = ({454 ask,455 busy,456 decision,196 diff = inBrowser,457 files,458 newerHead,459 now,460 onDecide,461 onMark,462 placed,463 read,464 soon,465 stamp,466 verdict,467}: Required<468 Pick<469 FinishViewProps,470 | "busy"471 | "decision"472 | "files"473 | "now"474 | "onDecide"475 | "placed"476 | "read"477 | "soon"478 | "stamp"479 >480> &481 Pick<FinishViewProps, "ask" | "newerHead" | "onMark" | "verdict">) => (482 <div className={`tablet:hidden flex flex-col gap-6 ${GUTTER}`}>483 {ask === undefined ? null : (484 <p className="text-want max-w-[70ch]">{ask.brief.want}</p>485 )}486 {verdict === undefined ? null : (487 <div data-outcome={verdict.outcome._tag}>488 <StatusLine489 command={false}490 subject={{491 kind: "answer",492 outcome: verdict.outcome,493 project: verdict.project,494 stage: verdict.stage,495 }}496 />497 </div>498 )}499 {newerHead === undefined ? null : <NewerHead head={newerHead} />}500 <DecisionCard501 busy={busy}502 choices={stuckAboveBar}503 decision={decision}504 finishLink={false}505 now={now}506 onDecide={onDecide}507 soon={soon}508 stamp={stamp}509 />510 {files.length === 0 ? null : (511 <OneFileAtATime512 files={files}513 notes={refusalNotes(placed)}514 onMark={onMark}515 read={read}516 />517 )}518 </div>519);520521/** The inspector's facts: the want, the verdict, the decision, the lines that finish it, the diff's stats. */522const FinishFacts = ({523 ask,524 busy,525 decision,526 files,527 now,528 onDecide,529 platformUrl,530 soon,531 stamp,532 verdict,199}: {200 readonly decision: FinishDecision;201 readonly ask?: Ask | undefined;202 readonly verdict?: Verdict | undefined;203 readonly platformUrl: string;204 /** How the diff is drawn: in the browser by default; a test draws it in place. */205 readonly diff?: (patch: string) => ReactNode;206}) => {207 const patch = patchOf(decision);533}: Required<534 Pick<535 FinishViewProps,536 | "busy"537 | "decision"538 | "files"539 | "now"540 | "onDecide"541 | "platformUrl"542 | "soon"543 | "stamp"544 >545> &546 Pick<FinishViewProps, "ask" | "verdict">) => (547 <>548 {ask === undefined ? null : <WantFacts ask={ask} />}549 {verdict === undefined ? null : <VerdictFacts verdict={verdict} />}550 {verdict === undefined ? null : (551 <GateFacts552 holds={{ decided: false, heldBack: verdict.heldBack.length > 0 }}553 outcome={verdict.outcome}554 stage={verdict.stage}555 />556 )}557 <FactBlock label="Decision">558 <DecisionCard559 busy={busy}560 decision={decision}561 finishLink={false}562 layout="stack"563 now={now}564 onDecide={onDecide}565 soon={soon}566 stamp={stamp}567 />568 </FactBlock>569 <FinishLines570 decision={decision}571 platformUrl={platformUrl}572 verdict={verdict}573 />574 {files.length === 0 ? null : (575 <DiffStatsFacts stats={statsOf(files, ask?.territory.paths ?? [])} />576 )}577 </>578);579580export const FinishView = ({581 busy = false,582 draw = false,583 placed = NO_REFUSALS,584 read = NO_FILES,585 soon = false,586 split = false,587 stamp = false,588 ...props589}: FinishViewProps) => {590 const { ask, decision, files, folded, now } = props;591 const stats = statsOf(files, ask?.territory.paths ?? []);592 const readCount = files.filter(({ file }) => read.has(file.path)).length;593594 const subject = {595 decision,596 kind: "decision",597 now,598 viewerDecides: true,599 } as const;600601 const allFolded =602 files.length > 0 &&603 files.every((file) =>604 folded === undefined ? file.folded : folded.has(file.file.path)605 );606607 const shared = { busy, placed, read, soon, stamp };608609 return (210 <>211 {ask === undefined ? null : <Want ask={ask} />}212 {verdict === undefined ? null : <VerdictPart verdict={verdict} />}213 {Option.isSome(patch) ? <Diff diff={diff} patch={patch.value} /> : null}214 <Lines decision={decision} platformUrl={platformUrl} verdict={verdict} />215 </>610 <Workspace611 crumbs={[612 { label: decision.project, to: `/${decision.project}` },613 { label: "Today", to: "/today" },614 { label: decision.id, mono: true },615 ]}616 facts={<FinishFacts {...props} {...shared} />}617 factsHeading="This finish"618 meta={619 <>620 {decision.project} · finish ·{" "}621 <code className="text-mono font-mono">{decision.id}</code>622 </>623 }624 state={<StatusLine compact subject={subject} />}625 status={<StatusLine subject={subject} />}626 title={describeSubject(decision.subject)}627 toolbar={628 files.length === 0 ? undefined : (629 <>630 <DiffToolbar631 allFolded={allFolded}632 files={props.filesButton}633 onFoldAll={props.onFoldAll}634 onSplit={props.onSplit}635 split={split}636 stats={stats}637 />638 <p639 className="text-ui text-muted-foreground tablet:block hidden shrink-0 tabular-nums"640 data-read-count={readCount}641 >642 {readCount} of {files.length}{" "}643 {files.length === 1 ? "file" : "files"} read644 </p>645 </>646 )647 }648 variant="code"649 >650 <PhoneFinish {...props} {...shared} />651 {files.length === 0 ? (652 <p653 className={`text-ui text-muted-foreground tablet:block hidden ${GUTTER}`}654 >655 This decision carries no diff: fetch the answer&apos;s head to read656 it, with the first line in Facts.657 </p>658 ) : (659 <WideDiff {...props} {...shared} draw={draw} split={split} />660 )}661 </Workspace>662 );663};
added:apps/web/src/features/finish/mark-read.tsx+39 added
deleted:apps/web/src/features/finish/patch-diff.tsx-46 removed
1/**2 * An answer's diff, drawn by `@pierre/diffs`: one stacked (unified) view per3 * changed file, its lines wrapped rather than scrolled sideways, so a phone4 * reads it at 360 px. The colours follow the system's light or dark setting,5 * as the rest of the site does.6 *7 * The library and Shiki's grammars are megabytes, so only the browser loads8 * this module (`client-diff.tsx`); the Worker never bundles it.9 */10import { parsePatchFiles } from "@pierre/diffs";11import { FileDiff } from "@pierre/diffs/react";12import type { FileDiffOptions } from "@pierre/diffs/react";13import { useMemo } from "react";1415import { diffsOptions, registerCodeTheme } from "../code/pierre.ts";1617registerCodeTheme();1819const options = {20 ...diffsOptions,21 diffStyle: "unified",22 overflow: "wrap",23} as const satisfies FileDiffOptions<undefined, undefined>;2425export const PatchDiffs = ({ patch }: { readonly patch: string }) => {26 const files = useMemo(27 () => parsePatchFiles(patch).flatMap((parsed) => parsed.files),28 [patch]29 );3031 return (32 <div className="flex flex-col gap-4" data-diff="pierre">33 {files.map((file) => (34 <section35 aria-label={file.name}36 key={`${file.prevName ?? ""}:${file.name}`}37 >38 <FileDiff fileDiff={file} options={options} />39 </section>40 ))}41 </div>42 );43};4445// `React.lazy` takes a module's default export.46export default PatchDiffs;
modified:apps/web/src/features/finish/patch.ts+60 added
91 unmodified lines
92 }9394 return Arr.dedupe(blocks.flatMap((block) => Option.toArray(pathOf(block))));95};9697/** The text of each file's block of a unified diff, by the path it ends up at. */98export const fileBlocks = (patch: string): ReadonlyMap<string, string> => {99 const lines = patch.split("\n");100 const gitHeaders = lines.some((line) => HEADER.test(line));101102 const starts = (line: string, next: string | undefined) =>103 gitHeaders104 ? line.startsWith("diff --git ")105 : OLD_FILE.test(line) && next !== undefined && NEW_FILE.test(next);106107 const blocks: string[][] = [];108109 for (const [index, line] of lines.entries()) {110 if (starts(line, lines[index + 1])) {111 blocks.push([line]);112 } else {113 blocks.at(-1)?.push(line);114 }115 }116117 return new Map(118 blocks.flatMap((block) =>119 Option.toArray(120 Option.map(pathOf(block), (path) => [path, block.join("\n")] as const)121 )122 )123 );124};125126/**127 * A short, stable id for one file's change: a polynomial hash over its128 * block of the diff, kept under a 32-bit prime. A new head that changes129 * the file changes its id, so whatever was kept against the old one no130 * longer matches.131 */132export const patchIdOf = (text: string): string => {133 let hash = 7;134135 for (let index = 0; index < text.length; index += 1) {136 hash = (hash * 31 + (text.codePointAt(index) ?? 0)) % 4_294_967_291;137 }138139 return hash.toString(16).padStart(8, "0");140};141142const waives = DecisionSubject.isAnyOf(["Waiver"]);143144/**145 * The answer's diff a `Waiver` decision carries, when it carries one under146 * the same `patch` label a finish uses: the page draws the marker's file147 * from it, with the marker at its line.148 */149export const waiverPatchOf = (decision: Decision): Option.Option<string> =>150 waives(decision.subject)151 ? Option.map(152 Arr.findFirst(decision.evidence, ({ label }) => label === PATCH_LABEL),153 ({ value }) => value154 ).pipe(Option.filter((patch) => patch.trim().length > 0))155 : Option.none();
added:apps/web/src/features/finish/read-marks.ts+130 added
1/**2 * Which of a finish's files its reader has marked read: kept in this3 * browser alone, never sent anywhere, and about files, never a person. A4 * mark is kept against the decision, the file and that file's change (its5 * patch id), and the whole set against the answer's head: a new head6 * pushed to the answer clears them, and a file whose change differs reads7 * unread.8 *9 * The browser's storage may be missing, full or refused (a private window);10 * every read and write is tried, and a refused one keeps nothing, so the11 * page works the same with no marks.12 *13 * The rail and the diff both show the marks; a change made in one is told14 * to the other with an event on the window.15 */16import { Option, Result, Schema } from "effect";17import { useCallback, useEffect, useState } from "react";1819/** What one decision's marks are kept as. */20const Kept = Schema.Struct({21 head: Schema.String,22 read: Schema.Record(Schema.String, Schema.String),23});2425const decodeKept = Schema.decodeUnknownOption(Schema.fromJsonString(Kept));2627/** Where one decision's marks are kept. */28export const marksKey = (project: string, decision: string) =>29 `finish.read:${project}/${decision}`;3031/** The event a change to the marks is told by. */32const CHANGED = "finish-read-marks";3334/** A file and its change, as a mark is kept against it. */35export interface MarkedFile {36 readonly path: string;37 readonly patchId: string;38}3940/** The paths marked read, at `head`, whose change is still the one marked. */41export const readMarks = (42 storage: Storage | undefined,43 key: string,44 head: string,45 files: readonly MarkedFile[]46): ReadonlySet<string> => {47 const kept = Result.getOrElse(48 Result.try(() => storage?.getItem(key) ?? null),49 () => null50 );5152 return Option.match(Option.flatMap(Option.fromNullishOr(kept), decodeKept), {53 onNone: () => new Set(),54 onSome: ({ head: at, read }) =>55 at === head56 ? new Set(57 files.flatMap(({ patchId, path }) =>58 read[path] === patchId ? [path] : []59 )60 )61 : new Set(),62 });63};6465/** Mark `file` read or unread at `head`; marks kept at another head are dropped. A refused write keeps nothing. */66export const writeMark = (67 storage: Storage | undefined,68 key: string,69 head: string,70 file: MarkedFile,71 read: boolean72): void => {73 const kept = Result.getOrElse(74 Result.try(() => storage?.getItem(key) ?? null),75 () => null76 );7778 const current = Option.getOrUndefined(79 Option.filter(80 Option.flatMap(Option.fromNullishOr(kept), decodeKept),81 (marks) => marks.head === head82 )83 );8485 const { [file.path]: _was, ...others } = current?.read ?? {};86 const next = read ? { ...others, [file.path]: file.patchId } : others;8788 Result.try(() => storage?.setItem(key, JSON.stringify({ head, read: next })));89};9091/** The browser's storage, when there is one this page may use. */92const browserStorage = (): Storage | undefined =>93 Result.getOrUndefined(Result.try(() => globalThis.localStorage));9495/**96 * The marks on `files` at `head`, read once the page runs (the server97 * draws none), and the way to set one. Every view of the same decision98 * hears a change made in another.99 */100export const useReadMarks = (101 key: string,102 head: string,103 files: readonly MarkedFile[],104 storage: () => Storage | undefined = browserStorage105) => {106 const [read, setRead] = useState<ReadonlySet<string>>(new Set());107108 useEffect(() => {109 const load = () => {110 setRead(readMarks(storage(), key, head, files));111 };112113 load();114 globalThis.addEventListener(CHANGED, load);115116 return () => {117 globalThis.removeEventListener(CHANGED, load);118 };119 }, [files, head, key, storage]);120121 const mark = useCallback(122 (file: MarkedFile, on: boolean) => {123 writeMark(storage(), key, head, file, on);124 globalThis.dispatchEvent(new Event(CHANGED));125 },126 [head, key, storage]127 );128129 return { mark, read };130};
modified:apps/web/src/features/proposal/client-file.tsx+1 added-1 removed
34 unmodified lines
35 const fallback = <Plain content={content} />;3637 return (38 <section className="flex min-w-0 flex-col gap-1.5" data-file={path}>39 <Heading className="font-mono text-sm font-medium [overflow-wrap:anywhere]">39 <Heading className="text-mono font-mono font-medium [overflow-wrap:anywhere]">40 {path}41 </Heading>42 {DraftedFileLater === undefined ? (43 fallback
10 unmodified lines
modified:apps/web/src/features/proposal/drafted-file.tsx+2 added
20 unmodified lines
21}2223const options: FileOptions<undefined, undefined> = {24 ...diffsOptions,25 // The path is the section's heading already.26 disableFileHeader: true,27 overflow: "scroll",28};2930export const DraftedFile = ({ content, path }: DraftedFileProps) => {
14 unmodified lines
modified:apps/web/src/features/proposal/failure.tsx+37 added-19 removed
1/**2 * A call the propose and proposal pages sent, failed. A session that ended3 * (or never began) asks the reader to sign in and come back to the same4 * address, so the form or the proposal is where they left it; anything else5 * shows as Today's failures do: the refusal, or that the platform did not6 * answer.4 * address, so the form or the proposal is where they left it; a refusal5 * reads as the platform gave it, through `RefusalView`; anything else is6 * the platform not answering, in ink, never as a refusal.7 */8import { Unauthenticated } from "@repo/protocol/principal";9import { Refusal } from "@repo/protocol/refusal";10import { Cause, Option, Schema } from "effect";11import { LogIn } from "lucide-react";1213import { signInHref } from "../auth/session-slot.tsx";13import { FailureView, Notice } from "../today/today-page.tsx";14import { UnreachableNotice } from "../shared/pending.tsx";15import { RefusalView } from "../shared/refusal.tsx";1617const isUnauthenticated = Schema.is(Unauthenticated);1819const isRefusal = Schema.is(Refusal);2021export const ProposalFailure = ({22 cause,23 doing,24 here,
2 unmodified lines
27 /** What the reader was doing, as "Sign in to …" ends: `propose it`. */28 readonly doing: string;29 /** The page's own address (`hereOf`), where sign-in comes back to. */30 readonly here: string;31}) => {32 const error = Cause.findErrorOption(cause);3334 if (Option.exists(error, isUnauthenticated)) {35 return (36 <p className="border-rule text-ui flex items-start gap-2 border-y py-3">37 <LogIn27}) =>28 Option.exists(Cause.findErrorOption(cause), isUnauthenticated) ? (29 <Notice30 icon={<LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />}31 >32 You are not signed in, or your session has ended.{" "}33 <a34 className="decoration-rule font-medium underline hover:decoration-current"35 href={signInHref(here)}36 >37 Sign in38 </a>{" "}39 to {doing}; you come back to this page.40 </Notice>38 aria-hidden="true"39 className="mt-0.5 size-4 shrink-0"40 strokeWidth={1.75}41 />42 <span>43 You are not signed in, or your session has ended.{" "}44 <a45 className="decoration-rule font-medium underline hover:decoration-current"46 href={signInHref(here)}47 >48 Sign in49 </a>{" "}50 to {doing}; you come back to this page.51 </span>52 </p>53 );54 }5556 return Option.isSome(error) && isRefusal(error.value) ? (57 <RefusalView refusals={[error.value]} />58 ) : (42 <FailureView cause={cause} />59 <UnreachableNotice />60 );61};
modified:apps/web/src/features/proposal/proposal-view.tsx+366 added-151 removed
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`.2 * One proposal, as its proposer and its deciders follow it. The title is3 * its want; under it, where the platform's draft stands in the outcome's4 * words: drafting (the checking role), ready and waiting for a decider (the5 * waiting role), or a failed round, drawn by `RefusalView` when the round6 * failed with a refusal the page can draw whole, else as an ink line. Then7 * the draft read as a guide, in the order it was made: the ask file (its8 * want, territory and kind as rows, its source behind a disclosure), the9 * check (its source), and red first (the run that failed twice the same10 * way, its assertion once).11 *12 * "Let the platform's agent draft it" (or "Draft again"), with a note for13 * the agent, is the proposer's or a decider's while the proposal is open14 * and not drafting; a decider also gets the way to the decision that would15 * open the ask. The inspector holds who proposed it, when it expires, the16 * decision, and the draft's round.17 *18 * Nothing here edits the drafted files: a member proposes again, or a19 * decider sends the draft back with a note.20 */21import { Brand } from "@repo/brand";22import type { ConfigFile } from "@repo/protocol/domain/common";23import { DraftState } from "@repo/protocol/domain/proposal";24import type { Proposal } from "@repo/protocol/domain/proposal";25import type { DecisionId, ProjectName } from "@repo/protocol/ids";18import { Option } from "effect";26import { groups } from "@repo/protocol/refusal";27import type { Refusal } from "@repo/protocol/refusal";28import { Array as Arr, DateTime, Option } from "effect";29import { constVoid } from "effect/Function";20import { CircleCheck, OctagonX, Scale } from "lucide-react";30import { ChevronDown, Scale, X } from "lucide-react";31import { useId, useState } from "react";32import type { ReactNode } from "react";3324import { Badge } from "../../components/ui/badge.tsx";34import { Button } from "../../components/ui/button.tsx";26import { Spinner } from "../../components/ui/spinner.tsx";35import { Textarea } from "../../components/ui/textarea.tsx";28import { LABEL } from "../shared/classes.ts";36import { isTestPath } from "../code/diff-model.ts";37import { FactBlock } from "../shared/facts.tsx";38import { HandleLink } from "../shared/handle.tsx";39import { AppLink } from "../shared/link.tsx";40import { decisionPath } from "../shared/paths.ts";41import { RefusalView } from "../shared/refusal.tsx";42import { Workspace } from "../shared/shell/workspace.tsx";43import { StatusLine } from "../shared/status-line.tsx";44import { When } from "../shared/time.tsx";45import { DraftedCode } from "./client-file.tsx";4647/**48 * How many attempts a draft round makes before it fails: the platform's
18 unmodified lines
67/** Whether the platform's agent is drafting the proposal's ask right now. */68export const isDrafting = (proposal: Proposal) =>69 proposal.draft !== undefined && draftingNow(proposal.draft);7056/** The badge each standing wears: an ending that opened nothing reads as refused. */57const badgeVariant = {58 Drafting: "outline",59 Failed: "destructive",60 Ready: "secondary",61 accepted: "secondary",62 declined: "destructive",63 expired: "destructive",64 open: "secondary",65} as const satisfies Record<ReturnType<typeof standing>, string>;71/** Every refusal of the union, to find one by the tag a failed draft kept. */72const refusalKinds = groups.flatMap(({ members }) => [...members]);7367const StateBadge = ({ proposal }: { readonly proposal: Proposal }) => {68 const word = standing(proposal);74/**75 * The refusal a failed round ended with, when its tag alone makes one: a76 * draft keeps only the tag, so a refusal that needs fields of its own77 * cannot be drawn whole, and is said in words instead.78 */79export const refusalOfTag = (tag: string): Option.Option<Refusal> =>80 Arr.findFirst(refusalKinds, (kind) => kind.identifier === tag).pipe(81 Option.flatMap((kind): Option.Option<Refusal> =>82 // SAFETY: `makeOption` checks its input at run time, so a refusal whose fields all have defaults is made and one that needs a field answers None.83 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a loop over the union's members cannot name each member's input; see SAFETY.84 kind.makeOption({} as never)85 )86 );8788/** Whether a drafted file is the ask file: under the config folder, or named as one. */89const isAskFile = ({ path }: ConfigFile) =>90 path.startsWith(`${Brand.configDir}/`) || path.endsWith(".ask.ts");9192/** The draft's files in the order it made them: the ask file, the check, then what the check reads. */93const filesInOrder = (files: readonly ConfigFile[]) => {94 const askFile = files.find(isAskFile);95 const rest = files.filter((file) => file !== askFile);96 const checks = rest.filter(({ path }) => isTestPath(path));97 const others = rest.filter(({ path }) => !isTestPath(path));9899 return { askFile, checks, others };100};101102/** The kind an ask file names (`kinds.fix`), when it names one plainly. */103const kindIn = (source: string) =>104 /\bkinds\.(?<kind>[A-Za-z]+)/u.exec(source)?.groups?.kind;105106const Step = ({107 children,108 id,109 title,110}: {111 readonly children: ReactNode;112 readonly id: string;113 readonly title: string;114}) => (115 <section aria-labelledby={id} className="flex min-w-0 flex-col gap-3">116 <h2 className="text-title" id={id}>117 {title}118 </h2>119 {children}120 </section>121);122123const Row = ({124 children,125 label,126}: {127 readonly children: ReactNode;128 readonly label: string;129}) => (130 <div className="contents">131 <dt className="text-label text-muted-foreground pt-0.5">{label}</dt>132 <dd className="text-ui min-w-0 [overflow-wrap:anywhere]">{children}</dd>133 </div>134);135136/** The ask file: what it states, then its source behind a disclosure. */137const AskFileStep = ({138 file,139 proposal,140}: {141 readonly file: ConfigFile | undefined;142 readonly proposal: Proposal;143}) => {144 const kind = file === undefined ? undefined : kindIn(file.content);145146 return (71 <Badge data-standing={word} variant={badgeVariant[word]}>72 {word === "Drafting" ? <Spinner className="size-3" /> : null}73 {word}74 </Badge>147 <Step id={`${proposal.id}-ask-file`} title="The ask file">148 <dl className="tablet:grid-cols-[7rem_1fr] grid grid-cols-1 gap-x-4 gap-y-1.5">149 <Row label="Want">{proposal.want}</Row>150 {proposal.territory === undefined ? null : (151 <Row label="Territory">152 <code className="text-mono font-mono">{proposal.territory}</code>153 </Row>154 )}155 {kind === undefined ? null : (156 <Row label="Kind">157 <code className="text-mono font-mono">{kind}</code>158 </Row>159 )}160 </dl>161 {file === undefined ? null : (162 <details className="group">163 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 [&::-webkit-details-marker]:hidden">164 Its source, <code className="text-mono font-mono">{file.path}</code>165 <ChevronDown166 aria-hidden="true"167 className="size-3.5 transition-transform duration-150 group-open:rotate-180"168 strokeWidth={1.75}169 />170 </summary>171 <div className="mt-2">172 <DraftedCode content={file.content} path={file.path} />173 </div>174 </details>175 )}176 </Step>177 );178};17978/** What the draft says: in progress, ready with its red-first run, or failed. */79const DraftFacts = ({ draft }: { readonly draft: DraftState }) =>180/** Red first: the run that failed twice the same way on main, its assertion once. */181const RedFirst = ({ draft }: { readonly draft: DraftState }) =>182 DraftState.match(draft, {81 Drafting: ({ note, round }) => (82 <div className="flex flex-col gap-1 text-sm" data-draft="Drafting">83 <p className="flex items-start gap-2">84 <Spinner className="text-checking mt-0.5 shrink-0" />85 <span>86 Drafting (round {round}): the platform&apos;s agent is writing the87 ask and a check, then running the check on main, where it must fail88 twice the same way. This takes a few minutes; the page follows it.89 </span>183 Drafting: () => null,184 Failed: () => null,185 Ready: ({ attempts, model, red }) => (186 <Step id="red-first" title="Red first">187 <p className="text-ui">188 The check ran on main and fails twice the same way in lane {red.lane}:{" "}189 <span className="sr-only">{red.signature}</span>190 </p>91 {note === undefined ? null : (92 <p93 className="pl-6 [overflow-wrap:anywhere] whitespace-pre-line"94 data-note=""95 >96 <span className={LABEL}>Note:</span> {note}97 </p>98 )}99 </div>100 ),101 Failed: ({ attempts, model, refusal, round }) => (102 <div className="flex flex-col gap-1 text-sm" data-draft="Failed">103 <p className="flex items-start gap-2">104 <OctagonX105 aria-hidden="true"106 className="text-refused mt-0.5 size-4 shrink-0"107 />108 <span>109 The draft failed (round {round}), after {attempts} of{" "}110 {DRAFT_ATTEMPTS} attempts by {model}. The last refusal:{" "}111 <b className="text-refused font-mono font-semibold">{refusal}</b>112 </span>191 <samp192 aria-hidden="true"193 className="border-rule bg-surface text-mono leading-terminal block border px-3 py-2 font-mono [overflow-wrap:anywhere] whitespace-pre-wrap"194 >195 {red.signature}196 </samp>197 <p className="text-label text-muted-foreground font-normal">198 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}199 </p>114 </div>200 </Step>201 ),116 Ready: ({ attempts, model, red }) => (117 <dl118 className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[minmax(8rem,auto)_1fr]"119 data-draft="Ready"120 >121 <dt className={`${LABEL} pt-0.5`}>Red first</dt>122 <dd className="mb-1.5 flex items-start gap-2 [overflow-wrap:anywhere] sm:mb-0">123 <CircleCheck124 aria-hidden="true"125 className="text-landed mt-0.5 size-4 shrink-0"126 />127 <span>128 fails twice the same way in lane {red.lane}: {red.signature}129 </span>130 </dd>131 <dt className={`${LABEL} pt-0.5`}>Drafted by</dt>132 <dd className="mb-1.5 [overflow-wrap:anywhere] sm:mb-0">133 drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}134 </dd>135 </dl>136 ),202 });203204/** A round that failed: the refusal whole when the page can draw it, else in words, in ink. */205const FailedRound = ({ draft }: { readonly draft: DraftState }) =>206 DraftState.match(draft, {207 Drafting: () => null,208 Failed: ({ attempts, model, refusal, round }) =>209 Option.match(refusalOfTag(refusal), {210 onNone: () => (211 <p className="text-want flex items-start gap-2" data-draft="Failed">212 <X213 aria-hidden="true"214 className="mt-1 size-4 shrink-0"215 strokeWidth={1.75}216 />217 <span>218 <strong className="font-semibold">The draft failed:</strong>{" "}219 <code className="text-mono font-mono">{refusal}</code>, in round{" "}220 {round}, after {attempts} of {DRAFT_ATTEMPTS} attempts by {model}.221 </span>222 </p>223 ),224 onSome: (made) => (225 <div className="flex flex-col gap-2" data-draft="Failed">226 <p className="text-ui text-muted-foreground">227 Round {round} failed after {attempts} of {DRAFT_ATTEMPTS} attempts228 by {model}, with:229 </p>230 <RefusalView refusals={[made]} />231 </div>232 ),233 }),234 Ready: () => null,235 });236237/** "Draft again", with a note the agent reads. */238const Redraft = ({239 again,240 busy,
10 unmodified lines
251 <section252 aria-label="Draft again"253 className="border-rule flex flex-col gap-3 border-t pt-4"254 >157 <details className="text-sm">158 <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">255 <details className="group">256 <summary className="text-ui text-muted-foreground hover:text-foreground flex w-fit cursor-pointer list-none items-center gap-1.5 py-1 select-none [&::-webkit-details-marker]:hidden">257 Add a note for the agent258 <ChevronDown259 aria-hidden="true"260 className="size-3.5 transition-transform duration-150 group-open:rotate-180"261 strokeWidth={1.75}262 />263 </summary>161 <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>264 <label265 className="text-label text-muted-foreground mt-2 block"266 htmlFor={noteId}267 >268 What the next draft should do differently269 </label>270 <Textarea165 className="mt-1 text-sm md:text-sm"271 className="tablet:text-ui mt-1 text-base"272 id={noteId}273 maxLength={NOTE_LIMIT}274 onChange={(event) => {275 setNote(event.target.value);
1 unmodified line
277 value={note}278 />279 </details>280 <Button175 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"281 className="tablet:h-9 tablet:w-fit h-11 w-full px-4"282 disabled={busy}283 onClick={() => {284 const written = note.trim();285
15 unmodified lines
301}: {302 readonly decision: DecisionId;303 readonly project: ProjectName;304}) => (199 <a200 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"305 <AppLink306 className="text-ui decoration-rule flex w-fit items-center gap-2 font-medium underline hover:decoration-current"307 data-decision={decision}202 href={`/${project}/decisions/${decision}`}308 to={decisionPath(project, decision)}309 >204 <Scale aria-hidden="true" className="size-4 shrink-0" />310 <Scale aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />311 Decide it: {decision}206 </a>312 </AppLink>313);314315/** The draft's round, in a line: its number and where it stands. */316const roundLine = (draft: DraftState) =>317 DraftState.match(draft, {318 Drafting: ({ round }) => `Round ${round}, drafting now`,319 Failed: ({ attempts, round }) =>320 `Round ${round} failed after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,321 Ready: ({ attempts, round }) =>322 `Round ${round} ready after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,323 });324325/** The inspector's facts: who proposed it, when it expires, its decision, the draft's round. */326const ProposalFacts = ({327 decision,328 now,329 project,330 proposal,331}: {332 readonly decision: Option.Option<DecisionId>;333 readonly now: DateTime.Utc;334 readonly project: ProjectName;335 readonly proposal: Proposal;336}) => (337 <>338 <FactBlock label="Proposal">339 <dl className="text-ui grid grid-cols-[6rem_1fr] gap-x-3 gap-y-1.5">340 <dt className="text-label text-muted-foreground pt-0.5">Proposed by</dt>341 <dd>342 <HandleLink handle={proposal.proposer} />{" "}343 <span className="text-muted-foreground">344 <When at={proposal.openedAt} now={now} />345 </span>346 </dd>347 <dt className="text-label text-muted-foreground pt-0.5">Expires</dt>348 <dd>349 <When at={proposal.expiresAt} now={now} />350 <span className="text-muted-foreground">351 {" "}352 unless a decider opens it353 </span>354 </dd>355 <dt className="text-label text-muted-foreground pt-0.5">State</dt>356 <dd data-standing={standing(proposal)}>{proposal.state}</dd>357 </dl>358 </FactBlock>359 {Option.isSome(decision) ? (360 <FactBlock label="Decision">361 <DecisionLink decision={decision.value} project={project} />362 </FactBlock>363 ) : null}364 {proposal.draft === undefined ? null : (365 <FactBlock label="Drafting">366 <p className="text-ui">{roundLine(proposal.draft)}</p>367 </FactBlock>368 )}369 </>370);371372/** Where the proposal stands, under its title: the status line, or a failed round; then what drafting means and its note. */373const ProposalStatus = ({ proposal }: { readonly proposal: Proposal }) => {374 const { draft } = proposal;375 const drafting = draft !== undefined && draftingNow(draft);376377 return (378 <div379 className="flex flex-col gap-3"380 data-draft={draft?._tag}381 data-proposal={proposal.id}382 data-standing={standing(proposal)}383 >384 {draft !== undefined && failedNow(draft) && proposal.state === "open" ? (385 <FailedRound draft={draft} />386 ) : (387 <StatusLine subject={{ kind: "proposal", proposal }} />388 )}389 {drafting ? (390 <p className="text-ui text-muted-foreground max-w-[70ch]">391 The platform&apos;s agent is writing the ask and a check, then running392 the check on main, where it must fail twice the same way. This takes a393 few minutes; the page follows it.394 </p>395 ) : null}396 {drafting && draft.note !== undefined ? (397 <p398 className="text-ui [overflow-wrap:anywhere] whitespace-pre-line"399 data-note=""400 >401 <span className="text-label text-muted-foreground">Note:</span>{" "}402 {draft.note}403 </p>404 ) : null}405 </div>406 );407};408409/** The draft as a guide, in the order it was made; a want alone says so. */410const DraftGuide = ({411 files,412 proposal,413}: {414 readonly files: readonly ConfigFile[];415 readonly proposal: Proposal;416}) => {417 const { askFile, checks, others } = filesInOrder(files);418 const kept = proposal.draft !== undefined && failedNow(proposal.draft);419420 if (files.length === 0) {421 return proposal.draft === undefined ? (422 <p className="text-body max-w-[70ch]">423 A want alone: no ask file or check yet. A decider who accepts it writes424 the change it asks for.425 </p>426 ) : null;427 }428429 return (430 <>431 {kept ? (432 <p className="text-ui text-muted-foreground" data-kept="">433 An earlier round&apos;s ready draft, which a decider can still accept:434 it runs red first again on main before the ask opens.435 </p>436 ) : null}437 <AskFileStep file={askFile} proposal={proposal} />438 {checks.length === 0 ? null : (439 <Step id={`${proposal.id}-check`} title="The check">440 {[...checks, ...others].map(({ content, path }) => (441 <DraftedCode content={content} key={path} path={path} />442 ))}443 </Step>444 )}445 {proposal.draft === undefined ? null : (446 <RedFirst draft={proposal.draft} />447 )}448 </>449 );450};451452export const ProposalView = ({453 busy = false,454 children,455 decision,456 files,457 mayRedraft,458 now = DateTime.nowUnsafe(),459 onRedraft = constVoid,460 project,461 proposal,462}: {
9 unmodified lines
472 /** Whether a "Draft again" is on its way: the button waits. */473 readonly busy?: boolean;474 /** What the last "Draft again" came back with, when it was refused. */475 readonly children?: ReactNode;476 readonly now?: DateTime.Utc;477}): ReactNode => {478 const open = proposal.state === "open";479480 return (236 <article237 aria-labelledby={`${proposal.id}-want`}238 className="flex max-w-[90ch] min-w-0 flex-col gap-5"239 data-proposal={proposal.id}481 <Workspace482 crumbs={[483 { label: project, to: `/${project}` },484 { label: "Proposals" },485 { label: proposal.id, mono: true },486 ]}487 facts={488 <ProposalFacts489 decision={decision}490 now={now}491 project={project}492 proposal={proposal}493 />494 }495 factsHeading="This proposal"496 meta={497 <>498 proposed by <HandleLink handle={proposal.proposer} /> ·{" "}499 <code className="text-mono font-mono">{proposal.id}</code>500 </>501 }502 state={<StatusLine compact subject={{ kind: "proposal", proposal }} />}503 status={<ProposalStatus proposal={proposal} />}504 title={proposal.want}505 >241 <header className="flex flex-col gap-2">242 <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">243 <span className="font-mono">{project}</span>244 <span aria-hidden="true">·</span>245 <span className="font-mono">{proposal.id}</span>246 <StateBadge proposal={proposal} />247 </p>248 <h2249 className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"250 id={`${proposal.id}-want`}251 >252 {proposal.want}253 </h2>254 <p className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">255 <span>256 Proposed by <HandleLink handle={proposal.proposer} />257 </span>258 {proposal.territory === undefined ? null : (259 <span>260 in <code className="font-mono">{proposal.territory}</code>261 </span>262 )}263 </p>264 </header>265266 {proposal.draft === undefined ? null : (267 <DraftFacts draft={proposal.draft} />268 )}269270 {Option.isSome(decision) ? (506 {Option.isSome(decision) && open ? (507 <DecisionLink decision={decision.value} project={project} />508 ) : null}273274 {files.length === 0 ? null : (275 <section276 aria-labelledby={`${proposal.id}-files`}277 className="flex min-w-0 flex-col gap-4"278 >279 <h2 className="text-base font-semibold" id={`${proposal.id}-files`}>280 {proposal.draft === undefined ? "Proposed files" : "Drafted files"}281 </h2>282 {proposal.draft !== undefined && failedNow(proposal.draft) ? (283 <p className="text-muted-foreground -mt-2 text-sm" data-kept="">284 An earlier round&apos;s ready draft, which a decider can still285 accept: it runs red first again on main before the ask opens.286 </p>287 ) : null}288 {files.map(({ content, path }) => (289 <DraftedCode content={content} key={path} path={path} />290 ))}291 </section>292 )}293509 <DraftGuide files={files} proposal={proposal} />510 {children}295511 {mayRedraft && open && !isDrafting(proposal) ? (512 <Redraft513 again={proposal.draft !== undefined}514 busy={busy}515 onRedraft={onRedraft}516 />517 ) : null}303 </article>518 </Workspace>519 );520};
added:apps/web/src/features/propose/client-territory.tsx+53 added
1/**2 * The territory select, drawn in the browser only. The server renders its3 * stand-in: the trigger as it will look, holding the choice in sight and4 * in the form (a hidden input), never a native `<select>`; after5 * hydration the browser loads the kit's select over it.6 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic7 * import below is dead code there and the Worker bundles none of it.8 */9import { ClientOnly } from "@tanstack/react-router";10import { ChevronDown } from "lucide-react";11import { lazy, Suspense } from "react";1213// A type-only import is erased, so the server bundles nothing of it.14import type { TerritorySelectProps } from "./territory-select.tsx";1516const SelectLater = import.meta.env.SSR17 ? undefined18 : lazy(() => import("./territory-select.tsx"));1920/** The select's place before it is drawn: its trigger, showing the choice. */21const StandIn = ({ choices, labelledBy, value }: TerritorySelectProps) => (22 <>23 <button24 aria-labelledby={labelledBy}25 className="border-input tablet:text-ui flex h-11 w-full max-w-xs items-center justify-between gap-1.5 border bg-transparent py-2 pr-2 pl-2.5 text-base sm:h-9"26 data-slot="select-trigger"27 disabled28 type="button"29 >30 {choices.find((choice) => choice.value === value)?.label ?? value}31 <ChevronDown32 aria-hidden="true"33 className="text-muted-foreground size-4"34 strokeWidth={1.75}35 />36 </button>37 <input name="territory" type="hidden" value={value} />38 </>39);4041export const ClientTerritorySelect = (props: TerritorySelectProps) => {42 const fallback = <StandIn {...props} />;4344 return SelectLater === undefined ? (45 fallback46 ) : (47 <ClientOnly fallback={fallback}>48 <Suspense fallback={fallback}>49 <SelectLater {...props} />50 </Suspense>51 </ClientOnly>52 );53};
modified:apps/web/src/features/propose/propose-link.tsx+1 added-1 removed
13 unmodified lines
14import { proposeFormPath } from "./propose-view.tsx";1516export const ProposeLink = ({ project }: { readonly project: ProjectName }) => (17 <a18 className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"18 className="text-ui decoration-rule flex w-fit items-center gap-2 font-medium underline hover:decoration-current"19 data-propose=""20 href={proposeFormPath(project)}21 >22 <MessageSquarePlus aria-hidden="true" className="size-4 shrink-0" />
13 unmodified lines
modified:apps/web/src/features/propose/propose-view.tsx+205 added-69 removed
1 unmodified line
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.6 * want with where it points. The inspector says what makes a good want and7 * gives the same proposal as a command. Props in, markup out: the route8 * reads who is signed in and the project's paths, sends the payload, and9 * goes to the proposal once it is made.10 *11 * Only the want, the territory and the draft box: the files are the12 * agent's to write, or a person's through `propose --files` in the CLI.13 * Propose waits until there is a want, and says so on itself.14 */15import { Brand } from "@repo/brand";16import type { ProposeAsk } from "@repo/protocol/contracts";17import type { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";
7 unmodified lines
25import { Label } from "../../components/ui/label.tsx";26import { Spinner } from "../../components/ui/spinner.tsx";27import { Textarea } from "../../components/ui/textarea.tsx";28import { signInHref } from "../auth/session-slot.tsx";27import { LABEL } from "../shared/classes.ts";29import { CommandLine } from "../shared/command.tsx";30import { FactBlock } from "../shared/facts.tsx";31import { Workspace } from "../shared/shell/workspace.tsx";32import { ClientTerritorySelect } from "./client-territory.tsx";3334/** What `proposeAsk` takes, from its one schema. */35export type ProposePayload = typeof ProposeAsk.payloadSchema.Type;36
42 unmodified lines
79 onSome: ({ at, line, path }) =>80 `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,81 });8283/** The value the territory takes when the agent chooses it. */84const AGENT_CHOOSES = "";8586/** The territories the form offers: the agent's choice first, then each top folder. */87export const territoryChoices = (modules: readonly RepoPath[]) => [88 { label: "Let the agent choose", value: AGENT_CHOOSES },89 ...modules.map((module) => ({ label: module, value: module })),90];9192/** What Propose says: why it waits, or what it does. */93const proposeWords = (written: boolean, busy: boolean) => {94 if (!written) {95 return "Write the want first";96 }9798 return busy ? "Proposing" : "Propose";99};100101/** The proposal as a command, for a reader in a terminal. */102const PROPOSE_COMMAND = `${Brand.cli} propose --draft "<want>"`;103104const SignInFirst = ({105 about,106 project,107}: {
1 unmodified line
109 readonly project: ProjectName;110}) => (111 <section112 aria-label="Sign in to propose"88 className="border-rule flex flex-col gap-3 border-t pt-4"113 className="flex max-w-[70ch] flex-col items-start gap-3"114 >90 <p className="flex items-start gap-2 text-sm">91 <LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />115 <p className="text-body">116 A proposal asks {project} to open an ask nobody wrote yet: a want in your117 words, which the platform&apos;s agent can draft into an ask file and a118 failing check for a decider to accept.119 </p>120 <p className="text-ui flex items-start gap-2">121 <LogIn122 aria-hidden="true"123 className="mt-0.5 size-4 shrink-0"124 strokeWidth={1.75}125 />126 <span>93 Proposing an ask is for signed-in members.{" "}127 Proposing is for signed-in members.{" "}128 <a129 className="decoration-rule font-medium underline hover:decoration-current"130 href={signInHref(proposeFormPath(project, about))}131 >132 Sign in133 </a>{" "}100 to propose one, or propose from your clone:134 to propose one here, or propose from your clone:135 </span>136 </p>103 <CommandLine command={`${Brand.cli} propose --draft "<want>"`} />137 <CommandLine command={PROPOSE_COMMAND} />138 </section>139);140107export const ProposeView = ({141/** What makes a good want, and the same proposal from a terminal. */142const GoodWant = () => (143 <>144 <FactBlock label="A good want">145 <ul className="text-ui flex list-disc flex-col gap-1.5 pl-4">146 <li>Says what the project should do, not how to change the code.</li>147 <li>Asks for one change, small enough to check on its own.</li>148 <li>Says how you would tell it is done: what a check would see.</li>149 </ul>150 </FactBlock>151 <FactBlock label="From a terminal">152 <CommandLine command={PROPOSE_COMMAND} numbered />153 </FactBlock>154 </>155);156157const Form = ({158 about,109 busy = false,159 busy,160 children,161 modules,162 onPropose,163 project,114 signedIn,164}: {165 readonly project: ProjectName;117 readonly signedIn: boolean;166 readonly about: Option.Option<About>;119 /** The project's top folders, each a territory to choose. */167 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. */168 readonly onPropose?: ((payload: ProposePayload) => void) | undefined;169 readonly busy: boolean;170 readonly children?: ReactNode;127}): ReactNode => {171}) => {172 const id = useId();173174 const [want, setWant] = useState(() =>175 Option.match(about, { onNone: () => "", onSome: wantAbout })176 );177134 const [territory, setTerritory] = useState("");178 const [territory, setTerritory] = useState(AGENT_CHOOSES);179 const [draft, setDraft] = useState(true);136137 if (!signedIn) {138 return <SignInFirst about={about} project={project} />;139 }140180 const chosen = modules.find((module) => module === territory);181 const written = want.trim().length > 0;182 const choices = territoryChoices(modules);183184 return (185 <form186 aria-label="Propose an ask"147 className="flex max-w-[70ch] flex-col gap-5"187 className="flex max-w-[70ch] flex-col gap-6"188 data-propose=""189 onSubmit={(event) => {190 event.preventDefault();191192 if (written) {
7 unmodified lines
200 }201 }}202 >203 <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?204 <label className="text-ui font-medium" htmlFor={`${id}-want`}>205 What should {project} do that it does not do now?206 </label>207 <Textarea167 className="min-h-32 text-sm md:text-sm"208 className="min-h-32 text-base leading-6"209 id={`${id}-want`}210 name="want"211 onChange={(event) => {212 setWant(event.target.value);
3 unmodified lines
216 />217 </div>218219 <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 }}220 <span className="text-ui font-medium" id={`${id}-territory`}>221 Territory222 </span>223 <ClientTerritorySelect224 choices={choices}225 labelledBy={`${id}-territory`}226 onChange={setTerritory}227 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>228 />229 <p className="text-label text-muted-foreground font-normal">230 One of the project&apos;s top folders, or the agent picks from the231 want.232 </p>233 </div>234235 <div className="flex flex-col gap-1.5">200 <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>236 <div className="flex items-start gap-2">237 <Checkbox238 checked={draft}239 className="mt-0.5"240 id={`${id}-draft`}241 name="draft"242 onCheckedChange={(checked) => {243 setDraft(checked);244 }}245 />246 <Label className="text-ui leading-snug" htmlFor={`${id}-draft`}>247 Let the platform&apos;s agent draft the ask248 </Label>249 </div>250 <p className="text-label text-muted-foreground pl-6 font-normal">251 It writes the ask file and a check that fails on main, runs it red252 first, and puts the draft to a decider. Clear the box to propose the253 want alone.254 </p>255 </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>256257 {children}258259 <Button223 className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"260 className="tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4"261 data-written={written}262 disabled={busy || !written}263 type="submit"264 >265 {busy ? <Spinner /> : null}228 Propose266 {proposeWords(written, busy)}267 </Button>268 </form>269 );270};271272/** The form, the way to sign in, or the wait while the browser learns who is signed in. */273const ProposeBody = ({274 about,275 busy,276 checking,277 children,278 modules,279 onPropose,280 project,281 signedIn,282}: {283 readonly project: ProjectName;284 readonly signedIn: boolean;285 readonly checking: boolean;286 readonly about: Option.Option<About>;287 readonly modules: readonly RepoPath[];288 readonly onPropose?: ((payload: ProposePayload) => void) | undefined;289 readonly busy: boolean;290 readonly children?: ReactNode;291}) => {292 if (checking) {293 return (294 <output className="text-ui text-muted-foreground block">295 Checking who is signed in296 </output>297 );298 }299300 return signedIn ? (301 <Form302 about={about}303 busy={busy}304 modules={modules}305 onPropose={onPropose}306 project={project}307 >308 {children}309 </Form>310 ) : (311 <SignInFirst about={about} project={project} />312 );313};314315export const ProposeView = ({316 about,317 busy = false,318 checking = false,319 children,320 modules,321 onPropose,322 project,323 signedIn,324}: {325 readonly project: ProjectName;326 readonly signedIn: boolean;327 /** Whether the browser is still learning who is signed in. */328 readonly checking?: boolean;329 readonly about: Option.Option<About>;330 /** The project's top folders, each a territory to choose. */331 readonly modules: readonly RepoPath[];332 /** Sends the payload; the route goes to the proposal once it is made. */333 readonly onPropose?: (payload: ProposePayload) => void;334 /** Whether a proposal is on its way: the button waits. */335 readonly busy?: boolean;336 /** What the last proposal came back with, when it was refused. */337 readonly children?: ReactNode;338}): ReactNode => (339 // Below the shell's width the form comes first, and what makes a good340 // want follows it, rather than standing between the reader and the form.341 <div className="contents [&_[data-facts=inline]]:hidden">342 <Workspace343 crumbs={[344 { label: project, to: `/${project}` },345 { label: "Propose an ask" },346 ]}347 facts={<GoodWant />}348 factsHeading="Proposing"349 meta="A decider decides whether the ask opens; nothing lands from here."350 title="Propose an ask"351 >352 <ProposeBody353 about={about}354 busy={busy}355 checking={checking}356 modules={modules}357 onPropose={onPropose}358 project={project}359 signedIn={signedIn}360 >361 {children}362 </ProposeBody>363 <div className="shell:hidden border-rule flex flex-col border-t pt-4">364 <GoodWant />365 </div>366 </Workspace>367 </div>368);
added:apps/web/src/features/propose/territory-select.tsx+62 added
1/**2 * The territory a proposal names, chosen with the kit's select: the agent's3 * choice first, then each of the project's top folders in mono. Drawn in4 * the browser only (`client-territory.tsx`): Base UI's select, its5 * positioning and its scroll lock are the browser's to run, and the Worker6 * bundles none of them.7 */8import {9 Select,10 SelectContent,11 SelectItem,12 SelectTrigger,13 SelectValue,14} from "../../components/ui/select.tsx";1516export interface TerritorySelectProps {17 /** What the select offers, the agent's choice (`""`) first. */18 readonly choices: readonly {19 readonly label: string;20 readonly value: string;21 }[];22 readonly labelledBy: string;23 readonly onChange: (value: string) => void;24 readonly value: string;25}2627/** The trigger's look, shared with the server's stand-in for it. */28export const TRIGGER = "tablet:text-ui h-11 w-full max-w-xs text-base sm:h-9";2930export const TerritorySelect = ({31 choices,32 labelledBy,33 onChange,34 value,35}: TerritorySelectProps) => (36 <Select37 items={choices}38 name="territory"39 onValueChange={(chosen) => {40 onChange(chosen ?? "");41 }}42 value={value}43 >44 <SelectTrigger aria-labelledby={labelledBy} className={TRIGGER}>45 <SelectValue />46 </SelectTrigger>47 <SelectContent>48 {choices.map(({ label, value: each }) => (49 <SelectItem key={each} value={each}>50 {each === "" ? (51 label52 ) : (53 <code className="text-mono font-mono">{label}</code>54 )}55 </SelectItem>56 ))}57 </SelectContent>58 </Select>59);6061// `React.lazy` takes a module's default export.62export default TerritorySelect;
added:apps/web/src/features/today/read.ts+147 added
1/**2 * What Today's page reads, in a module with no view of its own: a route's3 * loader runs before its page's view loads, so the route reaches these4 * without carrying the page.5 *6 * - `TodayRead`: the reader's Today, or why there is none (a refusal, no7 * session, no answer from the platform), as the loader sends it.8 * - `readToday`: that read, made with whatever `Client` the caller gives9 * (the server's, carrying the reader's own session).10 * - The order a decider takes decisions in: due within the day first, then11 * by expiry.12 */13import { Client } from "@repo/protocol/contracts";14import { Today } from "@repo/protocol/domain/decision";15import type { Decision } from "@repo/protocol/domain/decision";16import type { DecisionId, ProjectName } from "@repo/protocol/ids";17import { Unauthenticated } from "@repo/protocol/principal";18import { Refusal } from "@repo/protocol/refusal";19import {20 Array as Arr,21 Cause,22 DateTime,23 Effect,24 Exit,25 Option,26 Order,27 Schema,28} from "effect";2930import { decisionKey } from "../decision/subject.ts";3132/** What the page read for its reader: their Today, or why there is none. */33export const TodayRead = Schema.TaggedUnion({34 Read: { today: Today },35 Refused: { refusal: Refusal },36 SignedOut: {},37 Unreachable: {},38});3940export type TodayRead = typeof TodayRead.Type;4142/** What Today's loader sends: the read, and the instant it was made. */43export const TodayPageData = Schema.Struct({44 now: Schema.DateTimeUtcFromString,45 read: TodayRead,46});4748export type TodayPageData = typeof TodayPageData.Type;4950const isRefusal = Schema.is(Refusal);5152const isUnauthenticated = Schema.is(Unauthenticated);5354/** A failed read of Today, as the page says it. */55export const readOfCause = (cause: Cause.Cause<unknown>): TodayRead => {56 const error = Cause.findErrorOption(cause);5758 if (Option.isSome(error) && isRefusal(error.value)) {59 return TodayRead.cases.Refused.make({ refusal: error.value });60 }6162 return Option.exists(error, isUnauthenticated)63 ? TodayRead.cases.SignedOut.make({})64 : TodayRead.cases.Unreachable.make({});65};6667/** Soonest to expire first, then oldest, then by project and id: one order every time. */68export const expiryOrder: Order.Order<Decision> = Order.combineAll([69 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),70 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),71 Order.mapInput(Order.String, ({ project }: Decision) => project),72 Order.mapInput(Order.String, ({ id }: Decision) => id),73]);7475/**76 * The decisions `today.expiringSoon` names. Ids are minted per project, so a77 * Today across projects may hold two decisions with one id; where an id is78 * named `n` times, the `n` of its decisions that expire first are the ones79 * meant (a decision that expires within the day expires before any that80 * does not).81 */82export const expiringSoon = (today: Today): ReadonlySet<string> => {83 const named = Arr.groupBy(today.expiringSoon, (id) => id);84 const byExpiry = Arr.sort(today.decisions, expiryOrder);8586 return new Set(87 Object.entries(named).flatMap(([id, times]) =>88 byExpiry89 .filter((decision) => decision.id === id)90 .slice(0, times.length)91 .map(decisionKey)92 )93 );94};9596/** Today's decisions in the order a decider takes them: expiring soon first, then by expiry. */97export const orderDecisions = (today: Today): readonly Decision[] => {98 const soon = expiringSoon(today);99100 return Arr.sort(101 today.decisions,102 Order.combine(103 Order.mapInput(104 Order.Boolean,105 (decision: Decision) => !soon.has(decisionKey(decision))106 ),107 expiryOrder108 )109 );110};111112/** Where one decision stands on Today: listed (and whether it expires soon), or not there. */113export const findDecision = (114 today: Today,115 project: ProjectName,116 id: DecisionId117): Option.Option<{ readonly decision: Decision; readonly soon: boolean }> => {118 const soon = expiringSoon(today);119120 return Arr.findFirst(121 today.decisions,122 (decision) => decision.project === project && decision.id === id123 ).pipe(124 Option.map((decision) => ({125 decision,126 soon: soon.has(decisionKey(decision)),127 }))128 );129};130131/** The reader's Today, or why there is none, encoded for the page. */132export const readToday = ({ project }: { readonly project?: ProjectName }) =>133 Effect.gen(function* () {134 const client = yield* Client;135136 const read = yield* Effect.exit(137 client.today(project === undefined ? {} : { project })138 );139140 return yield* Schema.encodeEffect(TodayPageData)({141 now: yield* DateTime.now,142 read: Exit.match(read, {143 onFailure: readOfCause,144 onSuccess: (today) => TodayRead.cases.Read.make({ today }),145 }),146 });147 });
modified:apps/web/src/features/today/today-page.tsx+593 added-322 removed
1/**2 * Today: a decider's day of decisions, not diffs, held to a budget. The3 * budget's decisions and the finishes are counted apart (a finish costs more4 * than a decision); the decisions expiring soon come first, then the rest by5 * expiry; what the budget leaves out waits for tomorrow, and may expire to6 * its safe default. Below them: the newcomers to welcome, and a sample of7 * landings that needed nobody.2 * Today: a decider's day of decisions, not diffs, held to a budget said in3 * one sentence. The decisions sit in sections: those due within the day,4 * then the rest within the budget by expiry, then how many wait for5 * tomorrow (their ids are not in the read, so they have no rows). Below6 * them, the newcomers to welcome and a sample of landings that needed7 * nobody.8 *9 * Each row says its subject in plain words (the link to its page), its10 * project, kind and id, and when it expires over its default. From the11 * shell's width a row selects into the inspector, which holds the whole12 * decision: its evidence, a note, and its choices, each with what it does.13 * Below it a row opens in place, one at a time, its choices kept in sight14 * above the bottom bar while it is open.15 *16 * A choice taken leaves its row where it was, reading what it did; the17 * budget sentence moves with the next read. There is no toast.18 *19 * A failure reads as what it is: a refusal (`NotDecider` for a person who10 * decides nothing) through `RefusalView`, a missing sign-in as the way to11 * sign in, and an unreachable platform as that, never as an empty day.20 * decides nothing) through `RefusalView`, a missing sign-in as what Today21 * is and how to sign in, and an unreachable platform as that, never as an22 * empty day.23 */24import { Brand } from "@repo/brand";25import type { Decision, Today } from "@repo/protocol/domain/decision";26import type { LandingView } from "@repo/protocol/domain/landing";16import type { DecisionId, ProjectName } from "@repo/protocol/ids";17import { Unauthenticated } from "@repo/protocol/principal";18import { Refusal } from "@repo/protocol/refusal";19import { Array as Arr, Cause, DateTime, Option, Order, Schema } from "effect";27import { Array as Arr, Option, Order } from "effect";28import type { DateTime } from "effect";29import { constVoid } from "effect/Function";30import { AsyncResult } from "effect/reactivity";21import { CircleCheck, LogIn, Unplug } from "lucide-react";31import { ChevronDown } from "lucide-react";32import { useState } from "react";33import type { ReactNode } from "react";3435import { signInHref } from "../auth/session-slot.tsx";36import { commitHref, shortSha } from "../code/paths.ts";37import { stuckAboveBar } from "../decision/choices.tsx";38import { DecisionCard } from "../decision/decision-card.tsx";39import type { DecideInput } from "../decision/decision-card.tsx";26import { LABEL } from "../shared/classes.ts";40import {41 consequenceOf,42 decisionHref,43 decisionKey,44 describeDefault,45 describeSubject,46 subjectKind,47 takenWords,48 tookEffect,49} from "../decision/subject.ts";50import { CommandLine } from "../shared/command.tsx";51import { EmptyState } from "../shared/empty.tsx";28import { HandleLink } from "../shared/handle.tsx";52import { FactBlock } from "../shared/facts.tsx";53import { useListKeys } from "../shared/keys.tsx";54import { AppLink } from "../shared/link.tsx";55import { personPath } from "../shared/paths.ts";56import { UnreachableNotice } from "../shared/pending.tsx";57import { RefusalView } from "../shared/refusal.tsx";30import { When } from "../shared/time.tsx";58import { MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";59import { Workspace } from "../shared/shell/workspace.tsx";60import { StatusLine } from "../shared/status-line.tsx";61import { distanceInWords, When } from "../shared/time.tsx";62import { expiringSoon, expiryOrder, readOfCause, TodayRead } from "./read.ts";6332const isRefusal = Schema.is(Refusal);64export {65 findDecision,66 orderDecisions,67 readOfCause,68 TodayPageData,69 TodayRead,70} from "./read.ts";7134const isUnauthenticated = Schema.is(Unauthenticated);72const counted = (count: number) => (count === 0 ? "none" : String(count));7336/** A decision's place in a Today that may hold several projects. */37const keyOf = ({ id, project }: Decision) => `${project}/${id}`;74/** The day's budget, in one sentence: decisions taken and left, and the finishes apart. */75export const budgetSentence = (budget: Today["budget"]) =>76 `Decisions: ${budget.used} taken, ${counted(Math.max(0, budget.total - budget.used))} left today. Finishes are counted apart: ${counted(budget.finishes)} taken.`;7739/** Soonest to expire first, then oldest, then by project and id: one order every time. */40const expiryOrder: Order.Order<Decision> = Order.combineAll([41 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),42 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),43 Order.mapInput(Order.String, ({ project }: Decision) => project),44 Order.mapInput(Order.String, ({ id }: Decision) => id),45]);78/** The budget for the context bar: what is left. */79const budgetShort = (budget: Today["budget"]) =>80 `${counted(Math.max(0, budget.total - budget.used))} left today`;8147/**48 * The decisions `today.expiringSoon` names. Ids are minted per project, so a49 * Today across projects may hold two decisions with one id; where an id is50 * named `n` times, the `n` of its decisions that expire first are the ones51 * meant (a decision that expires within the day expires before any that52 * does not).53 */54const expiringSoon = (today: Today): ReadonlySet<string> => {55 const named = Arr.groupBy(today.expiringSoon, (id) => id);56 const byExpiry = Arr.sort(today.decisions, expiryOrder);82/** What Today is, for someone it does not hold decisions for yet. */83const WHAT_TODAY_IS =84 "Today is a decider's page: the decisions you owe your projects each day, each with its evidence and a safe default if you leave it.";8558 return new Set(59 Object.entries(named).flatMap(([id, times]) =>60 byExpiry61 .filter((decision) => decision.id === id)62 .slice(0, times.length)63 .map(keyOf)64 )65 );66};86/** A decision on the page: listed, and whether it is due within the day. */87interface Listed {88 readonly decision: Decision;89 readonly soon: boolean;90}9168/** Today's decisions in the order a decider takes them: expiring soon first, then by expiry. */69export const orderDecisions = (today: Today): readonly Decision[] => {70 const soon = expiringSoon(today);92/** The choice a row's decision was taken with, when the decider took it here. */93const choiceOf = (decision: Decision) => decision.decided?.choice;9472 return Arr.sort(73 today.decisions,74 Order.combine(75 Order.mapInput(76 Order.Boolean,77 (decision: Decision) => !soon.has(keyOf(decision))78 ),79 expiryOrder80 )81 );82};95/** Its expiry over its default, at the row's end; muted when it is not due within the day. */96const openState = (listed: Listed, now: DateTime.Utc) => ({97 mark: listed.soon ? ("waiting" as const) : ("notYet" as const),98 time: `default: ${listed.decision.default}`,99 word: distanceInWords(listed.decision.expiresAt, now),100});10184/** Where one decision stands on Today: listed (and whether it expires soon), or not there. */85export const findDecision = (86 today: Today,87 project: ProjectName,88 id: DecisionId89): Option.Option<{ readonly decision: Decision; readonly soon: boolean }> => {90 const soon = expiringSoon(today);102/** The way to open a row in place, below the shell's width. */103const OpenHere = ({104 decision,105 onToggle,106 open,107}: {108 readonly decision: Decision;109 readonly open: boolean;110 readonly onToggle: () => void;111}) => (112 <button113 aria-controls={`here-${decisionKey(decision).replace("/", "-")}`}114 aria-expanded={open}115 aria-label={`${open ? "Close" : "Decide"} here: ${describeSubject(decision.subject)}`}116 className="text-muted-foreground hover:text-foreground hover:bg-surface shell:hidden relative z-10 inline-flex size-11 shrink-0 items-center justify-center transition-colors duration-[120ms]"117 onClick={onToggle}118 type="button"119 >120 <ChevronDown121 aria-hidden="true"122 className={`size-5 transition-transform duration-[180ms] ${open ? "rotate-180" : ""}`}123 strokeWidth={1.75}124 />125 </button>126);12792 return Arr.findFirst(93 today.decisions,94 (decision) => decision.project === project && decision.id === id95 ).pipe(96 Option.map((decision) => ({ decision, soon: soon.has(keyOf(decision)) }))97 );98};128interface RowsProps {129 readonly busy: boolean;130 readonly now: DateTime.Utc;131 readonly onDecide: (input: DecideInput) => void;132 readonly onSelect: ((key: string) => void) | undefined;133 readonly open: string | undefined;134 readonly onOpen: (key: string | undefined) => void;135 readonly selected: string | undefined;136 /** The decisions taken while the page was open, to stamp once. */137 readonly stamped: ReadonlySet<string>;138}139100const plural = (count: number, one: string, many: string) =>101 `${count} ${count === 1 ? one : many}`;140/** One decision's row: its subject, where it stands, and (below the shell's width) the whole of it in place. */141const DecisionRow = ({142 listed,143 props,144}: {145 readonly listed: Listed;146 readonly props: RowsProps;147}) => {148 const { decision } = listed;149 const key = decisionKey(decision);150 const choice = choiceOf(decision);151 const isOpen = props.open === key && choice === undefined;152103const SECTION = "flex flex-col gap-3";153 const state =154 choice === undefined155 ? openState(listed, props.now)156 : {157 mark: tookEffect(decision, choice)158 ? ("landed" as const)159 : ("notNeeded" as const),160 stamp: props.stamped.has(key),161 word: takenWords[choice],162 };163105const TITLE = "text-lg font-semibold";164 return (165 <Row166 action={167 choice === undefined ? (168 <OpenHere169 decision={decision}170 onToggle={() => {171 props.onOpen(isOpen ? undefined : key);172 }}173 open={isOpen}174 />175 ) : undefined176 }177 data={{178 "data-decided": choice,179 "data-decision": decision.id,180 "data-project": decision.project,181 "data-soon": listed.soon,182 }}183 href={decisionHref(decision)}184 id={key}185 meta={186 choice === undefined ? (187 <MetaLine188 parts={[189 decision.project,190 subjectKind(decision.subject),191 <MetaCode key="id">{decision.id}</MetaCode>,192 ]}193 />194 ) : (195 consequenceOf(decision.subject, choice)196 )197 }198 onSelect={props.onSelect}199 selected={props.selected === key}200 state={state}201 strip={202 choice === undefined ? (203 <div204 className={`shell:hidden pr-2 ${isOpen ? "animate-in fade-in-0 slide-in-from-top-1 pb-1 duration-[180ms]" : "hidden"}`}205 id={`here-${key.replace("/", "-")}`}206 >207 <DecisionCard208 busy={props.busy}209 choices={stuckAboveBar}210 decision={decision}211 now={props.now}212 onDecide={props.onDecide}213 soon={listed.soon}214 />215 </div>216 ) : undefined217 }218 title={describeSubject(decision.subject)}219 />220 );221};222107/** A one-line notice under a rule: an icon, then what to know. */108export const Notice = ({223const Section = ({224 children,110 icon,225 count,226 name,227}: {228 readonly children: ReactNode;113 readonly icon: ReactNode;229 readonly name: string;230 readonly count?: string;231}) => (115 <output className="border-rule flex items-start gap-2 border-t border-b py-3 text-sm">116 {icon}117 <span>{children}</span>118 </output>232 <RowGroup233 {...(count === undefined ? {} : { counts: count })}234 label={name}235 name={name}236 under="bar"237 >238 {children}239 </RowGroup>240);241121/** A call that failed: a refusal as the platform gave it, or why there is no answer. */122export const FailureView = ({123 cause,242const plural = (count: number, one: string, many: string) =>243 `${count} ${count === 1 ? one : many}`;244245/** The decisions, due today then within the budget, each section only when it holds one. */246const DecisionSections = ({247 listed,248 props,249}: {125 readonly cause: Cause.Cause<unknown>;250 readonly listed: readonly Listed[];251 readonly props: RowsProps;252}) => {127 const error = Cause.findErrorOption(cause);253 const dueToday = listed.filter(({ soon }) => soon);254 const later = listed.filter(({ soon }) => !soon);255129 if (Option.isSome(error) && isRefusal(error.value)) {130 return <RefusalView refusals={[error.value]} />;131 }132133 if (Option.isSome(error) && isUnauthenticated(error.value)) {134 return (135 <Notice136 icon={<LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />}137 >138 Today is a decider&apos;s page.{" "}139 <a140 className="decoration-rule font-medium underline hover:decoration-current"141 href="/auth/signin"142 >143 Sign in144 </a>{" "}145 to see yours.146 </Notice>147 );148 }149256 return (151 <Notice152 icon={<Unplug aria-hidden="true" className="mt-0.5 size-4 shrink-0" />}153 >154 The platform did not answer. Reload the page, or run{" "}155 <code className="font-mono text-[0.8125rem]">{Brand.cli} today</code> in a156 terminal.157 </Notice>257 <>258 {dueToday.length === 0 ? null : (259 <Section260 count={plural(dueToday.length, "decision", "decisions")}261 name="Due today"262 >263 {dueToday.map((each) => (264 <DecisionRow265 key={decisionKey(each.decision)}266 listed={each}267 props={props}268 />269 ))}270 </Section>271 )}272 {later.length === 0 ? null : (273 <Section274 count={plural(later.length, "decision", "decisions")}275 name="Within your budget"276 >277 {later.map((each) => (278 <DecisionRow279 key={decisionKey(each.decision)}280 listed={each}281 props={props}282 />283 ))}284 </Section>285 )}286 </>287 );288};289161/** Today on its way from the platform. */162export const ReadingToday = () => (163 <output className="text-muted-foreground block text-sm">164 Reading your Today165 </output>166);290/** How many wait beyond the budget, as a sentence: their ids are not in the read. */291const Tomorrow = ({ overflow }: { readonly overflow: number }) =>292 overflow === 0 ? null : (293 <Section name="Waits for tomorrow">294 <li295 className="border-rule text-ui flex min-h-10 items-center border-b py-2"296 data-overflow={overflow}297 >298 {overflow} more {overflow === 1 ? "waits" : "wait"} for tomorrow; each299 expires to its default if nobody decides first.300 </li>301 </Section>302 );303168/** The day's budget, as two fields: decisions against the total, and finishes apart. */169const Budget = ({ budget }: { readonly budget: Today["budget"] }) => {170 const left = Math.max(0, budget.total - budget.used);304const Newcomers = ({305 newcomers,306}: {307 readonly newcomers: Today["newcomers"];308}) =>309 newcomers.length === 0 ? null : (310 <Section name="Newcomers to welcome">311 {newcomers.map((handle) => (312 <Row313 href={personPath(handle)}314 id={handle}315 key={handle}316 meta="made a first claim this week"317 size="one-line"318 title={handle}319 />320 ))}321 </Section>322 );323172 return (173 <dl174 aria-label="Today's budget"175 className="border-rule grid grid-cols-2 border-t border-b"176 >177 <div className="border-rule flex flex-col gap-0.5 border-r py-2 pr-3">178 <dt className={LABEL}>Decisions</dt>179 <dd className="text-2xl font-semibold tabular-nums" data-budget="used">180 {budget.used} of {budget.total}181 </dd>182 <dd className="text-muted-foreground text-xs">183 {plural(left, "decision", "decisions")} left today184 </dd>185 </div>186 <div className="flex flex-col gap-0.5 py-2 pl-3">187 <dt className={LABEL}>Finishes</dt>188 <dd189 className="text-2xl font-semibold tabular-nums"190 data-budget="finishes"191 >192 {plural(budget.finishes, "finish", "finishes")}193 </dd>194 <dd className="text-muted-foreground text-xs">195 counted apart from decisions196 </dd>197 </div>198 </dl>324const Unattended = ({325 landings,326 now,327}: {328 readonly landings: readonly LandingView[];329 readonly now: DateTime.Utc;330}) =>331 landings.length === 0 ? null : (332 <Section name="Landed without a decision">333 {landings.map((landing) => (334 <Row335 href={commitHref(landing.project, landing.sha)}336 id={landing.sha}337 key={`${landing.project}/${landing.sha}`}338 meta={339 <MetaLine340 parts={[341 landing.project,342 <MetaCode key="sha">{shortSha(landing.sha)}</MetaCode>,343 ]}344 />345 }346 state={{347 mark: "landed",348 time: <When at={landing.landedAt} now={now} />,349 word: "Landed",350 }}351 title={352 landing.ask === undefined353 ? `Landed by ${landing.author}`354 : `${landing.ask}, answered by ${landing.author}`355 }356 />357 ))}358 </Section>359 );200};360202/** What the decider's last choice came to: taken, refused, or on its way. */203export const DecidedNotice = ({361/** The decision the inspector holds, whole. */362const SelectedFacts = ({363 busy,364 listed,365 now,366 onDecide,367 stamped,368}: {369 readonly busy: boolean;370 readonly listed: Listed;371 readonly now: DateTime.Utc;372 readonly onDecide: (input: DecideInput) => void;373 readonly stamped: boolean;374}) => (375 <>376 <FactBlock label="State">377 <AppLink378 className="text-want decoration-rule font-semibold text-balance [overflow-wrap:anywhere] underline-offset-4 hover:underline"379 to={decisionHref(listed.decision)}380 >381 {describeSubject(listed.decision.subject)}382 </AppLink>383 <StatusLine384 subject={{385 decision: listed.decision,386 kind: "decision",387 now,388 viewerDecides: true,389 }}390 />391 <p className="text-label text-muted-foreground font-normal">392 {describeDefault(listed.decision)}393 </p>394 </FactBlock>395 <FactBlock label="Evidence and choices">396 <DecisionCard397 busy={busy}398 decision={listed.decision}399 expiry={false}400 layout="stack"401 now={now}402 onDecide={onDecide}403 soon={listed.soon}404 stamp={stamped}405 />406 </FactBlock>407 </>408);409410/** Signed out: what Today is, the way in, and the command. */411const SignedOutNotice = ({ here }: { readonly here: string }) => (412 <div className="flex max-w-[70ch] flex-col items-start gap-3">413 <p className="text-body">{WHAT_TODAY_IS}</p>414 <p className="text-ui">415 <a416 className="decoration-rule font-medium underline hover:decoration-current"417 href={signInHref(here)}418 >419 Sign in420 </a>{" "}421 to see yours, or read it from a terminal:422 </p>423 <CommandLine command={`${Brand.cli} today`} />424 </div>425);426427/** What a choice that failed came back with: the refusal, or why there is none. */428const DecidedFailure = ({429 decided,430}: {206 readonly decided: AsyncResult.AsyncResult<207 { readonly decision: Decision },208 unknown209 >;431 readonly decided: AsyncResult.AsyncResult<unknown, unknown>;432}) => {211 if (AsyncResult.isFailure(decided)) {212 return <FailureView cause={decided.cause} />;433 if (!AsyncResult.isFailure(decided)) {434 return null;435 }436215 if (AsyncResult.isInitial(decided)) {216 return decided.waiting ? (217 <p className="text-checking text-sm" data-decided="waiting">218 Sending your choice219 </p>220 ) : null;221 }437 const read = readOfCause(decided.cause);438223 const { decision } = decided.value;439 return TodayRead.match(read, {440 Read: () => null,441 Refused: ({ refusal }) => <RefusalView refusals={[refusal]} />,442 SignedOut: () => <SignedOutNotice here="/today" />,443 Unreachable: () => <UnreachableNotice />,444 });445};446225 return decision.decided === undefined ? null : (226 <p227 className="flex items-start gap-2 text-sm"228 data-decided={decision.decided.choice}229 >230 <CircleCheck231 aria-hidden="true"232 className="text-landed mt-0.5 size-4 shrink-0"233 />234 <span>235 <strong className="text-landed font-semibold">Decided:</strong>{" "}236 {decision.decided.choice} on{" "}237 <code className="font-mono text-[0.8125rem]">238 {decision.project}/{decision.id}239 </code>240 </span>241 </p>447/** The page around a Today with no decisions to list: the reason, said whole. */448const Unlisted = ({ children }: { readonly children: ReactNode }) => (449 <Workspace crumbs={[{ label: "Today" }]} title="Today" variant="list">450 {children}451 </Workspace>452);453454/**455 * The decisions on the page: Today's, and any the decider took here that456 * the next read no longer lists, each where it was.457 */458const listedOf = (459 today: Today,460 taken: ReadonlyMap<string, Listed>461): readonly Listed[] => {462 const soon = expiringSoon(today);463464 const current = today.decisions.map((decision) => {465 const key = decisionKey(decision);466467 return taken.get(key) ?? { decision, soon: soon.has(key) };468 });469470 const gone = [...taken.values()].filter(471 ({ decision }) =>472 !today.decisions.some(473 (each) => decisionKey(each) === decisionKey(decision)474 )475 );476477 return Arr.sort(478 [...current, ...gone],479 Order.combine(480 Order.mapInput(Order.Boolean, ({ soon: due }: Listed) => !due),481 Order.mapInput(expiryOrder, ({ decision }: Listed) => decision)482 )483 );484};485245const Decisions = ({486/** `kept` with `decision`, taken, where it was listed. */487const withTaken = (488 kept: ReadonlyMap<string, Listed>,489 decision: Decision,490 soon: ReadonlySet<string>491): ReadonlyMap<string, Listed> => {492 const key = decisionKey(decision);493494 return new Map([495 ...kept,496 [key, { decision, soon: kept.get(key)?.soon ?? soon.has(key) }],497 ]);498};499500/** The decision a choice just came back with, when it was taken. */501const takenNow = (502 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>503): Option.Option<Decision> =>504 Option.filter(505 Option.map(AsyncResult.value(decided), ({ decision }) => decision),506 ({ decided: record }) => record !== undefined507 );508509const ListedToday = ({510 decided,511 now,512 onDecide,513 onSelect,514 selected,515 today,516}: {517 readonly today: Today;518 readonly now: DateTime.Utc;519 readonly onDecide: (input: DecideInput) => void;520 readonly decided: AsyncResult.AsyncResult<521 { readonly decision: Decision },522 unknown523 >;255 readonly now: DateTime.Utc;256 readonly onDecide: (input: DecideInput) => void;257 readonly today: Today;524 readonly selected: string | undefined;525 readonly onSelect: ((key: string) => void) | undefined;526}) => {527 const [kept, setKept] = useState<ReadonlyMap<string, Listed>>(new Map());528 const [open, setOpen] = useState<string>();529 const soon = expiringSoon(today);260 const ordered = orderDecisions(today);530 const fresh = takenNow(decided);531262 return (263 <section aria-labelledby="today-decisions" className={SECTION}>264 <h2 className={TITLE} id="today-decisions">265 Decisions266 </h2>267 <div aria-live="polite">268 <DecidedNotice decided={decided} />269 </div>270 {ordered.length === 0 ? (271 <EmptyState272 command={`${Brand.cli} today`}273 title="Nothing to decide today. Undecided decisions expire to their safe default."274 />275 ) : (276 <ol className="border-rule flex flex-col border-t">277 {ordered.map((decision) => (278 <li className="border-rule border-b py-5" key={keyOf(decision)}>279 <DecisionCard280 busy={decided.waiting}281 decision={decision}282 now={now}283 onDecide={onDecide}284 soon={soon.has(keyOf(decision))}285 />286 </li>287 ))}288 </ol>289 )}290 {today.overflow === 0 ? null : (291 <p292 className="text-muted-foreground text-sm"293 data-overflow={today.overflow}294 >295 {today.overflow} more {today.overflow === 1 ? "waits" : "wait"} for296 tomorrow; each expires to its default if nobody decides first.297 </p>298 )}299 </section>300 );301};532 // A choice taken stays on the page after the next read leaves it out:533 // kept as soon as it comes back, while this render draws it already.534 if (535 Option.isSome(fresh) &&536 kept.get(decisionKey(fresh.value))?.decision.decided === undefined537 ) {538 setKept(withTaken(kept, fresh.value, soon));539 }540303const Newcomers = ({304 newcomers,305}: {306 readonly newcomers: Today["newcomers"];307}) =>308 newcomers.length === 0 ? null : (309 <section aria-labelledby="today-newcomers" className={SECTION}>310 <h2 className={TITLE} id="today-newcomers">311 Newcomers to welcome312 </h2>313 <p className="text-muted-foreground text-sm">314 Their first claim was this week.315 </p>316 <ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm">317 {newcomers.map((handle) => (318 <li key={handle}>319 <HandleLink handle={handle} />320 </li>321 ))}322 </ul>323 </section>541 const taken = Option.match(fresh, {542 onNone: () => kept,543 onSome: (decision) => withTaken(kept, decision, soon),544 });545546 const listed = listedOf(today, taken);547 const keys = listed.map(({ decision }) => decisionKey(decision));548 const select = onSelect ?? constVoid;549550 useListKeys(keys, select);551552 const shown =553 listed.find(({ decision }) => decisionKey(decision) === selected) ??554 listed[0];555556 const stamped = new Set(557 [...kept.keys()].filter((key) => {558 const decision = kept.get(key)?.decision;559 const choice = decision?.decided?.choice;560561 return (562 decision !== undefined &&563 choice !== undefined &&564 choice !== "decline" &&565 tookEffect(decision, choice)566 );567 })568 );569326const Unattended = ({327 landings,328 now,329}: {330 readonly landings: readonly LandingView[];331 readonly now: DateTime.Utc;332}) =>333 landings.length === 0 ? null : (334 <section aria-labelledby="today-unattended" className={SECTION}>335 <h2 className={TITLE} id="today-unattended">336 Landed without a decision337 </h2>338 <p className="text-muted-foreground text-sm">339 A sample of answers that passed the gate and needed nobody.340 </p>341 <ul className="border-rule flex flex-col border-t">342 {landings.map((landing) => (343 <li344 className="border-rule flex flex-wrap items-baseline gap-x-3 gap-y-0.5 border-b py-2 text-sm"345 key={`${landing.project}/${landing.sha}`}570 const props: RowsProps = {571 busy: decided.waiting,572 now,573 onDecide,574 onOpen: setOpen,575 onSelect,576 open,577 // A row is drawn selected only when the address names it; with none578 // named the inspector holds the first, and no row looks chosen.579 selected,580 stamped,581 };582583 return (584 // Below the shell's width a row opens in place, so the inspector's585 // copy of the selected decision is not drawn in main as well.586 <div className="contents [&_[data-facts=inline]]:hidden">587 <Workspace588 count={budgetShort(today.budget)}589 crumbs={[{ label: "Today" }]}590 facts={591 shown === undefined ? undefined : (592 <SelectedFacts593 busy={decided.waiting}594 listed={shown}595 now={now}596 onDecide={onDecide}597 stamped={stamped.has(decisionKey(shown.decision))}598 />599 )600 }601 factsHeading="Selected decision"602 {...(shown === undefined603 ? {}604 : { factsKey: decisionKey(shown.decision) })}605 status={606 <p607 className="text-want max-w-[70ch]"608 data-budget={`${today.budget.used}/${today.budget.total}`}609 >347 <code className="font-mono text-[0.8125rem]">348 {landing.sha.slice(0, 7)}349 </code>350 <span className="min-w-0 [overflow-wrap:anywhere]">351 <span className="font-mono text-[0.8125rem]">352 {landing.project}353 </span>354 {landing.ask === undefined ? null : (355 <>356 {" "}357 answers{" "}358 <span className="font-mono text-[0.8125rem]">359 {landing.ask}360 </span>361 </>362 )}363 , by <HandleLink handle={landing.author} />364 </span>365 <span className="text-muted-foreground ml-auto text-xs">366 <When at={landing.landedAt} now={now} />367 </span>368 </li>369 ))}370 </ul>371 </section>610 {budgetSentence(today.budget)}611 </p>612 }613 title="Today"614 variant="list"615 >616 <div aria-live="polite" className="empty:hidden">617 <DecidedFailure decided={decided} />618 </div>619 {listed.length === 0 ? (620 <EmptyState621 command={`${Brand.cli} today`}622 title="Nothing to decide today. Undecided decisions expire to their safe default."623 />624 ) : (625 <DecisionSections listed={listed} props={props} />626 )}627 <Tomorrow overflow={today.overflow} />628 <Newcomers newcomers={today.newcomers} />629 <Unattended landings={today.unattended} now={now} />630 </Workspace>631 </div>632 );633};634635export const TodayView = ({636 decided = AsyncResult.initial(),637 now,638 onDecide,378 result,639 onSelect,640 read,641 selected,642}: {380 readonly result: AsyncResult.AsyncResult<Today, unknown>;643 readonly read: TodayRead;644 readonly now: DateTime.Utc;645 readonly onDecide: (input: DecideInput) => void;646 /** The decider's last choice, as `decide` answered it. */647 readonly decided?: AsyncResult.AsyncResult<648 { readonly decision: Decision },649 unknown650 >;388}) => {389 if (AsyncResult.isFailure(result)) {390 return <FailureView cause={result.cause} />;391 }392393 if (AsyncResult.isInitial(result)) {394 return <ReadingToday />;395 }396397 const today = result.value;398399 return (400 <>401 <Budget budget={today.budget} />402 <Decisions651 /** The decision the inspector holds (`project/id`); the first listed when none. */652 readonly selected?: string | undefined;653 readonly onSelect?: ((key: string) => void) | undefined;654}) =>655 TodayRead.match(read, {656 Read: ({ today }) => (657 <ListedToday658 decided={decided}659 now={now}660 onDecide={onDecide}661 onSelect={onSelect}662 selected={selected}663 today={today}664 />408 <Newcomers newcomers={today.newcomers} />409 <Unattended landings={today.unattended} now={now} />410 </>411 );412};665 ),666 Refused: ({ refusal }) => (667 <Unlisted>668 <p className="text-body max-w-[70ch]">{WHAT_TODAY_IS}</p>669 <RefusalView refusals={[refusal]} />670 <CommandLine command={`${Brand.cli} today`} />671 </Unlisted>672 ),673 SignedOut: () => (674 <Unlisted>675 <SignedOutNotice here="/today" />676 </Unlisted>677 ),678 Unreachable: () => (679 <Unlisted>680 <UnreachableNotice />681 </Unlisted>682 ),683 });
modified:apps/web/src/routes/$project/decisions/$decision.tsx+251 added-114 removed
1import { useAtom, useAtomValue } from "@effect/atom-react";2import { Brand } from "@repo/brand";3import type { Today } from "@repo/protocol/domain/decision";4import { DecisionId, ProjectName } from "@repo/protocol/ids";5import { createFileRoute, getRouteApi } from "@tanstack/react-router";6import { DateTime, Option, Schema } from "effect";1import { useAtom, useAtomMount, useAtomValue } from "@effect/atom-react";2import type { Decision } from "@repo/protocol/domain/decision";3import {4 createFileRoute,5 getRouteApi,6 useLocation,7 useRouter,8} from "@tanstack/react-router";9import { createServerFn } from "@tanstack/react-start";10import { getRequest } from "@tanstack/react-start/server";11import { env } from "cloudflare:workers";12import { Effect, Option, Schema } from "effect";13import type { DateTime } from "effect";14import { AsyncResult } from "effect/reactivity";15import { useCallback, useMemo, useState } from "react";169import {10 decideAtom,11 finishAskAtom,12 finishVerdictAtom,13} from "../../../client/decide.ts";14import { todayAtom } from "../../../client/today.ts";15import { DecisionCard } from "../../../features/decision/decision-card.tsx";17import { decideAtom } from "../../../client/decide.ts";18import { projectEventsAtom } from "../../../client/events.ts";19import { watchAtom } from "../../../client/watch.ts";20import { hereOf } from "../../../features/auth/session-slot.tsx";21import { useCodeFileKeys } from "../../../features/code/file-keys.ts";22import { parseDiffHash } from "../../../features/code/line-hash.ts";23import { SPLIT_QUERY, useMedia } from "../../../features/code/media.ts";24import { diffAnchor } from "../../../features/code/paths.ts";25import type { DecideInput } from "../../../features/decision/decision-card.tsx";26import { DecisionView } from "../../../features/decision/decision-page.tsx";27import {28 DecisionPageData,29 DecisionRead,30 newerThan,31 readDecision,32} from "../../../features/decision/read.ts";33import type { FoundDecision } from "../../../features/decision/read.ts";34import { patchFiles } from "../../../features/finish/files.ts";35import { FinishFilesButton } from "../../../features/finish/finish-files-button.tsx";36import { FinishRail } from "../../../features/finish/finish-rail.tsx";37import { FinishView } from "../../../features/finish/finish-view.tsx";38import {39 isFinishDecision,40 patchOf,41 waiverPatchOf,18import { isFinishDecision } from "../../../features/finish/patch.ts";42} from "../../../features/finish/patch.ts";43import type { FinishDecision } from "../../../features/finish/patch.ts";20import { EmptyState } from "../../../features/shared/empty.tsx";44import { marksKey, useReadMarks } from "../../../features/finish/read-marks.ts";45import { pageHead } from "../../../features/shared/head.ts";22import { PageShell } from "../../../features/shared/layout.tsx";23import {24 DecidedNotice,25 FailureView,26 findDecision,27 ReadingToday,28} from "../../../features/today/today-page.tsx";46import { personalPage } from "../../../server/cache-headers.ts";47import { serverClient } from "../../../server/client.ts";4830// `/$project/decisions/$decision`: one decision from the decider's Today in31// that project; for a `Finish`, the answer's diff, its ask and verdict, and32// the lines that finish it. The decision comes from `today` alone: someone33// who decides nothing there gets `NotDecider`, and no other read fetches a34// decision or a diff. Read in the browser, as Today is.49// `/$project/decisions/$decision`: one decision from the reader's Today in50// that project, read on the server with their own session; for a finish,51// the answer's diff, its ask and verdict, and where an earlier round was52// refused. The decision comes from `today` alone: someone who decides53// nothing there sees what a decision is and no evidence. A page about its54// reader is kept by no cache.5556const root = getRouteApi("__root__");5738const projectOf = Schema.decodeUnknownOption(ProjectName);58interface DecisionParams {59 readonly project: string;60 readonly decision: string;61}6240const decisionOf = Schema.decodeUnknownOption(DecisionId);63const decisionPage = createServerFn({ method: "GET" })64 .validator((params: DecisionParams) => params)65 .handler(({ data }) =>66 Effect.runPromise(67 readDecision(data).pipe(Effect.provide(serverClient(env, getRequest())))68 )69 );7042/** The ask and verdict a finish shows beside its diff, as they arrive. */43const Finish = ({ decision }: { readonly decision: FinishDecision }) => {44 const { platformUrl } = root.useLoaderData();45 const { ask, head } = decision.subject;46 const shown = useAtomValue(finishAskAtom(decision.project, ask));47 const judged = useAtomValue(finishVerdictAtom(decision.project, ask, head));71/** The decision the page found, when it found one. */72const foundOf = (read: DecisionRead): Option.Option<FoundDecision> =>73 DecisionRead.guards.Found(read) ? Option.some(read) : Option.none();7449 return (50 <FinishView51 ask={Option.getOrUndefined(AsyncResult.value(shown))?.ask}52 decision={decision}53 platformUrl={platformUrl}54 verdict={Option.getOrUndefined(AsyncResult.value(judged))?.verdict}55 />75/** The finish the page found, when the decision is one. */76const finishOf = (read: DecisionRead) =>77 Option.flatMap(foundOf(read), (found) =>78 isFinishDecision(found.decision)79 ? Option.some({ decision: found.decision, found })80 : Option.none()81 );57};8259const NotOnToday = ({ decision }: { readonly decision: string }) => (60 <EmptyState61 command={`${Brand.cli} today`}62 title={`Decision ${decision} is not on your Today: it was decided, it expired to its default, or it waits beyond today's budget.`}63 />64);83/** The decision as the reader's choice left it, once taken on this page. */84const takenHere = (85 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>,86 decision: Decision87) =>88 Option.getOrUndefined(89 Option.filter(90 Option.map(AsyncResult.value(decided), (taken) => taken.decision),91 (taken) =>92 taken.id === decision.id &&93 taken.project === decision.project &&94 taken.decided !== undefined95 )96 );9766/** The decision named, as the decider's Today in its project has it. */67const Found = ({98/** A finish's page: its files, folds, layout, read marks and keys. */99const Finish = ({100 busy,69 id,101 decision,102 found,103 now,104 onDecide,71 project,72 today,105 taken,106}: {74 readonly busy: boolean;75 readonly id: DecisionId;107 readonly decision: FinishDecision;108 readonly found: FoundDecision;109 readonly now: DateTime.Utc;110 readonly onDecide: (input: DecideInput) => void;77 readonly project: ProjectName;78 readonly today: AsyncResult.AsyncResult<Today, unknown>;111 readonly busy: boolean;112 readonly taken: Decision | undefined;113}) => {80 if (AsyncResult.isFailure(today)) {81 return <FailureView cause={today.cause} />;82 }114 const { platformUrl } = root.useLoaderData();115 const router = useRouter();116 const { ask, head } = decision.subject;11784 if (AsyncResult.isInitial(today)) {85 return <ReadingToday />;86 }118 // Live: a push to the answer while the page is open says so.119 useAtomMount(watchAtom(decision.project));120 const events = useAtomValue(projectEventsAtom(decision.project));12188 const found = findDecision(today.value, project, id);122 const newerHead =123 found.newerHead ??124 Option.getOrUndefined(125 Option.flatMapNullishOr(AsyncResult.value(events), (all) =>126 newerThan(all, ask, head)127 )128 );12990 if (Option.isNone(found)) {91 return <NotOnToday decision={id} />;92 }130 const files = useMemo(131 () =>132 Option.match(patchOf(decision), {133 onNone: () => [],134 onSome: (patch) =>135 patchFiles(136 patch,137 found.ask?.territory.paths ?? [],138 `${decision.project}/${decision.id}/${head}`139 ),140 }),141 [decision, found.ask, head]142 );14394 const { decision, soon } = found.value;144 const marked = useMemo(145 () => files.map(({ file, patchId }) => ({ patchId, path: file.path })),146 [files]147 );14896 // A finish is read whole (want, verdict, diff, the lines) before its97 // choices, which end the page.149 const { mark, read } = useReadMarks(150 marksKey(decision.project, decision.id),151 head,152 marked153 );154155 const [chosen, setChosen] = useState(false);156 const roomy = useMedia(SPLIT_QUERY);157 // Split only where the screen has room for two sides.158 const split = chosen && roomy;159160 const defaults = useMemo(161 () =>162 new Set(163 files.filter(({ folded }) => folded).map(({ file }) => file.path)164 ),165 [files]166 );167168 const [folded, setFolded] = useState<ReadonlySet<string>>(defaults);169170 const onFold = useCallback((path: string, fold: boolean) => {171 setFolded((was) => {172 if (was.has(path) === fold) {173 return was;174 }175176 const next = new Set(was);177178 if (fold) {179 next.add(path);180 } else {181 next.delete(path);182 }183184 return next;185 });186 }, []);187188 const current = useLocation({189 select: ({ hash }) =>190 Option.getOrUndefined(191 Option.map(parseDiffHash(hash), ({ path }) => path)192 ),193 });194195 const paths = useMemo(() => files.map(({ file }) => file.path), [files]);196197 useCodeFileKeys(paths, current, (path) => {198 Effect.runFork(199 Effect.tryPromise(() =>200 router.navigate({201 hash: diffAnchor(path),202 replace: true,203 resetScroll: false,204 to: ".",205 })206 ).pipe(Effect.ignore)207 );208 });209210 return (99 <DecisionCard211 <FinishView212 ask={found.ask}213 busy={busy}101 decision={decision}102 now={DateTime.nowUnsafe()}214 decision={215 taken === undefined ? decision : { ...taken, subject: decision.subject }216 }217 draw218 files={files}219 filesButton={<FinishFilesButton />}220 folded={folded}221 newerHead={newerHead}222 now={now}223 onDecide={onDecide}104 soon={soon}105 standalone106 >107 {isFinishDecision(decision) ? <Finish decision={decision} /> : undefined}108 </DecisionCard>224 onFold={onFold}225 onFoldAll={(fold) => {226 setFolded(fold ? new Set(paths) : new Set());227 }}228 onMark={mark}229 onSplit={setChosen}230 placed={found.placed}231 platformUrl={platformUrl}232 read={read}233 soon={found.soon}234 split={split}235 stamp={taken !== undefined}236 verdict={found.verdict}237 />238 );239};240112/** One project's Today, read for the decision page. */113const InProject = ({114 id,115 project,116}: {117 readonly id: DecisionId;118 readonly project: ProjectName;119}) => {120 const today = useAtomValue(todayAtom(project));241const DecisionPage = () => {242 const data = Schema.decodeSync(DecisionPageData)(Route.useLoaderData());243 const [decided, decide] = useAtom(decideAtom);244 const here = useLocation({ select: hereOf });245123 return (124 <>125 <div aria-live="polite">126 <DecidedNotice decided={decided} />127 </div>128 <Found129 busy={decided.waiting}130 id={id}131 onDecide={decide}132 project={project}133 today={today}134 />135 </>246 const waiverFiles = useMemo(247 () =>248 Option.getOrElse(249 Option.flatMap(foundOf(data.read), ({ decision }) =>250 Option.map(waiverPatchOf(decision), (patch) =>251 patchFiles(patch, [], `${decision.project}/${decision.id}`)252 )253 ),254 () => []255 ),256 [data.read]257 );137};258139const DecisionPage = () => {140 const params = Route.useParams();141 const project = projectOf(params.project);142 const id = decisionOf(params.decision);259 const found = finishOf(data.read);260261 const finish = Option.isSome(found) ? (262 <Finish263 busy={decided.waiting}264 decision={found.value.decision}265 found={found.value.found}266 now={data.now}267 onDecide={decide}268 taken={takenHere(decided, found.value.decision)}269 />270 ) : undefined;271272 return (145 <PageShell title={`Decision ${params.decision}`}>146 {Option.isSome(project) && Option.isSome(id) ? (147 <InProject id={id.value} project={project.value} />148 ) : (149 <NotOnToday decision={params.decision} />273 <DecisionView274 busy={decided.waiting}275 data={data}276 files={waiverFiles}277 finish={finish}278 here={here}279 onDecide={decide}280 taken={Option.getOrUndefined(281 Option.flatMapNullishOr(foundOf(data.read), ({ decision }) =>282 takenHere(decided, decision)283 )284 )}151 </PageShell>285 />286 );287};288289export const Route = createFileRoute("/$project/decisions/$decision")({290 staticData: { rail: FinishRail },291 loader: ({ params }) => decisionPage({ data: params }),292 headers: () => personalPage,293 head: ({ params }) =>294 pageHead({ title: `Decision ${params.decision} · ${params.project}` }),295 component: DecisionPage,157 head: ({ params }) => pageHead({ title: `Decision ${params.decision}` }),158 ssr: false,296});
modified:apps/web/src/routes/$project/proposals/$proposal.tsx+36 added-44 removed
1import {2 RegistryProvider,3 useAtom,4 useAtomMount,5 useAtomValue,6} from "@effect/atom-react";1import { useAtom, useAtomMount, useAtomValue } from "@effect/atom-react";2import { Client, ShowProposal } from "@repo/protocol/contracts";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Today } from "@repo/protocol/domain/decision";5import type { Proposal } from "@repo/protocol/domain/proposal";
1 unmodified line
7import type { DecisionId, Handle } from "@repo/protocol/ids";8import { createFileRoute, notFound, useLocation } from "@tanstack/react-router";9import { createServerFn } from "@tanstack/react-start";10import { env } from "cloudflare:workers";16import { Array, Effect, Option, Schema } from "effect";17import { AsyncResult, Atom } from "effect/reactivity";11import { Array, DateTime, Effect, Option, Schema } from "effect";12import { AsyncResult } from "effect/reactivity";1314import {15 draftAtom,16 projectTodayAtom,17 proposalAtom,18} from "../../../client/proposal.ts";19import { SeededAtoms, seedSuccess } from "../../../client/seeded.ts";20import { watchAtom } from "../../../client/watch.ts";21import { NotFoundView } from "../../../features/ask/refused.tsx";22import { hereOf } from "../../../features/auth/session-slot.tsx";23import { whoAtom } from "../../../features/auth/who.ts";27import { ProjectNav } from "../../../features/project/project-nav.tsx";28import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";24import { ProposalFailure } from "../../../features/proposal/failure.tsx";25import { ProposalView } from "../../../features/proposal/proposal-view.tsx";31import { EmptyState } from "../../../features/shared/empty.tsx";26import { pageHead } from "../../../features/shared/head.ts";33import { PageShell } from "../../../features/shared/layout.tsx";27import { notFoundFor, Refusals } from "../../../features/shared/refusals.ts";28import { personalPage } from "../../../server/cache-headers.ts";29import { serverClient } from "../../../server/client.ts";3031// `/$project/proposals/$proposal`: one proposal and the platform's draft of32// its ask. The loader reads `showProposal` on the server, so the page
19 unmodified lines
52 const client = yield* Client;5354 const shown = yield* client.showProposal({ project, proposal }).pipe(55 Effect.catchTags({61 UnknownProject: () => Effect.fail(notFound()),62 UnknownProposal: () => Effect.fail(notFound()),56 UnknownProject: notFoundFor,57 UnknownProposal: notFoundFor,58 })59 );6061 return yield* Schema.encodeEffect(ShowProposal.successSchema)(shown);
62 unmodified lines
124125 return (126 <ProposalView127 busy={redrafted.waiting}128 now={DateTime.nowUnsafe()}129 decision={decisionOn(today, proposal)}130 files={files}131 mayRedraft={mayRedraftAs(who, today, proposal)}132 onRedraft={(note) => {
26 unmodified lines
159160 const { id, project } = read.proposal;161162 return (167 <PageShell title={`${project}: proposal ${id}`}>168 <ProjectNav project={project} />169 <RegistryProvider170 initialValues={[171 Atom.initialValue(172 proposalAtom(project)(id),173 AsyncResult.success(read)174 ),175 ]}176 key={`${project}/${id}`}177 >178 <FreshProposal project={project} read={read} />179 </RegistryProvider>180 </PageShell>163 <SeededAtoms164 id={`${project}/${id}`}165 seeds={[seedSuccess(proposalAtom(project)(id), read)]}166 >167 <FreshProposal project={project} read={read} />168 </SeededAtoms>169 );170};171184const Unknown = () => {185 const { project, proposal } = Route.useParams();172const decodeRefusals = Schema.decodeUnknownOption(Refusals);173187 return Option.match(Schema.decodeUnknownOption(ProjectName)(project), {188 onNone: () => <UnknownProjectView name={project} />,189 onSome: (name) => (190 <PageShell title={`${name}: proposal ${proposal}`}>191 <ProjectNav project={name} />192 <EmptyState193 title={`${name} has no proposal ${proposal}, or no such project exists.`}194 />195 </PageShell>196 ),197 });198};174/** A proposal or a project the platform does not know: its refusal, as git prints it. */175const Unknown = ({ data }: { readonly data?: unknown }) => (176 <NotFoundView177 nothing="Nothing is at this address: a project's name is lowercase words joined by single dashes, and a proposal's id reads prop- and six digits."178 refusals={Option.getOrUndefined(decodeRefusals(data))}179 title="No such proposal"180 />181);182183export const Route = createFileRoute("/$project/proposals/$proposal")({184 loader: ({ params }) => proposalPage({ data: params }),202 head: ({ params: { project, proposal } }) =>203 pageHead({ title: `${project}: proposal ${proposal}` }),185 // Who may draft it again and the decision on it are the reader's own.186 headers: () => personalPage,187 head: ({ loaderData, params: { project, proposal } }) =>188 pageHead(189 loaderData === undefined190 ? { title: `${proposal} · ${project}` }191 : {192 description: loaderData.proposal.want,193 title: `${proposal} · ${project}`,194 }195 ),196 component: ProposalPage,197 notFoundComponent: Unknown,198});
modified:apps/web/src/routes/$project/proposals/new.tsx+4 added-20 removed
14 unmodified lines
15 proposeAtom,16} from "../../../client/propose.ts";17import { hereOf } from "../../../features/auth/session-slot.tsx";18import { whoAtom } from "../../../features/auth/who.ts";19import { ProjectNav } from "../../../features/project/project-nav.tsx";19import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";20import { ProposalFailure } from "../../../features/proposal/failure.tsx";21import { ProposeView } from "../../../features/propose/propose-view.tsx";22import type { About } from "../../../features/propose/propose-view.tsx";23import { pageHead } from "../../../features/shared/head.ts";25import { PageShell } from "../../../features/shared/layout.tsx";2425// `/$project/proposals/new`: the propose form. Who is signed in and the26// project's top folders are read in the browser (the server paints the27// page while it checks); a proposal made goes to its own page, a refusal
26 unmodified lines
54 line,55 path: about,56 }));5760const Checking = () => (61 <output className="text-muted-foreground block text-sm">62 Checking who is signed in63 </output>64);6558/** The form for `project`, once the browser knows who is signed in. */59const Propose = ({ project }: { readonly project: ProjectName }) => {60 const navigate = useNavigate();61 const search = Route.useSearch();
20 unmodified lines
82 });83 }84 }, [made, navigate, project]);8594 if (!AsyncResult.isSuccess(who)) {95 return <Checking />;96 }9786 return (87 <ProposeView88 about={aboutOf(search)}89 busy={proposed.waiting}90 checking={!AsyncResult.isSuccess(who)}91 modules={modules}92 onPropose={(payload) => {93 setSent(true);94 propose(payload);95 }}96 project={project}108 signedIn={Option.isSome(who.value)}97 signedIn={AsyncResult.isSuccess(who) && Option.isSome(who.value)}98 >99 {AsyncResult.isFailure(proposed) ? (100 <div aria-live="polite">101 <ProposalFailure
11 unmodified lines
113 const params = Route.useParams();114115 return Option.match(decodeProject(params.project), {116 onNone: () => <UnknownProjectView name={params.project} />,128 onSome: (project) => (129 <PageShell title={`${project}: propose an ask`}>130 <ProjectNav project={project} />131 <Propose project={project} />132 </PageShell>133 ),117 onSome: (project) => <Propose project={project} />,118 });119};120121export const Route = createFileRoute("/$project/proposals/new")({
7 unmodified lines
129 at: Option.getOrUndefined(decodeText(search.at)),130 line: Option.getOrUndefined(decodeLine(search.line)),131 }),132 head: ({ params: { project } }) =>149 pageHead({ title: `${project}: propose an ask` }),133 pageHead({ title: `Propose an ask · ${project}` }),134});
modified:apps/web/src/routes/today.tsx+102 added-23 removed
1import { useAtom, useAtomValue } from "@effect/atom-react";2import type { Today } from "@repo/protocol/domain/decision";3import { ProjectName } from "@repo/protocol/ids";4import { createFileRoute } from "@tanstack/react-router";5import { createServerFn } from "@tanstack/react-start";6import { getRequest } from "@tanstack/react-start/server";7import { env } from "cloudflare:workers";4import { DateTime, Option, Schema } from "effect";8import { Effect, Option, Schema } from "effect";9import { AsyncResult } from "effect/reactivity";1011import { decideAtom } from "../client/decide.ts";12import { SeededAtoms, seedSuccess } from "../client/seeded.ts";13import { todayAtom } from "../client/today.ts";14import { pageHead } from "../features/shared/head.ts";9import { PageShell } from "../features/shared/layout.tsx";15import {16 reloadOnEnter,17 useSelection,18} from "../features/shared/shell/selection.ts";19import {20 readOfCause,21 readToday,22 TodayPageData,23 TodayRead,24} from "../features/today/read.ts";25import { TodayView } from "../features/today/today-page.tsx";26import { personalPage } from "../server/cache-headers.ts";27import { serverClient } from "../server/client.ts";2829// `/today`: the signed-in decider's decisions across their projects, or in13// the one `?project=` names. A decider's page, read in the browser with the14// session cookie: the server renders the shell, never a decider's evidence.30// the one `?project=` names. The loader reads it on the server with the31// reader's own session (their cookie goes with the call), so the page32// arrives with its rows; in the browser the same read stays live, and a33// choice reads it again. A page about its reader is kept by no cache.3416const projectOf = Schema.decodeUnknownOption(ProjectName);35/** What the address may name: a project to narrow to, and the decision selected. */36const TodaySearch = Schema.Struct({37 decision: Schema.optionalKey(Schema.String),38 project: Schema.optionalKey(ProjectName),39});4041type TodaySearch = typeof TodaySearch.Type;4243const searchOf = Schema.decodeUnknownOption(TodaySearch);4445/** A page about its reader, kept by no cache. */46export const todayHeaders = () => personalPage;4748/** What the atom holds now, or the loader's read until it has read. */49const readFrom = (50 result: AsyncResult.AsyncResult<Today, unknown>,51 loaded: TodayRead52): TodayRead => {53 if (AsyncResult.isSuccess(result)) {54 return TodayRead.cases.Read.make({ today: result.value });55 }5657 return AsyncResult.isFailure(result) ? readOfCause(result.cause) : loaded;58};5960const todayPage = createServerFn({ method: "GET" })61 .validator((search: { readonly project?: ProjectName }) => search)62 .handler(({ data }) =>63 Effect.runPromise(64 readToday(data).pipe(Effect.provide(serverClient(env, getRequest())))65 )66 );6768/** Today over its atom, which starts from what the loader read and reads again after a choice. */69const LiveToday = ({70 data,71 project,72}: {73 readonly data: TodayPageData;74 readonly project: ProjectName | undefined;75}) => {76 const result = useAtomValue(todayAtom(project));77 const [decided, decide] = useAtom(decideAtom);78 const { select, selected } = useSelection("decision");7980 const read = readFrom(result, data.read);8182 return (83 <TodayView84 decided={decided}85 now={data.now}86 onDecide={decide}87 onSelect={select}88 read={read}89 selected={selected}90 />91 );92};9394const TodayPage = () => {95 const { project } = Route.useSearch();20 const today = useAtomValue(todayAtom(project));21 const [decided, decide] = useAtom(decideAtom);96 const data = Schema.decodeSync(TodayPageData)(Route.useLoaderData());9798 const seeds = TodayRead.match(data.read, {99 Read: ({ today }) => [seedSuccess(todayAtom(project), today)],100 Refused: () => [],101 SignedOut: () => [],102 Unreachable: () => [],103 });104105 return (24 <PageShell title={project === undefined ? "Today" : `Today in ${project}`}>25 <TodayView26 decided={decided}27 now={DateTime.nowUnsafe()}28 onDecide={decide}29 result={today}30 />31 </PageShell>106 <SeededAtoms id={`today/${project ?? ""}`} seeds={seeds}>107 <LiveToday data={data} project={project} />108 </SeededAtoms>109 );110};111112export const Route = createFileRoute("/today")({36 component: TodayPage,37 head: () => pageHead({ title: "Today" }),38 ssr: false,113 validateSearch: (search: {114 readonly decision?: unknown;115 readonly project?: unknown;41 }): { readonly project?: ProjectName } =>42 Option.match(projectOf(search.project), {43 onNone: () => ({}),44 onSome: (project) => ({ project }),45 }),116 }): TodaySearch => Option.getOrElse(searchOf(search), () => ({})),117 // A selection lives in the address; it never reads Today again.118 loaderDeps: ({ search }) =>119 search.project === undefined ? {} : { project: search.project },120 loader: ({ deps }) => todayPage({ data: deps }),121 shouldReload: reloadOnEnter,122 headers: todayHeaders,123 head: () => pageHead({ title: "Today" }),124 component: TodayPage,125});
modified:apps/web/test/decision.test.tsx+166 added-4 removed
15 unmodified lines
16import { DecisionSubject } from "@repo/protocol/domain/decision";17import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";18import { DraftState } from "@repo/protocol/domain/proposal";19import {20 AskId,21 CommitSha,22 DecisionId,23 Handle,24 LaneName,25 ProjectName,26 ProposalId,27 RepoPath,28} from "@repo/protocol/ids";29import { DecisionClosed } from "@repo/protocol/refusal";30import type { UnknownDecision } from "@repo/protocol/refusal";31import { asTester, unanswered } from "@repo/protocol/testing";30import { Cause, DateTime, Effect, Exit, Layer, Ref } from "effect";32import { Cause, DateTime, Effect, Exit, Layer, Option, Ref } from "effect";33import { AsyncResult, Atom, AtomRegistry, Reactivity } from "effect/reactivity";34import { RpcTest } from "effect/rpc";35import type { ReactElement } from "react";36import { renderToStaticMarkup } from "react-dom/server";
2 unmodified lines
39import { keys } from "../src/client/keys.ts";40import { todayAtom } from "../src/client/today.ts";41import { DecisionCard } from "../src/features/decision/decision-card.tsx";42import {43 DecisionRead,44 DecisionView,45} from "../src/features/decision/decision-page.tsx";46import type { DecisionPageData } from "../src/features/decision/decision-page.tsx";47import { patchFiles } from "../src/features/finish/files.ts";48import { waiverPatchOf } from "../src/features/finish/patch.ts";49import {50 DraftRead,51 draftReadOf,52 readDraft,53} from "../src/features/proposal/live-draft.ts";54import { RefusalView } from "../src/features/shared/refusal.tsx";55import {56 readOfCause,57 TodayRead,58 TodayView,46import { TodayView } from "../src/features/today/today-page.tsx";59} from "../src/features/today/today-page.tsx";60import { ContractsClient, webContracts } from "../src/surfaces.ts";6162const markupOf = (element: ReactElement) => renderToStaticMarkup(element);6364/** What a reader sees of `markup`: the text without its tags. */65const plainTextOf = (markup: string) =>66 markup67 .replaceAll(/<[^>]+>/gu, " ")68 .replaceAll("&#x27;", "'")69 .replaceAll("&quot;", '"')70 .replaceAll("&amp;", "&")71 .replaceAll(/\s+/gu, " ");7273/** Today as the page reads it from the atom: listed, or why not. */74const readOf = (result: AsyncResult.AsyncResult<Today, unknown>): TodayRead => {75 if (AsyncResult.isSuccess(result)) {76 return TodayRead.cases.Read.make({ today: result.value });77 }7879 return AsyncResult.isFailure(result)80 ? readOfCause(result.cause)81 : TodayRead.cases.Unreachable.make({});82};8384const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");8586const okonkwo = Handle.make("okonkwo");87
197 unmodified lines
285 listAsks: asked.listAsks,286 today: asked.today,287 }).toStrictEqual({ listAsks: 2, today: 2 });288 expect(256 markupOf(<TodayView now={now} onDecide={() => {}} result={today} />)289 markupOf(290 <TodayView now={now} onDecide={() => {}} read={readOf(today)} />291 )292 ).not.toContain('data-decision="dec-000002"');293 })294 );295
12 unmodified lines
308 <TodayView309 decided={decided}310 now={now}311 onDecide={() => {}}277 result={today}312 read={readOf(today)}313 />314 );315316 expect(Exit.isFailure(outcome)).toBeTruthy();
191 unmodified lines
508 it("links the proposal's page", () => {509 expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');510 });511});512513const vellum = ProjectName.make("vellum");514515/** A waiver on the answer to escape-attribute-quotes, carrying the answer's diff of the marker's file. */516const waiver: Decision = {517 deciders: [okonkwo],518 default: "decline",519 evidence: [520 {521 label: "patch",522 value: [523 "diff --git a/test/attributes.test.ts b/test/attributes.test.ts",524 "index 1111111..2222222 100644",525 "--- a/test/attributes.test.ts",526 "+++ b/test/attributes.test.ts",527 "@@ -6,4 +6,5 @@",528 ' import { escape } from "../src/escape.ts";',529 " ",530 ' test("quotes", () => {',531 '+test.skip("a quote in a code span", () => {});',532 ' expect(escape(\'"\')).toBe("&quot;");',533 "",534 ].join("\n"),535 },536 ],537 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),538 id: DecisionId.make("dec-000002"),539 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),540 project: vellum,541 subject: DecisionSubject.cases.Waiver.make({542 ask: AskId.make("escape-attribute-quotes"),543 at: { line: 9, path: RepoPath.make("test/attributes.test.ts") },544 marker: ".skip(",545 reason: "A quote in a code span needs the escaper's context.",546 }),547};548549const pageOf = (read: DecisionRead, chosen?: Decision) => {550 const data: DecisionPageData = {551 decision: waiver.id,552 now,553 project: vellum,554 read,555 };556557 const files = DecisionRead.guards.Found(read)558 ? Option.match(waiverPatchOf(read.decision), {559 onNone: () => [],560 onSome: (patch) => patchFiles(patch, [], "test"),561 })562 : [];563564 return markupOf(565 <DecisionView566 data={data}567 files={files}568 here="/vellum/decisions/dec-000002"569 onDecide={() => {}}570 taken={chosen}571 />572 );573};574575const found = DecisionRead.cases.Found.make({576 decision: waiver,577 placed: [],578 soon: true,579});580581describe(DecisionView, () => {582 it("titles the page with the subject and says when it expires, its default and whose move it is", () => {583 const text = plainTextOf(pageOf(found));584585 expect(text).toContain(586 "Allow .skip( at test/attributes.test.ts:9 in the answer to escape-attribute-quotes"587 );588 expect(text).toContain("Expires in 22 h");589 expect(text).toContain("default: decline");590 expect(text).toContain("your move");591 });592593 it("draws a waiver's marker at its line, in the answer's diff of that file", () => {594 const markup = pageOf(found);595 const line = markup.indexOf('data-line="9"');596 const note = markup.indexOf('data-note-line="9"');597 const after = markup.indexOf('data-line="10"');598599 expect(markup).toContain('data-file="test/attributes.test.ts"');600 expect(line).toBeGreaterThan(-1);601 expect(note).toBeGreaterThan(line);602 expect(after).toBeGreaterThan(note);603 expect(markup.slice(note, after)).toContain('data-marker=".skip("');604 });605606 it("says under each choice what it does", () => {607 const markup = pageOf(found);608609 expect(markup).toContain('data-consequence="accept"');610 expect(markup).toContain('data-consequence="decline"');611 expect(plainTextOf(markup)).toContain(612 "The answer goes on through the gate with .skip( allowed there, with you as Decided-by."613 );614 });615616 it("once decided, shows the record and no choices", () => {617 const markup = pageOf(found, {618 ...waiver,619 decided: { at: now, by: okonkwo, choice: "accept", note: "Split out." },620 });621622 expect(markup).not.toContain("data-choice=");623 expect(markup).toContain('data-decided="accept"');624 expect(plainTextOf(markup)).toContain("Accepted");625 expect(plainTextOf(markup)).toContain("Split out.");626 });627628 it("signed out, says what a decision is and who takes it, with no choices and no evidence", () => {629 const markup = pageOf(DecisionRead.cases.SignedOut.make({}));630 const text = plainTextOf(markup);631632 expect(markup).not.toContain("data-choice=");633 expect(markup).not.toContain(".skip(");634 expect(text).toContain("A decider takes it on their Today");635 expect(markup).toContain('href="/vellum/people"');636 expect(text).toContain(`${Brand.cli} today --project vellum`);637 });638});
modified:apps/web/test/finish.test.tsx+228 added-49 removed
1/**2 * Finishing an answer from its diff: a `Finish` decision's page shows the3 * answer's diff (drawn by `@pierre/diffs`), beside the ask's want and the4 * verdict, and the git lines that fetch the head and finish it locally. The5 * diff comes only from the decision's own `patch` evidence; without one the6 * page shows the lines and no diff. Rendered with `react-dom/server`.2 * Finishing an answer from its diff: a `Finish` decision's page lays the3 * answer's diff out as the code browser does. The server sends it as plain4 * text (the browser draws it over in place), its files with the ask's5 * territory first, then tests, then the rest; a refusal from an earlier6 * round sits under the line it pointed at; each file can be marked read in7 * this browser alone; a newer head says so above the diff; and the three8 * lines that fetch the head and finish it are numbered. The diff comes only9 * from the decision's own `patch` evidence; without one the page shows the10 * lines and no diff. Rendered with `react-dom/server`.11 */12import { describe, expect, it } from "@effect/vitest";13import { Brand } from "@repo/brand";14import type { Verdict } from "@repo/protocol/domain/answer";
17 unmodified lines
32 ProposalId,33 RepoPath,34 TreeSha,35} from "@repo/protocol/ids";36import { Weakened } from "@repo/protocol/refusal";37import { DateTime, Option } from "effect";38import type { ReactElement } from "react";39import { renderToStaticMarkup } from "react-dom/server";4041import type { PlacedRefusal } from "../src/features/finish/annotation.tsx";42import { patchFiles } from "../src/features/finish/files.ts";43import { FinishView } from "../src/features/finish/finish-view.tsx";37import type { FinishDecision } from "../src/features/finish/finish-view.tsx";38import { PatchDiffs } from "../src/features/finish/patch-diff.tsx";44import type {45 FinishDecision,46 FinishViewProps,47} from "../src/features/finish/finish-view.tsx";48import { changedFiles, patchOf } from "../src/features/finish/patch.ts";49import {50 marksKey,51 readMarks,52 writeMark,53} from "../src/features/finish/read-marks.ts";5455/** The entities React writes for text, and what each reads as. */56const ENTITIES: ReadonlyMap<string, string> = new Map([57 ["&#x27;", "'"],
132 unmodified lines
190 tree: TreeSha.make("3".repeat(40)),191 verifier: "platform",192};193180const drawn = (patch: string) => <PatchDiffs patch={patch} />;194const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");195196const filesOf = (decision: FinishDecision) =>197 Option.match(patchOf(decision), {198 onNone: () => [],199 onSome: (patch) => patchFiles(patch, ["src/**"], "test"),200 });201202const pageOf = (203 decision: FinishDecision,204 extra: Partial<FinishViewProps> = {}205) => (206 <FinishView207 decision={decision}208 files={filesOf(decision)}209 now={now}210 onDecide={() => {}}211 platformUrl={PLATFORM_URL}212 {...extra}213 />214);215216/** The files the server's diff draws, in its order. */217const drawnFilesOf = (markup: string) =>218 [...markup.matchAll(/<section aria-label="(?<file>[^"]+)" data-file=/gu)].map(219 (match) => match.groups?.file220 );221222/** A refusal from the answer's first round, at line 2 of its test. */223const placed: PlacedRefusal = {224 line: 2,225 path: "test/parse.test.ts",226 refusal: new Weakened({227 at: { line: 2, path: RepoPath.make("test/parse.test.ts") },228 weakening: { marker: ".only(" },229 }),230 round: 1,231};232233describe(FinishView, () => {183 it("draws the answer's diff with @pierre/diffs, one view per changed file, named", () => {184 const element = (185 <FinishView186 decision={withPatch}187 diff={drawn}188 platformUrl={PLATFORM_URL}189 />234 it("lists the changed files on the server, the territory's first, then tests, then the rest", () => {235 expect(drawnFilesOf(markupOf(pageOf(withPatch)))).toStrictEqual([236 "src/iso.ts",237 "src/legacy.ts",238 "src/parse.ts",239 "test/parse.test.ts",240 "docs/new.md",241 ]);242243 for (const file of FILES) {244 expect(textOf(pageOf(withPatch))).toContain(file);245 }246 });247248 it("leaves the drawing to the browser: the server sends the diff as plain text", () => {249 const markup = markupOf(pageOf(withPatch));250251 expect(markup).not.toContain("<diffs-container");252 expect(markup).toContain('data-diff="plain"');253 expect(markup).toContain(254 "export const parse = (text: string) =&gt; fromIso(text);"255 );256 });257192 // Each file's view, by the name it carries: the region around one193 // `<diffs-container>`.194 const views = [195 ...markupOf(element).matchAll(196 /<section aria-label="(?<file>[^"]+)"><diffs-container\b/gu197 ),198 ].map((view) => view.groups?.file);258 it("draws a refusal under the line its `at` names, in the file it names", () => {259 const markup = markupOf(pageOf(withPatch, { placed: [placed] }));260 const file = markup.indexOf('data-file="test/parse.test.ts"');261 const line = markup.indexOf('data-line="2"', file);262 const note = markup.indexOf('data-note-line="2"', file);263200 expect(views).toStrictEqual(FILES);264 expect(file).toBeGreaterThan(-1);265 expect(note).toBeGreaterThan(line);266 expect(markup.slice(note)).toContain('data-refusal="Weakened"');267 expect(textOf(pageOf(withPatch, { placed: [placed] }))).toContain(268 "Refused here in round 1"269 );270 });271203 it("names the changed files on the server and leaves the drawing to the browser", () => {204 const element = (205 <FinishView decision={withPatch} platformUrl={PLATFORM_URL} />272 it("counts the files read, never a person, and offers Mark read on each file", () => {273 const markup = markupOf(274 pageOf(withPatch, { read: new Set(["src/parse.ts"]) })275 );276208 expect(markupOf(element)).not.toContain("<diffs-container");209210 for (const file of FILES) {211 expect(textOf(element)).toContain(file);212 }277 expect(278 textOf(pageOf(withPatch, { read: new Set(["src/parse.ts"]) }))279 ).toContain("1 of 5 files read");280 expect(markup).toContain('data-mark-read="src/iso.ts"');281 expect(markup).toMatch(282 /aria-pressed="true"[^>]*data-mark-read="src\/parse.ts"/u283 );284 expect(textOf(pageOf(withPatch))).toContain("Mark read");285 expect(textOf(pageOf(withPatch))).not.toMatch(/review/iu);286 });287215 it("without a patch, shows the lines that fetch the head and finish it, and no diff", () => {216 const element = (217 <FinishView decision={withoutPatch} platformUrl={PLATFORM_URL} />288 it("says a newer head was pushed, above the diff, and keeps the diff the decision names", () => {289 const text = textOf(pageOf(withPatch, { newerHead: base }));290291 expect(text).toContain("A new answer was pushed");292 expect(text).toContain("Reload the diff");293 expect(text).toContain(294 "export const parse = (text: string) => fromIso(text);"295 );296 });297298 it("numbers the three lines that finish it", () => {299 const markup = markupOf(pageOf(withPatch));300301 const list =302 /<ol[^>]*data-finish-lines=""[^>]*>(?<items>[\s\S]*?)<\/ol>/u.exec(markup)303 ?.groups?.items;304305 expect([...(list ?? "").matchAll(/<li\b/gu)]).toHaveLength(3);306 });307308 it("without a patch, shows the lines that fetch the head and finish it, and no diff", () => {309 const element = pageOf(withoutPatch);310 const text = textOf(element);311312 expect(text).toContain(`git fetch ${PLATFORM_URL}/`);313 expect(text).toContain(` ${head}`);
7 unmodified lines
321 ...withoutPatch.evidence,322 { label: "fork", value: "datekit--parse-iso--ines-v" },323 ]);324235 const text = textOf(236 <FinishView237 decision={named}238 platformUrl={PLATFORM_URL}239 verdict={verdict}240 />241 );325 const text = textOf(pageOf(named, { verdict }));326327 expect(text).toContain(328 `git fetch ${PLATFORM_URL}/datekit--parse-iso--ines-v.git ${head}`329 );330 expect(text).toContain(`--base ${base}`);331 });332333 it("shows the ask's want and the verdict beside the diff", () => {250 const element = (251 <FinishView252 ask={ask}253 decision={withPatch}254 platformUrl={PLATFORM_URL}255 verdict={verdict}256 />257 );334 const element = pageOf(withPatch, { ask, verdict });335336 expect(textOf(element)).toContain(337 "An ISO date with a leap day parses to that day."338 );339 expect(markupOf(element)).toContain('data-outcome="AwaitingFinish"');340 });341342 it("offers its choices with what each does", () => {343 const text = textOf(pageOf(withPatch));344345 expect(text).toContain(346 "Lands the answer as it is, with you as Finished-by."347 );348 expect(text).toContain(349 "Nothing lands; the answer keeps waiting for a finish."350 );351 });352});353354/** A browser storage over a map, as `localStorage` behaves. */355const storageOver = (kept: Map<string, string>): Storage => ({356 clear: () => {357 kept.clear();358 },359 getItem: (key) => kept.get(key) ?? null,360 key: (index) => [...kept.keys()][index] ?? null,361 get length() {362 return kept.size;363 },364 removeItem: (key) => {365 kept.delete(key);366 },367 setItem: (key, value) => {368 kept.set(key, value);369 },370});371372/** A storage that refuses every read and write, as a private window's may. */373const refusing: Storage = {374 clear: () => {375 throw new Error("refused");376 },377 getItem: () => {378 throw new Error("refused");379 },380 key: () => {381 throw new Error("refused");382 },383 length: 0,384 removeItem: () => {385 throw new Error("refused");386 },387 setItem: () => {388 throw new Error("refused");389 },390};391392describe("the read marks", () => {393 const key = marksKey("datekit", "dec-000007");394395 const files = filesOf(withPatch).map(({ file, patchId }) => ({396 patchId,397 path: file.path,398 }));399400 const [first] = files;401402 it("marks a file read in this browser, against its change", () => {403 const storage = storageOver(new Map());404405 if (first !== undefined) {406 writeMark(storage, key, head, first, true);407 }408409 expect([...readMarks(storage, key, head, files)]).toStrictEqual([410 "src/iso.ts",411 ]);412 });413414 it("forgets every mark once a new head is pushed", () => {415 const storage = storageOver(new Map());416417 if (first !== undefined) {418 writeMark(storage, key, head, first, true);419 }420421 expect(readMarks(storage, key, base, files).size).toBe(0);422 });423424 it("reads a file unread when its change is not the one marked", () => {425 const storage = storageOver(new Map());426427 if (first !== undefined) {428 writeMark(storage, key, head, { ...first, patchId: "00000000" }, true);429 }430431 expect(readMarks(storage, key, head, files).size).toBe(0);432 });433434 it("keeps working, with no marks, when the storage refuses", () => {435 expect(() => {436 if (first !== undefined) {437 writeMark(refusing, key, head, first, true);438 }439 }).not.toThrow();440 expect(readMarks(refusing, key, head, files).size).toBe(0);441 expect(readMarks(undefined, key, head, files).size).toBe(0);442 });443});444445describe(patchOf, () => {446 it("gives the diff a Finish decision carries, and nothing for one without", () => {447 expect(patchOf(withPatch)).toStrictEqual(Option.some(PATCH));448 expect(patchOf(withoutPatch)).toStrictEqual(Option.none());
45 unmodified lines
modified:apps/web/test/proposal.test.tsx+47 added-5 removed
121 unmodified lines
122 expect(text).toContain("formatISO keeps the offset it was given.");123 expect(text).toContain("lin-h");124 });125126 it("while drafting, shows the spinner and no Draft again", () => {126 it("titles the page with the want, never the proposal's id", () => {127 expect(view(drafting)).toMatch(128 /<h1[^>]*>formatISO keeps the offset it was given\.<\/h1>/u129 );130 });131132 it("while drafting, says so in the checking role, and offers no Draft again", () => {133 const markup = view(drafting);134129 expect(markup).toContain('data-slot="spinner"');130 expect(plainText(markup)).toContain("Drafting");135 expect(markup).toMatch(/data-tone="checking"[^>]*>[\s\S]*?Drafting/u);136 expect(markup).not.toMatch(DRAFT_AGAIN);137 });138139 it("once ready, says it waits for a decider, in the waiting role", () => {140 const markup = view(ready);141142 expect(markup).toMatch(/data-tone="waiting"/u);143 expect(plainText(markup)).toContain("Ready , waits for a decider");144 });145146 it("reads the draft as a guide, in its order: the ask file, the check, red first", () => {147 const text = plainText(view(ready));148149 expect(text.indexOf("The ask file")).toBeLessThan(150 text.indexOf("The check")151 );152 expect(text.indexOf("The check")).toBeLessThan(text.indexOf("Red first"));153 expect(view(ready)).not.toMatch(/<h2[^>]*>\s*0[1-9]/u);154 });155156 it("while drafting with a note, shows the note the round was asked with", () => {157 const noted = withDraft(158 shownWith([]),159 DraftState.cases.Drafting.make({
19 unmodified lines
179 expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);180 expect(markup).toContain('href="/datekit/decisions/dec-000003"');181 });182161 it("once ready, shows no spinner", () => {183 it("once ready, draws nothing in the checking role", () => {184 expect(view(ready)).not.toContain('data-tone="checking"');185 expect(view(ready)).not.toContain('data-slot="spinner"');186 });187165 it("once failed, shows the last refusal's headline and Draft again", () => {188 it("once failed with a refusal, draws it as git prints it, and offers Draft again", () => {189 const markup = view(failed);190191 expect(plainText(markup)).toContain("NotRedFirst");192 expect(markup).toContain('data-refusal="NotRedFirst"');193 expect(markup).toMatch(DRAFT_AGAIN);194 });195196 it("once failed with a refusal it cannot draw whole, says so in ink, never in the refused role", () => {197 const weak = withDraft(198 shownWith([]),199 DraftState.cases.Failed.make({200 attempts: 3,201 model,202 refusal: "WeakCheck",203 round: 1,204 })205 );206207 const markup = view(weak);208209 expect(plainText(markup)).toContain("The draft failed: WeakCheck");210 expect(markup).not.toContain("text-refused");211 expect(markup).not.toContain("data-refusal=");212 });213214 it("failed after a ready round, still shows that round's files as a draft a decider can accept", () => {215 const kept = withDraft(216 ready,217 DraftState.cases.Failed.make({
260 unmodified lines
modified:apps/web/test/propose.test.tsx+38 added-4 removed
18 unmodified lines
19import { ProposalFailure } from "../src/features/proposal/failure.tsx";20import {21 ProposeView,22 proposalPayload,23 territoryChoices,24} from "../src/features/propose/propose-view.tsx";25import type { About } from "../src/features/propose/propose-view.tsx";26import { markupOf, plainText } from "./ask-fixtures.ts";27
22 unmodified lines
50 );51 expect(plainText(markup)).toContain(52 "Let the platform's agent draft the ask"53 );53 expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Propose/u);54 expect(markup).toMatch(/<button[^>]*type="submit"/u);55 });5656 it("offers each of the project's top folders as the territory", () => {57 it("says on Propose why it waits, until there is a want", () => {58 const empty = signedIn();5960 const written = signedIn(61 Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })62 );6364 expect(empty).toMatch(65 /<button(?=[^>]*disabled="")(?=[^>]*type="submit")[^>]*>Write the want first<\/button>/u66 );67 expect(written).toMatch(68 /<button[^>]*type="submit"[^>]*>Propose<\/button>/u69 );70 expect(written).not.toMatch(71 /<button(?=[^>]*disabled="")(?=[^>]*type="submit")/u72 );73 });7475 it("offers each of the project's top folders as the territory, through the kit's select, never a native one", () => {76 const markup = signedIn();7778 expect(markup).toContain('name="territory"');60 expect(markup).toContain('<option value="src">src</option>');61 expect(markup).toContain('<option value="docs">docs</option>');79 expect(markup).not.toContain("<select");80 expect(markup).toContain('data-slot="select-trigger"');81 expect(territoryChoices(modules)).toStrictEqual([82 { label: "Let the agent choose", value: "" },83 { label: "docs", value: "docs" },84 { label: "src", value: "src" },85 ]);86 });8788 it("gives the same proposal as a command, and what makes a good want", () => {89 const text = plainText(signedIn());9091 expect(text).toContain(`${Brand.cli} propose --draft "<want>"`);92 expect(text).toContain("not how to change the code");93 });9495 it("starts the want at the line a why page names", () => {96 const markup = signedIn(97 Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })98 );
15 unmodified lines
114115 expect(markup).not.toContain("<form");116 expect(markup).not.toContain("<textarea");117 expect(markup).toMatch(/<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in/u);118 expect(plainText(markup)).toContain(119 `${Brand.cli} propose --draft "<want>"`120 );121 });122});123124describe(proposalPayload, () => {
142 unmodified lines
modified:apps/web/test/today.test.tsx+367 added-61 removed
1/**2 * Today, as a decider reads it: decisions, not diffs, against the day's3 * budget. Each decision says in plain words what it is about, what happens4 * if nobody decides (its own `default`) and when, and offers only the5 * choices its subject allows. Rendered to HTML with `react-dom/server`.3 * budget, said in one sentence. The decisions sit in sections (due today,4 * then the rest by expiry), each row's link the subject in plain words;5 * then how many wait for tomorrow, the newcomers to welcome and the6 * landings that needed nobody. Every choice says what it does under it.7 * A choice taken leaves its row where it was, reading what it did.8 *9 * Rendered to HTML with `react-dom/server`, and read through the route's10 * loader over the dev world with its fixtures, signed in as a decider.11 */12import { describe, expect, it } from "@effect/vitest";13import { Brand } from "@repo/brand";14import { Client, Contracts } from "@repo/protocol/contracts";15import { RefNameText } from "@repo/protocol/domain/common";16import { DecisionSubject } from "@repo/protocol/domain/decision";10import type { Decision, Today } from "@repo/protocol/domain/decision";17import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";18import type { LandingView } from "@repo/protocol/domain/landing";19import {20 AskId,21 CommitSha,
5 unmodified lines
27 ProposalId,28 RatchetName,29 RepoPath,30} from "@repo/protocol/ids";24import { NotDecider } from "@repo/protocol/refusal";25import { Cause, DateTime } from "effect";31import { DecisionClosed, NotDecider } from "@repo/protocol/refusal";32import { Cause, DateTime, Effect, Layer, Schema } from "effect";33import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";34import { AsyncResult } from "effect/reactivity";35import { RpcClient, RpcSerialization } from "effect/rpc";36import type { ReactElement } from "react";37import { renderToStaticMarkup } from "react-dom/server";3839import { devServer } from "../src/dev/server.ts";40import { devToken } from "../src/dev/sessions.ts";41import {42 allowedChoices,43 consequenceOf,44 describeSubject,45} from "../src/features/decision/decision-card.tsx";46import { RefusalView } from "../src/features/shared/refusal.tsx";47import { readToday } from "../src/features/today/read.ts";48import {49 budgetSentence,50 orderDecisions,51 TodayPageData,52 TodayRead,53 TodayView,54} from "../src/features/today/today-page.tsx";55import { Route, todayHeaders } from "../src/routes/today.tsx";5657/** The entities React writes for text, and what each reads as. */58const ENTITIES: ReadonlyMap<string, string> = new Map([59 ["&#x27;", "'"],
4 unmodified lines
64]);6566const markupOf = (element: ReactElement) => renderToStaticMarkup(element);6751/** What a reader sees: the markup without its tags, entities decoded. */52const textOf = (element: ReactElement) =>53 markupOf(element)68/** What a reader sees of `markup`: the text without its tags, entities decoded. */69const textIn = (markup: string) =>70 markup71 .replaceAll(/<[^>]+>/gu, " ")72 .replaceAll(73 /&(?:#x27|amp|gt|lt|quot);/gu,74 (entity) => ENTITIES.get(entity) ?? entity75 )76 .replaceAll(/\s+/gu, " ");7761/** Each decision card's id, in the order the page lists them. */62const cardsOf = (element: ReactElement) =>63 [...markupOf(element).matchAll(/data-decision="(?<id>[^"]+)"/gu)].map(64 (match) => match.groups?.id65 );78const textOf = (element: ReactElement) => textIn(markupOf(element));7967/** The choices each card offers, as `id: choice choice`. */68const choicesOf = (element: ReactElement) => {69 const markup = markupOf(element);80/** Each row's markup, by the decision it stands for, in the order the page lists them: from its `<li>` to the next row or the end of its list. */81const rowsOf = (markup: string) => {82 const starts = [83 ...markup.matchAll(/<li[^>]*data-decision="(?<id>[^"]+)"[^>]*>/gu),84 ];8571 return [...markup.matchAll(/data-decision="(?<id>[^"]+)"/gu)].map(72 (match, index, all) => {73 const end = all[index + 1]?.index ?? markup.length;74 const card = markup.slice(match.index, end);86 return starts.map((match, index) => {87 const start = match.index;88 const listEnd = markup.indexOf("</ul></section>", start);89 const next = starts[index + 1]?.index ?? markup.length;9076 const choices = [77 ...card.matchAll(/data-choice="(?<choice>[^"]+)"/gu),78 ].map((each) => each.groups?.choice);91 return {92 body: markup.slice(93 start,94 listEnd === -1 ? next : Math.min(next, listEnd)95 ),96 id: match.groups?.id ?? "",97 };98 });99};10080 return `${match.groups?.id}: ${choices.join(" ")}`;81 }101/** The choices each row offers, as `id: choice choice`. */102const choicesOf = (markup: string) =>103 rowsOf(markup).map(104 ({ body, id }) =>105 `${id}: ${[...body.matchAll(/data-choice="(?<choice>[^"]+)"/gu)]106 .map((each) => each.groups?.choice)107 .join(" ")}`108 );109110/** The section headers, in the order the page shows them. */111const sectionsOf = (markup: string) => {112 const main = markup.includes("<aside")113 ? markup.slice(0, markup.indexOf("<aside"))114 : markup;115116 return [...main.matchAll(/<h2[^>]*>(?<name>[^<]+)<\/h2>/gu)].map(117 (match) => match.groups?.name118 );119};120121const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");122
76 unmodified lines
199 landing("d", "parse-iso", "2026-10-06T18:00:00Z"),200 ],201};202167const page = (168 <TodayView169 now={now}170 onDecide={() => {}}171 result={AsyncResult.success(today)}172 />173);203const viewOf = (204 read: TodayRead,205 extra: Partial<Parameters<typeof TodayView>[0]> = {}206) => <TodayView now={now} onDecide={() => {}} read={read} {...extra} />;207208const page = viewOf(TodayRead.cases.Read.make({ today }));209210describe(TodayView, () => {176 it("counts decisions against the budget and finishes apart", () => {211 it("says the budget as one sentence, the finishes counted apart", () => {212 const text = textOf(page);213179 expect(text).toContain("2 of 5");180 expect(text).toContain("1 finish");214 expect(text).toContain(215 "Decisions: 2 taken, 3 left today. Finishes are counted apart: 1 taken."216 );217 expect(markupOf(page)).toContain('data-budget="2/5"');218 expect(text).not.toContain("2 of 5");219 expect(text).not.toContain("3 of 5");220 });221222 it("says none when no finish was taken", () => {223 expect(budgetSentence({ finishes: 0, total: 5, used: 5 })).toBe(224 "Decisions: 5 taken, none left today. Finishes are counted apart: none taken."225 );226 });227228 it("puts its sections in order, each under its header", () => {229 expect(sectionsOf(markupOf(page))).toStrictEqual([230 "Due today",231 "Within your budget",232 "Waits for tomorrow",233 "Newcomers to welcome",234 "Landed without a decision",235 ]);236 });237238 it("lists the decision expiring soon first, then the rest by expiry", () => {185 expect(cardsOf(page)).toStrictEqual([239 expect(rowsOf(markupOf(page)).map(({ id }) => id)).toStrictEqual([240 "dec-000002",241 "dec-000003",242 "dec-000001",243 ]);244 });245246 it("links each row by its subject in plain words, never by its id", () => {247 const links = [248 ...markupOf(page).matchAll(249 /<a[^>]*data-list-key="(?<key>[^"]+)"[^>]*>(?<text>[^<]*)<\/a>/gu250 ),251 ].flatMap((match) =>252 match.groups?.key?.includes("/dec-") === true253 ? [[match.groups.key, textIn(match.groups.text ?? "")]]254 : []255 );256257 expect(links).toStrictEqual([258 [259 "datekit/dec-000002",260 "main moved without a landing, from aaaaaaa to bbbbbbb",261 ],262 ["datekit/dec-000003", "Vouch for lin-h, so they may claim asks"],263 ["burrow/dec-000001", "Open the ask proposed in prop-000004"],264 ]);265 });266267 it("says when each expires and its default at the row's end", () => {268 const [first] = rowsOf(markupOf(page));269270 expect(textIn(first?.body ?? "")).toContain("in 22 h");271 expect(textIn(first?.body ?? "")).toContain("default: revert");272 });273274 it("says what happens if nobody decides, from the decision's own default, and when it expires", () => {275 const text = textOf(page);276277 expect(text).toContain("If nobody decides by Thu 8 Oct, 10:00 UTC: revert");
7 unmodified lines
285 it("takes the default's word from the decision, never from its subject", () => {286 const adopting = { ...stray, default: "adopt" } as const;287288 const text = textOf(207 <TodayView208 now={now}209 onDecide={() => {}}210 result={AsyncResult.success({ ...today, decisions: [adopting] })}211 />289 viewOf(290 TodayRead.cases.Read.make({291 today: { ...today, decisions: [adopting] },292 })293 )294 );295296 expect(text).toContain("If nobody decides by Thu 8 Oct, 10:00 UTC: adopt");297 });298217 it("says what each decision is about in plain words", () => {218 const text = textOf(page);299 it("says how many more wait for tomorrow", () => {300 const markup = markupOf(page);301220 expect(text).toContain(221 "main moved without a landing, from aaaaaaa to bbbbbbb"222 );223 expect(text).toContain("Vouch for lin-h, so they may claim asks");224 expect(text).toContain("Open the ask proposed in prop-000004");302 expect(textIn(markup)).toContain("4 more wait for tomorrow");303 expect(markup).toContain('data-overflow="4"');304 expect(305 textOf(306 viewOf(TodayRead.cases.Read.make({ today: { ...today, overflow: 3 } }))307 )308 ).toContain("3 more wait for tomorrow");309 });310227 it("says how many more wait for tomorrow", () => {228 expect(textOf(page)).toContain("4 more wait for tomorrow");229 });230311 it("names the newcomers to welcome and the landings that needed nobody", () => {312 const text = textOf(page);313 const markup = markupOf(page);314315 expect(markup).toContain('href="/people/lin-h"');316 expect(text).toContain("format-date");317 expect(text).toContain("parse-iso");238 expect(text).toContain("cccccc");318 expect(text).toContain("ccccccc");319 });320321 it("offers each decision only the choices its subject allows", () => {242 expect(choicesOf(page)).toStrictEqual([322 expect(choicesOf(markupOf(page))).toStrictEqual([323 "dec-000002: adopt revert",324 "dec-000003: accept decline",325 "dec-000001: accept decline",326 ]);327 });328249 it("shows a NotDecider failure as the refusal, not an empty page", () => {329 it("says under every choice what it does", () => {330 for (const { body } of rowsOf(markupOf(page))) {331 const choices = [...body.matchAll(/data-choice="(?<c>[^"]+)"/gu)].map(332 (match) => match.groups?.c333 );334335 const lines = [...body.matchAll(/data-consequence="(?<c>[^"]+)"/gu)].map(336 (match) => match.groups?.c337 );338339 expect(lines).toStrictEqual(choices);340 }341342 expect(textOf(page)).toContain(343 "Opens the ask: its file and check land on main, with you as Decided-by."344 );345 expect(textOf(page)).toContain("The proposal closes; nothing lands.");346 });347348 it("keeps a decision taken in its row, reading what it did, and offers its choices no more", () => {349 const taken: Decision = {350 ...proposal,351 decided: { at: now, by: okonkwo, choice: "accept" },352 };353354 const markup = markupOf(355 viewOf(356 TodayRead.cases.Read.make({357 today: {358 ...today,359 budget: { ...today.budget, used: 3 },360 decisions: [vouch, stray],361 },362 }),363 { decided: AsyncResult.success({ decision: taken }) }364 )365 );366367 const rows = rowsOf(markup);368 const last = rows.at(-1);369370 expect(rows.map(({ id }) => id)).toStrictEqual([371 "dec-000002",372 "dec-000003",373 "dec-000001",374 ]);375 expect(textIn(last?.body ?? "")).toContain("Accepted");376 expect(textIn(last?.body ?? "")).toContain(377 "Opens the ask: its file and check land on main, with you as Decided-by."378 );379 expect(last?.body).not.toContain("data-choice=");380 expect(textIn(markup)).toContain("Decisions: 3 taken, 2 left today.");381 });382383 it("shows a NotDecider failure as the refusal, says what Today is, and lists no decision", () => {384 const refused = new NotDecider({});385386 const markup = markupOf(253 <TodayView254 now={now}255 onDecide={() => {}}256 result={AsyncResult.failure(Cause.fail(refused))}257 />387 viewOf(TodayRead.cases.Refused.make({ refusal: refused }))388 );389390 expect(markup).toContain(markupOf(<RefusalView refusals={[refused]} />));391 expect(markup).not.toContain("data-decision");392 expect(textIn(markup)).toContain(`${Brand.cli} today`);393 });394395 it("signed out, says what Today is in one sentence, links to sign in, and gives the command", () => {396 const markup = markupOf(viewOf(TodayRead.cases.SignedOut.make({})));397 const text = textIn(markup);398399 expect(text).toContain("Today is a decider's page");400 expect(markup).toMatch(401 /<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in<\/a>/u402 );403 expect(text).toContain(`${Brand.cli} today`);404 expect(markup).not.toContain("data-decision");405 });406407 it("shows a DecisionClosed refusal the decider's choice came back with", () => {408 const closed = new DecisionClosed({ decision: stray.id });409410 const markup = markupOf(411 viewOf(TodayRead.cases.Read.make({ today }), {412 decided: AsyncResult.failure(Cause.fail(closed)),413 })414 );415416 expect(markup).toContain(markupOf(<RefusalView refusals={[closed]} />));417 });418});419420describe(orderDecisions, () => {421 it("puts the decisions expiring soon first, then the rest by expiry", () => {
88 unmodified lines
510 "Let SENTRY_DSN be sent to more hosts through the platform's proxy",511 ]);512 });513});514515describe(consequenceOf, () => {516 it("says what each choice on each subject does, as the platform does it", () => {517 expect(518 subjects.map((subject) =>519 allowedChoices(subject).map((choice: Choice) =>520 consequenceOf(subject, choice)521 )522 )523 ).toStrictEqual([524 [525 "main stays at bbbbbbb, kept as a landing with you as Decided-by.",526 "A landing puts back the tree at aaaaaaa, with you as Decided-by.",527 ],528 [529 "Lands lin-h in the vouch file, with you as Decided-by.",530 "Nothing lands; lin-h stays unvouched.",531 ],532 [533 "Opens the ask: its file and check land on main, with you as Decided-by.",534 "The proposal closes; nothing lands.",535 ],536 [537 "Lands the answer as it is, with you as Finished-by.",538 "Nothing lands; the answer keeps waiting for a finish.",539 ],540 [541 "The answer goes on through the gate with the ratchet at 3, with you as Decided-by.",542 "The answer is refused; the ratchet stays at 2.",543 ],544 [545 "The answer goes on through the gate with .skip( allowed there, with you as Decided-by.",546 "The answer is refused at that line.",547 ],548 [549 "The answer that changes it goes on through the gate, with you as Decided-by.",550 "The answer that changes it is refused; the posture stays open.",551 ],552 [553 "Your choice is kept on the decision; the platform takes no other step on it.",554 "Your choice is kept on the decision; the platform takes no other step on it.",555 ],556 [557 "Your choice is kept on the decision; the platform takes no other step on it.",558 "Your choice is kept on the decision; the platform takes no other step on it.",559 ],560 ]);561 });562563 it("names a stray push to another ref as moving nothing", () => {564 const elsewhere = DecisionSubject.cases.StrayPush.make({565 after: sha("b"),566 before: sha("a"),567 ref: RefNameText.make("refs/heads/release"),568 });569570 expect(consequenceOf(elsewhere, "revert")).toBe(571 "Only main is reverted: release stays where it is."572 );573 });574});575576const vellum = ProjectName.make("vellum");577578/** A `Client` of a fresh dev world with its fixtures, signed in as `handle` (or as nobody). */579const fixturesClient = (handle?: string) =>580 Layer.unwrap(581 Effect.gen(function* () {582 const { dispose, handler } = devServer({ fixtures: "on" });583584 yield* Effect.addFinalizer(() => Effect.promise(dispose));585586 return Layer.effect(Client)(RpcClient.make(Contracts)).pipe(587 Layer.provide(588 RpcClient.layerProtocolHttp({589 transformClient: HttpClient.mapRequest((request) =>590 handle === undefined591 ? request592 : HttpClientRequest.bearerToken(593 request,594 devToken(Handle.make(handle))595 )596 ),597 url: "http://localhost/rpc",598 })599 ),600 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),601 Layer.provide(602 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>603 handler(new Request(input, init))604 )605 )606 );607 })608 );609610/** The page the route renders from what `readToday` sent, as the browser decodes it. */611const pageFrom = (encoded: typeof TodayPageData.Encoded) => {612 const data = Schema.decodeSync(TodayPageData)(encoded);613614 return markupOf(615 <TodayView now={data.now} onDecide={() => {}} read={data.read} />616 );617};618619describe("Today, read on the server with the reader's session", () => {620 it.live(621 "renders a decider's Today from the fixtures: the budget sentence, the sections and what waits",622 () =>623 Effect.gen(function* () {624 const markup = pageFrom(yield* readToday({ project: vellum }));625 const text = textIn(markup);626627 expect(text).toContain(628 "Decisions: 2 taken, 3 left today. Finishes are counted apart: none taken."629 );630 expect(sectionsOf(markup).slice(0, 3)).toStrictEqual([631 "Due today",632 "Within your budget",633 "Waits for tomorrow",634 ]);635 expect(text).toContain("3 more wait for tomorrow");636 expect(rowsOf(markup)).toHaveLength(3);637638 for (const { body } of rowsOf(markup)) {639 expect(body).toContain("data-consequence=");640 }641 }).pipe(Effect.provide(fixturesClient("ines-v")), Effect.scoped),642 60_000643 );644645 it.live(646 "signed out, sends what Today is, the way to sign in and the command",647 () =>648 Effect.gen(function* () {649 const markup = pageFrom(yield* readToday({}));650651 expect(textIn(markup)).toContain("Today is a decider's page");652 expect(textIn(markup)).toContain(`${Brand.cli} today`);653 expect(markup).not.toContain("data-decision");654 }).pipe(Effect.provide(fixturesClient()), Effect.scoped),655 60_000656 );657658 it("is kept by no cache: its response is private and never stored", () => {659 expect(Route.options.headers).toBe(todayHeaders);660 expect(todayHeaders()).toStrictEqual({661 "Cache-Control": "private, no-store",662 });663 });664});