Fix the proposal page's decision link, the propose form's stale move and its sign-in return
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- The proposal page's Today now reads again on the project's keys as well as Today's, so a draft that settles (ProposalDrafted) shows its new decision's link without a reload; before, only keys.today() refreshed it. - The propose route moves only on a settled success (`proposalMade` in client/propose.ts): AsyncResult.value kept an earlier send's proposal while a later send waited or after it was refused, so the form could jump to an old proposal and hide the refusal. - Signed out, the sign-in link comes back to the form with its ?about&line&at, so a why page's prefill survives signing in. One address builder, proposeFormPath(project, about), replaces the two copies. - The decision card treats a label with a slash or a dot as a file, so a check at the repo's root renders as code too; isFileFact is module-private. - Tests: projectTodayAtom re-reads on ProposalDrafted's keys, readProposal's read and its not-founds, topFolders, proposalMade (waiting and refused), the sign-in return path, a root-level file in the card, and DRAFT_ATTEMPTS held equal to @repo/project's DRAFT_ROUNDS (a dev dependency of the web). Each fix's test failed first by assertion.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+381 added−26 removed
- tests:+319 added−4 removed
- other:+62 added−22 removed
Provenance
- Commit
91bdc90- Tree
3853c1f- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
2d0e927
10 files changed+381 added−26 removed
modified:apps/web/src/client/proposal.ts+14 added-4 removed
5 unmodified lines6789101011121314152 unmodified lines1819202121222324256 unmodified lines323334353636373839404138424344454647484950515219 unmodified lines5 unmodified lines * proposer's or a decider's "Draft again" over `draftAsk`. * * The decider's Today in one project lives here too, as the proposal page * reads it: it holds the open decision on the proposal (within the day's * budget), and it answers only a decider (`NotDecider` otherwise). Each read * budget), and it answers only a decider (`NotDecider` otherwise); it reads * again when the project's keys change, as a settled draft changes them. Each read * renders as waiting on the server, so the Worker reads none of them for a * page that draws them in the browser. */import type { DraftAsk } from "@repo/protocol/contracts";2 unmodified linesimport { Atom, Reactivity } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";import { todayAtom } from "./today.ts";
/** One proposal and the files it holds: `proposalAtom(project)(proposal)`. */export const proposalAtom = Atom.family((project: ProjectName) => Atom.family((proposal: ProposalId) =>6 unmodified lines ) ));
/** The reader's Today in `project`, when they decide there. *//** * The reader's Today in `project`, when they decide there. A draft that * settles puts its decision up, so the project's keys (which a * `ProposalDrafted` changes, through `keys.proposal`) read it again too. */export const projectTodayAtom = Atom.family((project: ProjectName) => Atom.withServerValueInitial(todayAtom(project)) Atom.withServerValueInitial( ContractsClient.query( "today", { project }, { reactivityKeys: [...keys.today(), ...keys.project(project)] } ) ));
/** * Draft a proposal's ask again: `{ project, proposal, note? }`, answered19 unmodified linesmodified:apps/web/src/client/propose.ts+14 added-2 removed
6 unmodified lines7891011111213131415161727 unmodified lines45464748495051525354555657585960616263648 unmodified lines6 unmodified lines * key reads again. */import type { ProposeAsk } from "@repo/protocol/contracts";import { RepoPath } from "@repo/protocol/ids";import type { ProjectName } from "@repo/protocol/ids";import type { ProjectName, ProposalId } from "@repo/protocol/ids";import { Array, Effect, Option, Order, Schema } from "effect";import { Atom, Reactivity } from "effect/reactivity";import { AsyncResult, Atom, Reactivity } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
27 unmodified lines ) ));
/** * The proposal the last send made, once it answered. While a later send is * on its way, or after it was refused, the atom still holds an earlier * send's proposal, which names none here: the form never moves to it. */export const proposalMade = ( result: AsyncResult.AsyncResult<typeof ProposeAsk.successSchema.Type, unknown>): Option.Option<ProposalId> => AsyncResult.isSuccess(result) && !result.waiting ? Option.some(result.value.proposal.id) : Option.none();
/** Propose an ask: `proposeAsk`'s payload, answered with the proposal. */export const proposeAtom = ContractsClient.runtime.fn< typeof ProposeAsk.payloadSchema.Type>()(8 unmodified linesmodified:apps/web/src/features/decision/decision-card.tsx+3 added-2 removed
121 unmodified lines122 const isDraftingNow = DraftState.isAnyOf(["Drafting"]);123 124 /**125 * Whether an evidence line holds a file: its label is a path (one word with126- * a slash, as the ask file's), where every other label is words.126+ * a slash or a dot, as the ask file under the config folder, or a check127+ * at the root, `offset.test.ts`), where every other label is words.128 */128-export const isFileFact = ({ label }: Fact) => /^\S+\/\S+$/u.test(label);129+const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);130 131 /** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */132 const filesOf = (decision: Decision): readonly Fact[] =>133 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];291 unmodified linesmodified:apps/web/src/features/proposal/proposal-view.tsx+2 added-1 removed
28 unmodified lines29 import { DraftedCode } from "./client-file.tsx";30 31 /**32 * How many attempts a draft round makes before it fails: the platform's33- * `DRAFT_ROUNDS` (`@repo/project/draft-runs`), which the web cannot import.33+ * `DRAFT_ROUNDS` (`@repo/project/draft-runs`), which the web's production34+ * code does not import; `test/proposal.test.tsx` holds the two equal.35 */36 export const DRAFT_ATTEMPTS = 3;37 38 /** The longest note `draftAsk` takes. */250 unmodified linesmodified:apps/web/src/features/propose/propose-link.tsx+1 added-4 removed
9 unmodified lines101112131415151617181617181916 unmodified lines9 unmodified linesimport { AsyncResult } from "effect/reactivity";import { MessageSquarePlus } from "lucide-react";
import { whoAtom } from "../auth/who.ts";import { proposeFormPath } from "./propose-view.tsx";
/** The form's address for `project`. */export const proposeFormPath = (project: ProjectName) => `/${project}/proposals/new`;
export const ProposeLink = ({ project }: { readonly project: ProjectName }) => ( <a className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current" data-propose=""16 unmodified linesmodified:apps/web/src/features/propose/propose-view.tsx+22 added-5 removed
58 unmodified lines59 /** How a want about one line starts: `In \`src/format.ts\` line 12 at 4c2e6a8: `. */60 export const wantAbout = ({ at, line, path }: About) =>61 `In \`${path}\` line ${line} at ${at.slice(0, 7)}: `;62 63-/** The form's own address, for sign-in to come back to. */64-const proposePath = (project: ProjectName) => `/${project}/proposals/new`;63+/**64+ * The form's address for `project`, at the line a why page names when it65+ * names one: where the project page links, and where sign-in comes back to.66+ */67+export const proposeFormPath = (68+ project: ProjectName,69+ about: Option.Option<About> = Option.none()70+) =>71+ Option.match(about, {72+ onNone: () => `/${project}/proposals/new`,73+ onSome: ({ at, line, path }) =>74+ `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,75+ });76 77 const LABEL = "text-muted-foreground text-xs font-medium";78 68-const SignInFirst = ({ project }: { readonly project: ProjectName }) => (79+const SignInFirst = ({80+ about,81+ project,82+}: {83+ readonly about: Option.Option<About>;84+ readonly project: ProjectName;85+}) => (86 <section87 aria-label="Sign in to propose"88 className="border-rule flex flex-col gap-3 border-t pt-4"89 >2 unmodified lines92 <span>93 Proposing an ask is for signed-in members.{" "}94 <a95 className="decoration-rule font-medium underline hover:decoration-current"79- href={`/auth/signin?${new URLSearchParams({ return: proposePath(project) }).toString()}`}96+ href={`/auth/signin?${new URLSearchParams({ return: proposeFormPath(project, about) }).toString()}`}97 >98 Sign in99 </a>{" "}100 to propose one, or propose from your clone:33 unmodified lines134 const [territory, setTerritory] = useState("");135 const [draft, setDraft] = useState(true);136 137 if (!signedIn) {121- return <SignInFirst project={project} />;138+ return <SignInFirst about={about} project={project} />;139 }140 141 const chosen = modules.find((module) => module === territory);142 const written = want.trim().length > 0;90 unmodified linesmodified:apps/web/src/routes/$project/proposals/new.tsx+6 added-4 removed
3 unmodified lines4 import { Option, Schema } from "effect";5 import { AsyncResult } from "effect/reactivity";6 import { useEffect, useState } from "react";7 8-import { modulesAtom, proposeAtom } from "../../../client/propose.ts";8+import {9+ modulesAtom,10+ proposalMade,11+ proposeAtom,12+} from "../../../client/propose.ts";13 import { whoAtom } from "../../../features/auth/who.ts";14 import { ProjectNav } from "../../../features/project/project-nav.tsx";15 import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";16 import { ProposeView } from "../../../features/propose/propose-view.tsx";55 unmodified lines72 // Set once this form sends: a proposal the atom still holds from an73 // earlier visit never moves the page.74 const [sent, setSent] = useState(false);75 72- const made = sent73- ? Option.getOrUndefined(AsyncResult.value(proposed))?.proposal.id74- : undefined;76+ const made = sent ? Option.getOrUndefined(proposalMade(proposed)) : undefined;77 78 useEffect(() => {79 if (made !== undefined) {80 void navigate({60 unmodified linesmodified:apps/web/test/decision.test.tsx+21 added
356 unmodified lines357 expect(acceptOf(markup)).not.toContain('disabled=""');358 expect(markup).not.toContain("Drafting…");359 });360 361+ it("shows a check at the repo's root as code too", () => {362+ const markup = markupOf(363+ <DecisionCard364+ decision={{365+ ...opening,366+ evidence: [367+ ...opening.evidence,368+ { label: "offset.test.ts", value: "test('keeps +02:00');\n" },369+ ],370+ }}371+ draft={ready}372+ now={now}373+ onDecide={() => {}}374+ />375+ );376+377+ expect(markup).toMatch(/<h4[^>]*>offset\.test\.ts<\/h4>/u);378+ expect(markup).not.toMatch(/<dt[^>]*>offset\.test\.ts<\/dt>/u);379+ expect(markup).toMatch(/<dt[^>]*>want<\/dt>/u);380+ });381+382 it("links the proposal's page", () => {383 expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');384 });385 });modified:apps/web/test/proposal.test.tsx+204 added-4 removed
6 unmodified lines7 * drafting, and the way to its decision when one is open.8 */9 import { describe, expect, it } from "@effect/vitest";10 import { Brand } from "@repo/brand";11+import { DRAFT_ROUNDS } from "@repo/project/draft-runs";11-import { ShowProposal } from "@repo/protocol/contracts";12+import { Client, Contracts, ShowProposal } from "@repo/protocol/contracts";13+import { ProjectEvent } from "@repo/protocol/domain/event";14 import { DraftState } from "@repo/protocol/domain/proposal";13-import { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";14-import { DateTime, Option, Schema } from "effect";15+import { DecisionId, Handle, LaneName, ProjectName } from "@repo/protocol/ids";16+import { UnknownProject, UnknownProposal } from "@repo/protocol/refusal";17+import { asTester, unanswered } from "@repo/protocol/testing";18+import { isNotFound } from "@tanstack/react-router";19+import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";20+import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";21+import { RpcTest } from "effect/rpc";22 23+import { projectTodayAtom } from "../src/client/proposal.ts";24+import { keysOf } from "../src/client/watch.ts";25+import {26+ DRAFT_ATTEMPTS,27+ ProposalView,16-import { ProposalView } from "../src/features/proposal/proposal-view.tsx";28+} from "../src/features/proposal/proposal-view.tsx";29+import { readProposal } from "../src/routes/$project/proposals/$proposal.tsx";30+import { ContractsClient, webContracts } from "../src/surfaces.ts";31 import { markupOf, plainText } from "./ask-fixtures.ts";32 33 const datekit = ProjectName.make("datekit");34 131 unmodified lines166 167 expect(markup).not.toMatch(DRAFT_AGAIN);168 });169 170+ it("counts attempts out of the platform's own number of draft attempts", () => {171+ expect(DRAFT_ATTEMPTS).toBe(DRAFT_ROUNDS);172+ });173+174 it("once accepted, offers no button", () => {175 const accepted: Shown = {176 ...ready,177 proposal: { ...ready.proposal, state: "accepted" },4 unmodified lines182 expect(plainText(markup)).toContain("accepted");183 expect(markup).not.toContain("<button");184 });185 });186+187+/** A platform that knows datekit's prop-000007 only, counting what it is asked. */188+const platformHandlers = (189+ asked: Ref.Ref<{ proposal: number; today: number }>190+) =>191+ Layer.mergeAll(192+ unanswered,193+ Contracts.toLayerHandler("showProposal", ({ project, proposal }) =>194+ Effect.gen(function* () {195+ yield* Ref.update(asked, (seen) => ({196+ ...seen,197+ proposal: seen.proposal + 1,198+ }));199+200+ if (project !== datekit) {201+ return yield* new UnknownProject({ project });202+ }203+204+ if (proposal !== ready.proposal.id) {205+ return yield* new UnknownProposal({ proposal });206+ }207+208+ return ready;209+ })210+ ),211+ Contracts.toLayerHandler("today", () =>212+ Ref.update(asked, (seen) => ({ ...seen, today: seen.today + 1 })).pipe(213+ Effect.as({214+ budget: { finishes: 0, total: 5, used: 0 },215+ decider: Handle.make("okonkwo"),216+ decisions: [],217+ expiringSoon: [],218+ newcomers: [],219+ overflow: 0,220+ unattended: [],221+ })222+ )223+ ),224+ asTester225+ );226+227+const counted = () => Ref.make({ proposal: 0, today: 0 });228+229+describe(readProposal, () => {230+ it.effect("reads the proposal and its files, encoded for the page", () =>231+ Effect.gen(function* () {232+ const asked = yield* counted();233+234+ const read = yield* readProposal("datekit", "prop-000007").pipe(235+ Effect.provide(236+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(237+ Layer.provide(platformHandlers(asked))238+ )239+ )240+ );241+242+ expect(decodeShown(read).files.map(({ path }) => path)).toStrictEqual([243+ askFile,244+ testFile,245+ ]);246+ })247+ );248+249+ it.effect(250+ "is a not-found for a proposal or a project the platform does not know",251+ () =>252+ Effect.gen(function* () {253+ const asked = yield* counted();254+255+ const platform = Layer.effect(256+ Client,257+ RpcTest.makeClient(Contracts)258+ ).pipe(Layer.provide(platformHandlers(asked)));259+260+ const noProposal = yield* Effect.flip(261+ readProposal("datekit", "prop-000099").pipe(Effect.provide(platform))262+ );263+264+ const noProject = yield* Effect.flip(265+ readProposal("burrow", "prop-000007").pipe(Effect.provide(platform))266+ );267+268+ expect(isNotFound(noProposal)).toBeTruthy();269+ expect(isNotFound(noProject)).toBeTruthy();270+ expect((yield* Ref.get(asked)).proposal).toBe(2);271+ })272+ );273+274+ it.effect(275+ "is a not-found, asking nothing, for an address that names no proposal",276+ () =>277+ Effect.gen(function* () {278+ const asked = yield* counted();279+280+ const refused = yield* Effect.flip(281+ readProposal("datekit", "not a proposal").pipe(282+ Effect.provide(283+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(284+ Layer.provide(platformHandlers(asked))285+ )286+ )287+ )288+ );289+290+ expect(isNotFound(refused)).toBeTruthy();291+ expect((yield* Ref.get(asked)).proposal).toBe(0);292+ })293+ );294+});295+296+/** Lets the atoms' fibers run until `done` holds, or long enough that it would have. */297+const runUntil = (done: Effect.Effect<boolean>) =>298+ Effect.yieldNow.pipe(299+ Effect.andThen(done),300+ Effect.repeat({ times: 200, until: (held) => held })301+ );302+303+describe("the proposal page's Today", () => {304+ it.effect(305+ "reads again when the proposal's draft settles, so its new decision is linked",306+ () =>307+ Effect.gen(function* () {308+ const asked = yield* counted();309+310+ // One browser tab whose `ContractsClient` reaches the stub platform in process.311+ const registry = yield* Effect.acquireRelease(312+ Effect.sync(() =>313+ AtomRegistry.make({314+ initialValues: [315+ Atom.initialValue(316+ ContractsClient.runtime.layer,317+ Layer.effect(318+ ContractsClient,319+ RpcTest.makeClient(webContracts, { flatten: true })320+ ).pipe(321+ Layer.provide(platformHandlers(asked)),322+ Layer.provideMerge(Reactivity.layer)323+ )324+ ),325+ ],326+ })327+ ),328+ (made) =>329+ Effect.sync(() => {330+ made.dispose();331+ })332+ );333+334+ const today = projectTodayAtom(datekit);335+336+ registry.mount(today);337+ yield* AtomRegistry.getResult(registry, today, {338+ suspendOnWaiting: true,339+ });340+341+ // What the watch does on `ProposalDrafted` (`keysOf` in `watch.ts`).342+ yield* AtomRegistry.getResult(343+ registry,344+ ContractsClient.runtime.atom(345+ Reactivity.invalidate(346+ keysOf(347+ datekit,348+ ProjectEvent.cases.ProposalDrafted.make({349+ at: DateTime.makeUnsafe("2026-10-07T09:05:00Z"),350+ proposal: ready.proposal.id,351+ ready: true,352+ seq: 4,353+ })354+ )355+ )356+ ),357+ { suspendOnWaiting: true }358+ );359+360+ expect(361+ yield* runUntil(362+ Ref.get(asked).pipe(Effect.map(({ today: seen }) => seen > 1))363+ )364+ ).toBeTruthy();365+ })366+ );367+});modified:apps/web/test/propose.test.tsx+94 added
5 unmodified lines6 * the want. Signed out, the page offers sign-in and no form. What the form7 * sends is the `proposeAsk` contract's own payload.8 */9 import { describe, expect, it } from "@effect/vitest";10+import { Brand } from "@repo/brand";11 import { ProposeAsk } from "@repo/protocol/contracts";12 import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";13+import { CapReached } from "@repo/protocol/refusal";14 import { Option, Schema } from "effect";15+import { AsyncResult } from "effect/reactivity";16 17+import { proposalMade, topFolders } from "../src/client/propose.ts";18 import {19 ProposeView,20 proposalPayload,21 } from "../src/features/propose/propose-view.tsx";96 unmodified lines118 });119 expect(Object.hasOwn(payload, "draft")).toBeFalsy();120 });121 });122+123+describe(topFolders, () => {124+ it("offers each top folder once, sorted, and no dot folder or root file", () => {125+ expect(126+ topFolders(127+ [128+ "src/format.ts",129+ "README.md",130+ `${Brand.configDir}/asks/x.ask.ts`,131+ "test/format.test.ts",132+ "src/parse/iso.ts",133+ ".github/workflows/ci.yml",134+ "docs/guide.md",135+ ].map((path) => RepoPath.make(path))136+ )137+ ).toStrictEqual(["docs", "src", "test"]);138+ });139+});140+141+/** `proposeAsk`'s answer: the proposal `id`, made. */142+const made = (id: string) =>143+ Schema.decodeUnknownSync(ProposeAsk.successSchema)({144+ proposal: {145+ expiresAt: "2026-10-21T09:00:00.000Z",146+ files: [],147+ id,148+ openedAt: "2026-10-07T09:00:00.000Z",149+ project: "datekit",150+ proposer: "lin-h",151+ state: "open",152+ want: "formatISO keeps the offset.",153+ },154+ });155+156+describe(proposalMade, () => {157+ const earlier = AsyncResult.success(made("prop-000004"));158+159+ it("names the proposal a send made, once it answered", () => {160+ expect(161+ proposalMade(AsyncResult.success(made("prop-000005")))162+ ).toStrictEqual(Option.some("prop-000005"));163+ });164+165+ it("names none while a later send is on its way, or after it was refused", () => {166+ expect(proposalMade(AsyncResult.waiting(earlier))).toStrictEqual(167+ Option.none()168+ );169+ expect(170+ proposalMade(171+ AsyncResult.fail(new CapReached({ cap: 3 }), {172+ previousSuccess: Option.some(earlier),173+ })174+ )175+ ).toStrictEqual(Option.none());176+ });177+});178+179+describe("the sign-in link", () => {180+ it("comes back to the form, at the line a why page named", () => {181+ const markup = markupOf(182+ <ProposeView183+ about={Option.some({184+ at,185+ line: 12,186+ path: RepoPath.make("src/format.ts"),187+ })}188+ modules={modules}189+ project={datekit}190+ signedIn={false}191+ />192+ );193+194+ const href = /href="(?<href>\/auth\/signin[^"]*)"/u195+ .exec(markup)196+ ?.groups?.href?.replaceAll("&", "&");197+198+ const back = new URL(href ?? "/", "https://web.test").searchParams.get(199+ "return"200+ );201+202+ const there = new URL(back ?? "/", "https://web.test");203+204+ expect(there.pathname).toBe("/datekit/proposals/new");205+ expect(Object.fromEntries(there.searchParams)).toStrictEqual({206+ about: "src/format.ts",207+ at,208+ line: "12",209+ });210+ });211+});