Skip to content
Myr

proposal.test.tsx

This file

Path

apps/web/test/proposal.test.tsx

465 lines · 13.6 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { DRAFT_ROUNDS } from "@repo/project/draft-runs";4import { Client, Contracts, ShowProposal } from "@repo/protocol/contracts";5import { ProjectEvent } from "@repo/protocol/domain/event";6import { DraftState } from "@repo/protocol/domain/proposal";7import { DecisionId, Handle, LaneName, ProjectName } from "@repo/protocol/ids";8import { Unauthenticated } from "@repo/protocol/principal";9import { UnknownProject, UnknownProposal } from "@repo/protocol/refusal";10import { asTester, unanswered } from "@repo/protocol/testing";11import { isNotFound } from "@tanstack/react-router";12import { Cause, DateTime, Effect, Layer, Option, Ref, Schema } from "effect";13import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";14import { RpcTest } from "effect/rpc";1516import { projectTodayAtom } from "../src/client/proposal.ts";17import { keysOf } from "../src/client/watch.ts";18import { ProposalFailure } from "../src/features/proposal/failure.tsx";19import {20  DRAFT_ATTEMPTS,21  ProposalView,22} from "../src/features/proposal/proposal-view.tsx";23import { readProposal } from "../src/routes/$owner/$project/proposals/$proposal.tsx";24import { ContractsClient, webContracts } from "../src/surfaces.ts";25import { markupOf, plainText } from "./ask-fixtures.ts";2627const datekit = ProjectName.make("oscabriel/datekit");2829const decodeShown = Schema.decodeUnknownSync(ShowProposal.successSchema);3031const model = "@cf/moonshotai/kimi-k2.7-code";3233const askFile = `${Brand.configDir}/asks/format-keeps-offset.ask.ts`;3435const testFile = "src/format.offset.test.ts";3637type Shown = typeof ShowProposal.successSchema.Type;3839const shownWith = (files: readonly string[]): Shown =>40  decodeShown({41    files: files.map((path) => ({ content: `// ${path}\n`, path })),42    proposal: {43      expiresAt: "2026-10-21T09:00:00.000Z",44      files,45      id: "prop-000007",46      openedAt: "2026-10-07T09:00:00.000Z",47      project: "datekit",48      proposer: "lin-h",49      state: "open",50      want: "formatISO keeps the offset it was given.",51    },52  });5354const withDraft = (base: Shown, draft: DraftState): Shown => ({55  ...base,56  proposal: { ...base.proposal, draft },57});5859const drafting = withDraft(60  shownWith([]),61  DraftState.cases.Drafting.make({62    round: 1,63    startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),64  })65);6667const ready = withDraft(68  shownWith([askFile, testFile]),69  DraftState.cases.Ready.make({70    attempts: 2,71    model,72    red: {73      lane: LaneName.make("unit"),74      signature: "expected '+02:00', got 'Z'",75    },76    round: 1,77  })78);7980const failed = withDraft(81  shownWith([]),82  DraftState.cases.Failed.make({83    attempts: 3,84    model,85    refusal: "NotRedFirst",86    round: 2,87  })88);8990const decision = DecisionId.make("dec-000003");9192const view = (93  { files, proposal }: Shown,94  linked: Option.Option<DecisionId> = Option.none()95) =>96  markupOf(97    <ProposalView98      decision={linked}99      files={files}100      mayRedraft101      project={datekit}102      proposal={proposal}103    />104  );105106const DRAFT_AGAIN = /<button[^>]*>[^<]*Draft again/u;107108describe(ProposalView, () => {109  it("shows the want and the proposer", () => {110    const text = plainText(view(drafting));111112    expect(text).toContain("formatISO keeps the offset it was given.");113    expect(text).toContain("lin-h");114  });115116  it("titles the page with the want, never the proposal's id", () => {117    expect(view(drafting)).toMatch(118      /<h1[^>]*>formatISO keeps the offset it was given\.<\/h1>/u119    );120  });121122  it("while drafting, says so in the checking role, and offers no Draft again", () => {123    const markup = view(drafting);124125    expect(markup).toMatch(/data-tone="checking"[^>]*>[\s\S]*?Drafting/u);126    expect(markup).not.toMatch(DRAFT_AGAIN);127  });128129  it("once ready, says it waits for a maintainer, in the waiting role", () => {130    const markup = view(ready);131132    expect(markup).toMatch(/data-tone="waiting"/u);133    expect(plainText(markup)).toContain("Ready , waits for a maintainer");134  });135136  it("reads the draft as a guide, in its order: the ask file, the check, red first", () => {137    const text = plainText(view(ready));138139    expect(text.indexOf("The ask file")).toBeLessThan(140      text.indexOf("The check")141    );142    expect(text.indexOf("The check")).toBeLessThan(text.indexOf("Red first"));143    expect(view(ready)).not.toMatch(/<h2[^>]*>\s*0[1-9]/u);144  });145146  it("while drafting with a note, shows the note the round was asked with", () => {147    const noted = withDraft(148      shownWith([]),149      DraftState.cases.Drafting.make({150        note: "only the parser",151        round: 2,152        startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),153      })154    );155156    expect(plainText(view(noted))).toContain("Note: only the parser");157    expect(plainText(view(drafting))).not.toContain("Note:");158  });159160  it("once ready, shows both files, the red-first run, who drafted it and its decision", () => {161    const markup = view(ready, Option.some(decision));162    const text = plainText(markup);163164    expect(text).toContain(askFile);165    expect(text).toContain(testFile);166    expect(text).toContain(167      "fails twice the same way in lane unit: expected '+02:00', got 'Z'"168    );169    expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);170    expect(markup).toContain('href="/oscabriel/datekit/decisions/dec-000003"');171  });172173  it("once ready, draws nothing in the checking role", () => {174    expect(view(ready)).not.toContain('data-tone="checking"');175    expect(view(ready)).not.toContain('data-slot="spinner"');176  });177178  it("once failed with a refusal, draws it as git prints it, and offers Draft again", () => {179    const markup = view(failed);180181    expect(plainText(markup)).toContain("NotRedFirst");182    expect(markup).toContain('data-refusal="NotRedFirst"');183    expect(markup).toMatch(DRAFT_AGAIN);184  });185186  it("once failed with a refusal it cannot draw whole, says so in ink, never in the refused role", () => {187    const weak = withDraft(188      shownWith([]),189      DraftState.cases.Failed.make({190        attempts: 3,191        model,192        refusal: "WeakCheck",193        round: 1,194      })195    );196197    const markup = view(weak);198199    expect(plainText(markup)).toContain("The draft failed: WeakCheck");200    expect(markup).not.toContain("text-refused");201    expect(markup).not.toContain("data-refusal=");202  });203204  it("failed after a ready round, still shows that round's files as a draft a maintainer can accept", () => {205    const kept = withDraft(206      ready,207      DraftState.cases.Failed.make({208        attempts: 3,209        model,210        refusal: "NotRedFirst",211        round: 2,212      })213    );214215    const text = plainText(view(kept));216217    expect(text).toContain(askFile);218    expect(text).toContain(testFile);219    expect(text).toContain("An earlier round's ready draft");220    expect(plainText(view(ready))).not.toContain("An earlier round");221  });222223  it("offers Draft again only to the proposer or a maintainer", () => {224    const markup = markupOf(225      <ProposalView226        decision={Option.none()}227        files={[]}228        mayRedraft={false}229        project={datekit}230        proposal={failed.proposal}231      />232    );233234    expect(markup).not.toMatch(DRAFT_AGAIN);235  });236237  it("counts attempts out of the platform's own number of draft attempts", () => {238    expect(DRAFT_ATTEMPTS).toBe(DRAFT_ROUNDS);239  });240241  it("once accepted, offers no button", () => {242    const accepted: Shown = {243      ...ready,244      proposal: { ...ready.proposal, state: "accepted" },245    };246247    const markup = view(accepted);248249    expect(plainText(markup)).toContain("accepted");250    expect(markup).not.toContain("<button");251  });252});253254describe("a failed call on the proposal page", () => {255  const here = "/oscabriel/datekit/proposals/prop-000007";256257  it("with no session, asks to sign in and come back to the page", () => {258    const markup = markupOf(259      <ProposalFailure260        cause={Cause.fail(new Unauthenticated({}))}261        doing="draft it again"262        here={here}263      />264    );265266    expect(markup).toContain(267      'href="/auth/signin?return=%2Foscabriel%2Fdatekit%2Fproposals%2Fprop-000007"'268    );269    expect(plainText(markup)).toContain("Sign in");270    expect(plainText(markup)).not.toContain("Today is a maintainer's page");271  });272273  it("refused, shows the refusal", () => {274    const markup = markupOf(275      <ProposalFailure276        cause={Cause.fail(new UnknownProposal({ proposal: ready.proposal.id }))}277        doing="draft it again"278        here={here}279      />280    );281282    expect(plainText(markup)).toContain("UnknownProposal");283    expect(markup).not.toContain("/auth/signin");284  });285});286287const platformHandlers = (288  asked: Ref.Ref<{ proposal: number; today: number }>289) =>290  Layer.mergeAll(291    unanswered,292    Contracts.toLayerHandler("showProposal", ({ project, proposal }) =>293      Effect.gen(function* () {294        yield* Ref.update(asked, (seen) => ({295          ...seen,296          proposal: seen.proposal + 1,297        }));298299        if (project !== datekit) {300          return yield* new UnknownProject({ project });301        }302303        if (proposal !== ready.proposal.id) {304          return yield* new UnknownProposal({ proposal });305        }306307        return ready;308      })309    ),310    Contracts.toLayerHandler("today", () =>311      Ref.update(asked, (seen) => ({ ...seen, today: seen.today + 1 })).pipe(312        Effect.as({313          budget: { finishes: 0, total: 5, used: 0 },314          decider: Handle.make("okonkwo"),315          decisions: [],316          expiringSoon: [],317          newcomers: [],318          overflow: 0,319          unattended: [],320        })321      )322    ),323    asTester324  );325326const counted = () => Ref.make({ proposal: 0, today: 0 });327328describe(readProposal, () => {329  it.effect("reads the proposal and its files, encoded for the page", () =>330    Effect.gen(function* () {331      const asked = yield* counted();332333      const read = yield* readProposal("datekit", "prop-000007").pipe(334        Effect.provide(335          Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(336            Layer.provide(platformHandlers(asked))337          )338        )339      );340341      expect(decodeShown(read).files.map(({ path }) => path)).toStrictEqual([342        askFile,343        testFile,344      ]);345    })346  );347348  it.effect(349    "is a not-found for a proposal or a project the platform does not know",350    () =>351      Effect.gen(function* () {352        const asked = yield* counted();353354        const platform = Layer.effect(355          Client,356          RpcTest.makeClient(Contracts)357        ).pipe(Layer.provide(platformHandlers(asked)));358359        const noProposal = yield* Effect.flip(360          readProposal("datekit", "prop-000099").pipe(Effect.provide(platform))361        );362363        const noProject = yield* Effect.flip(364          readProposal("burrow", "prop-000007").pipe(Effect.provide(platform))365        );366367        expect(isNotFound(noProposal)).toBeTruthy();368        expect(isNotFound(noProject)).toBeTruthy();369        expect((yield* Ref.get(asked)).proposal).toBe(2);370      })371  );372373  it.effect(374    "is a not-found, asking nothing, for an address that names no proposal",375    () =>376      Effect.gen(function* () {377        const asked = yield* counted();378379        const refused = yield* Effect.flip(380          readProposal("datekit", "not a proposal").pipe(381            Effect.provide(382              Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(383                Layer.provide(platformHandlers(asked))384              )385            )386          )387        );388389        expect(isNotFound(refused)).toBeTruthy();390        expect((yield* Ref.get(asked)).proposal).toBe(0);391      })392  );393});394395const runUntil = (done: Effect.Effect<boolean>) =>396  Effect.yieldNow.pipe(397    Effect.andThen(done),398    Effect.repeat({ times: 200, until: (held) => held })399  );400401describe("the proposal page's Today", () => {402  it.effect(403    "reads again when the proposal's draft settles, so its new decision is linked",404    () =>405      Effect.gen(function* () {406        const asked = yield* counted();407408        // One browser tab whose `ContractsClient` reaches the stub platform in process.409        const registry = yield* Effect.acquireRelease(410          Effect.sync(() =>411            AtomRegistry.make({412              initialValues: [413                Atom.initialValue(414                  ContractsClient.runtime.layer,415                  Layer.effect(416                    ContractsClient,417                    RpcTest.makeClient(webContracts, { flatten: true })418                  ).pipe(419                    Layer.provide(platformHandlers(asked)),420                    Layer.provideMerge(Reactivity.layer)421                  )422                ),423              ],424            })425          ),426          (made) =>427            Effect.sync(() => {428              made.dispose();429            })430        );431432        const today = projectTodayAtom(datekit);433434        registry.mount(today);435        yield* AtomRegistry.getResult(registry, today, {436          suspendOnWaiting: true,437        });438439        // What the watch does on `ProposalDrafted` (`keysOf` in `watch.ts`).440        yield* AtomRegistry.getResult(441          registry,442          ContractsClient.runtime.atom(443            Reactivity.invalidate(444              keysOf(445                datekit,446                ProjectEvent.cases.ProposalDrafted.make({447                  at: DateTime.makeUnsafe("2026-10-07T09:05:00Z"),448                  proposal: ready.proposal.id,449                  ready: true,450                  seq: 4,451                })452              )453            )454          ),455          { suspendOnWaiting: true }456        );457458        expect(459          yield* runUntil(460            Ref.get(asked).pipe(Effect.map(({ today: seen }) => seen > 1))461          )462        ).toBeTruthy();463      })464  );465});