decision.test.tsx
This file
Path
apps/web/test/decision.test.tsx
670 lines · 19.8 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Contracts } from "@repo/protocol/contracts";4import { RefNameText } from "@repo/protocol/domain/common";5import { DecisionSubject } from "@repo/protocol/domain/decision";6import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";7import { DraftState } from "@repo/protocol/domain/proposal";8import {9 AskId,10 CommitSha,11 DecisionId,12 Handle,13 LaneName,14 ProjectName,15 ProposalId,16 RepoPath,17} from "@repo/protocol/ids";18import { DecisionClosed } from "@repo/protocol/refusal";19import type { UnknownDecision } from "@repo/protocol/refusal";20import { asTester, unanswered } from "@repo/protocol/testing";21import { Cause, DateTime, Effect, Exit, Layer, Option, Ref } from "effect";22import { AsyncResult, Atom, AtomRegistry, Reactivity } from "effect/reactivity";23import { RpcTest } from "effect/rpc";24import type { ReactElement } from "react";25import { renderToStaticMarkup } from "react-dom/server";2627import { decideAtom } from "../src/client/decide.ts";28import { keys } from "../src/client/keys.ts";29import { todayAtom } from "../src/client/today.ts";30import { DecisionCard } from "../src/features/decision/decision-card.tsx";31import {32 DecisionRead,33 DecisionView,34} from "../src/features/decision/decision-page.tsx";35import type { DecisionPageData } from "../src/features/decision/decision-page.tsx";36import { patchFiles } from "../src/features/finish/files.ts";37import { waiverPatchOf } from "../src/features/finish/patch.ts";38import { InboxView } from "../src/features/inbox/inbox-page.tsx";39import { Decisions, InboxRead, Takeable } from "../src/features/inbox/read.ts";40import { ProposalFailure } from "../src/features/proposal/failure.tsx";41import {42 DraftRead,43 draftReadOf,44 readDraft,45} from "../src/features/proposal/live-draft.ts";46import { RefusalView } from "../src/features/shared/refusal.tsx";47import { ContractsClient, webContracts } from "../src/surfaces.ts";4849const markupOf = (element: ReactElement) => renderToStaticMarkup(element);5051const plainTextOf = (markup: string) =>52 markup53 .replaceAll(/<[^>]+>/gu, " ")54 .replaceAll("'", "'")55 .replaceAll(""", '"')56 .replaceAll("&", "&")57 .replaceAll(/\s+/gu, " ");5859const readOf = (result: AsyncResult.AsyncResult<Today, unknown>): InboxRead =>60 InboxRead.cases.Read.make({61 asks: Takeable.cases.Listed.make({ asks: [] }),62 decisions: AsyncResult.isSuccess(result)63 ? Decisions.cases.Decides.make({ today: result.value })64 : Decisions.cases.Unreachable.make({}),65 handle: Handle.make("okonkwo"),66 held: 0,67 running: 0,68 work: [],69 });7071const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");7273const okonkwo = Handle.make("okonkwo");7475const datekit = ProjectName.make("oscabriel/datekit");7677const stray: Decision = {78 deciders: [okonkwo],79 default: "revert",80 evidence: [],81 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),82 id: DecisionId.make("dec-000002"),83 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),84 project: datekit,85 subject: DecisionSubject.cases.StrayPush.make({86 after: CommitSha.make("b".repeat(40)),87 before: CommitSha.make("a".repeat(40)),88 ref: RefNameText.make("refs/heads/main"),89 }),90};9192const todayWith = (decisions: readonly Decision[]): Today => ({93 budget: { finishes: 0, total: 5, used: 1 },94 decider: okonkwo,95 decisions,96 expiringSoon: decisions.map(({ id }) => id),97 newcomers: [],98 overflow: 0,99 unattended: [],100});101102interface Asked {103 readonly decide: readonly unknown[];104 readonly listAsks: number;105 readonly today: number;106}107108type Decide = (payload: {109 readonly choice: Choice;110}) => Effect.Effect<111 { readonly decision: Decision },112 DecisionClosed | UnknownDecision113>;114115const contracts = (asked: Ref.Ref<Asked>, answer: Decide) => {116 const decided = Ref.makeUnsafe(false);117118 const handlers = Layer.mergeAll(119 unanswered,120 Contracts.toLayerHandler("today", () =>121 Ref.update(asked, (all) => ({ ...all, today: all.today + 1 })).pipe(122 Effect.andThen(Ref.get(decided)),123 Effect.map((done) => todayWith(done ? [] : [stray]))124 )125 ),126 Contracts.toLayerHandler("listAsks", () =>127 Ref.update(asked, (all) => ({ ...all, listAsks: all.listAsks + 1 })).pipe(128 Effect.as({ asks: [] })129 )130 ),131 Contracts.toLayerHandler("decide", (payload) =>132 Ref.update(asked, (all) => ({133 ...all,134 decide: [...all.decide, payload],135 })).pipe(136 Effect.andThen(Ref.set(decided, true)),137 Effect.andThen(answer(payload))138 )139 )140 );141142 return Layer.effect(ContractsClient)(143 RpcTest.makeClient(webContracts, { flatten: true })144 ).pipe(145 Layer.provide([handlers, asTester]),146 Layer.provideMerge(Reactivity.layer)147 );148};149150const registryOver = (151 layer: Layer.Layer<ContractsClient | Reactivity.Reactivity>152) =>153 Effect.acquireRelease(154 Effect.sync(() =>155 AtomRegistry.make({156 initialValues: [157 Atom.initialValue(ContractsClient.runtime.layer, layer),158 ],159 })160 ),161 (registry) =>162 Effect.sync(() => {163 registry.dispose();164 })165 );166167const projectAsks = ContractsClient.query(168 "listAsks",169 { project: datekit },170 { reactivityKeys: keys.project(datekit) }171);172173const decideOnce = (174 answer: Decide,175 input: {176 readonly choice: Choice;177 readonly note?: string;178 }179) =>180 Effect.gen(function* () {181 const asked = yield* Ref.make<Asked>({ decide: [], listAsks: 0, today: 0 });182 const registry = yield* registryOver(contracts(asked, answer));183 const today = todayAtom();184185 registry.mount(today);186 registry.mount(projectAsks);187 registry.mount(decideAtom);188189 yield* AtomRegistry.getResult(registry, today);190 yield* AtomRegistry.getResult(registry, projectAsks);191192 registry.set(decideAtom, {193 decision: stray.id,194 project: datekit,195 ...input,196 });197198 const outcome = yield* Effect.exit(199 AtomRegistry.getResult(registry, decideAtom, { suspendOnWaiting: true })200 );201202 yield* AtomRegistry.getResult(registry, today, { suspendOnWaiting: true });203 yield* AtomRegistry.getResult(registry, projectAsks, {204 suspendOnWaiting: true,205 });206207 return {208 asked: yield* Ref.get(asked),209 decided: registry.get(decideAtom),210 outcome,211 today: registry.get(today),212 };213 }).pipe(Effect.scoped);214215const taken: Decide = ({ choice }) =>216 Effect.succeed({217 decision: {218 ...stray,219 decided: { at: now, by: okonkwo, choice },220 },221 });222223describe("the decide atom", () => {224 it.live(225 "sends the choice and the note as the decide contract's payload",226 () =>227 Effect.gen(function* () {228 const { asked, outcome } = yield* decideOnce(taken, {229 choice: "revert",230 note: "Pushed by the old deploy key.",231 });232233 expect(Exit.isSuccess(outcome)).toBeTruthy();234 expect(asked.decide).toStrictEqual([235 {236 choice: "revert",237 decision: "dec-000002",238 note: "Pushed by the old deploy key.",239 project: "oscabriel/datekit",240 },241 ]);242 })243 );244245 it.live("sends no note when the maintainer wrote none", () =>246 Effect.gen(function* () {247 const { asked } = yield* decideOnce(taken, { choice: "adopt" });248249 expect(asked.decide).toStrictEqual([250 {251 choice: "adopt",252 decision: "dec-000002",253 project: "oscabriel/datekit",254 },255 ]);256 })257 );258259 it.live(260 "on success reads Today and the project again, and the decision leaves Today",261 () =>262 Effect.gen(function* () {263 const { asked, today } = yield* decideOnce(taken, {264 choice: "revert",265 });266267 expect({268 listAsks: asked.listAsks,269 today: asked.today,270 }).toStrictEqual({ listAsks: 2, today: 2 });271 expect(272 markupOf(273 <InboxView now={now} onDecide={() => {}} read={readOf(today)} />274 )275 ).not.toContain('data-decision="dec-000002"');276 })277 );278279 it.live(280 "shows DecisionClosed as the refusal, and reads Today again without the decision",281 () =>282 Effect.gen(function* () {283 const closed = new DecisionClosed({ decision: stray.id });284285 const { asked, decided, outcome, today } = yield* decideOnce(286 () => Effect.fail(closed),287 { choice: "revert" }288 );289290 const markup = markupOf(291 <InboxView292 decided={decided}293 now={now}294 onDecide={() => {}}295 read={readOf(today)}296 />297 );298299 expect(Exit.isFailure(outcome)).toBeTruthy();300 expect(asked.today).toBe(2);301 expect(markup).toContain(markupOf(<RefusalView refusals={[closed]} />));302 expect(markup).not.toContain('data-decision="dec-000002"');303 })304 );305});306307const acceptOf = (markup: string) =>308 /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";309310describe("DecisionCard for an OpenProposal", () => {311 const askFile = `${Brand.configDir}/asks/x.ask.ts`;312313 const proposal = ProposalId.make("prop-000007");314315 const opening: Decision = {316 deciders: [okonkwo],317 default: "decline",318 evidence: [319 { label: "want", value: "formatISO keeps the offset it was given." },320 {321 label: askFile,322 value: 'export default ask({ id: "x", kind: kinds.fix });\n',323 },324 { label: "red first", value: "unit: expected '+02:00', got 'Z'" },325 ],326 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),327 id: DecisionId.make("dec-000003"),328 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),329 project: datekit,330 subject: DecisionSubject.cases.OpenProposal.make({ proposal }),331 };332333 const card = (draft: DraftState) =>334 markupOf(335 <DecisionCard336 decision={opening}337 draft={readDraft(draft)}338 now={now}339 onDecide={() => {}}340 />341 );342343 const shown = (draft?: DraftState) => {344 const wanted = {345 expiresAt: opening.expiresAt,346 files: [],347 id: proposal,348 openedAt: opening.openedAt,349 project: datekit,350 proposer: Handle.make("lin-h"),351 state: "open" as const,352 want: "formatISO keeps the offset it was given.",353 };354355 return {356 files: [],357 proposal: draft === undefined ? wanted : { ...wanted, draft },358 };359 };360361 const cardRead = (draft?: DraftState) =>362 markupOf(363 <DecisionCard364 decision={opening}365 draft={draftReadOf(AsyncResult.success(shown(draft)))}366 now={now}367 onDecide={() => {}}368 />369 );370371 const drafting = DraftState.cases.Drafting.make({372 round: 2,373 startedAt: now,374 });375376 const ready = DraftState.cases.Ready.make({377 attempts: 1,378 model: "@cf/moonshotai/kimi-k2.7-code",379 red: { lane: LaneName.make("unit"), signature: "expected '+02:00'" },380 round: 1,381 });382383 const failed = DraftState.cases.Failed.make({384 attempts: 3,385 model: "@cf/moonshotai/kimi-k2.7-code",386 refusal: "NotRedFirst",387 round: 2,388 });389390 it("shows a file's path as a heading and its content in a pre", () => {391 const markup = card(ready);392393 expect(markup).toMatch(new RegExp(`<h4[^>]*>${askFile}</h4>`, "u"));394 expect(markup).toMatch(395 /<pre[^>]*>export default ask\(\{ id: "x", kind: kinds\.fix \}\);\n<\/pre>/u396 );397 expect(markup).not.toMatch(new RegExp(`<dt[^>]*>${askFile}</dt>`, "u"));398 expect(markup).toMatch(/<dt[^>]*>red first<\/dt>/u);399 });400401 it("holds Accept while the proposal's draft is drafting", () => {402 const markup = card(drafting);403404 expect(acceptOf(markup)).toContain('disabled=""');405 expect(markup).toContain("Drafting…");406 expect(407 /<button[^>]*data-choice="decline"[^>]*>/u.exec(markup)?.[0]408 ).not.toContain('disabled=""');409 });410411 it("holds Accept on the server, until the browser has read the draft", () => {412 const markup = markupOf(413 <DecisionCard decision={opening} now={now} onDecide={() => {}} />414 );415416 expect(acceptOf(markup)).toContain('disabled=""');417 expect(markup).toContain("Reading the draft…");418 expect(draftReadOf(AsyncResult.initial(true))).toStrictEqual(419 DraftRead.Unread({ failed: false })420 );421 });422423 it("holds Accept, without a spinner, when the browser could not read the draft", () => {424 const read = draftReadOf(AsyncResult.failure(Cause.fail("offline")));425426 const markup = markupOf(427 <DecisionCard428 decision={opening}429 draft={read}430 now={now}431 onDecide={() => {}}432 />433 );434435 expect(read).toStrictEqual(DraftRead.Unread({ failed: true }));436 expect(acceptOf(markup)).toContain('disabled=""');437 expect(markup).toContain("Draft not read; reload");438 expect(markup).not.toContain("Reading the draft…");439 expect(440 /<button[^>]*data-choice="accept"[^>]*>.*?<\/button>/u.exec(markup)?.[0]441 ).not.toContain('data-slot="spinner"');442 });443444 it("offers Accept once the read draft is ready, failed (an earlier ready draft or the want alone), or the proposal is a want alone", () => {445 for (const markup of [cardRead(ready), cardRead(failed), cardRead()]) {446 expect(acceptOf(markup)).not.toContain('disabled=""');447 expect(markup).not.toContain("Reading the draft…");448 expect(markup).not.toContain("Drafting…");449 }450 });451452 it("holds Accept, saying why, while the read draft is drafting", () => {453 const markup = cardRead(drafting);454455 expect(acceptOf(markup)).toContain('disabled=""');456 expect(markup).toContain("Drafting…");457 expect(markup).not.toContain("Reading the draft…");458 });459460 it("offers Accept once the draft is ready", () => {461 const markup = card(ready);462463 expect(acceptOf(markup)).not.toContain('disabled=""');464 expect(markup).not.toContain("Drafting…");465 });466467 it("shows a check at the repo's root as code too", () => {468 const markup = markupOf(469 <DecisionCard470 decision={{471 ...opening,472 evidence: [473 ...opening.evidence,474 { label: "offset.test.ts", value: "test('keeps +02:00');\n" },475 ],476 }}477 draft={readDraft(ready)}478 now={now}479 onDecide={() => {}}480 />481 );482483 expect(markup).toMatch(/<h4[^>]*>offset\.test\.ts<\/h4>/u);484 expect(markup).not.toMatch(/<dt[^>]*>offset\.test\.ts<\/dt>/u);485 expect(markup).toMatch(/<dt[^>]*>want<\/dt>/u);486 });487488 it("links the proposal's page", () => {489 expect(card(ready)).toContain(490 'href="/oscabriel/datekit/proposals/prop-000007"'491 );492 });493});494495const vellum = ProjectName.make("oscabriel/vellum");496497const waiver: Decision = {498 deciders: [okonkwo],499 default: "decline",500 evidence: [501 {502 label: "patch",503 value: [504 "diff --git a/test/attributes.test.ts b/test/attributes.test.ts",505 "index 1111111..2222222 100644",506 "--- a/test/attributes.test.ts",507 "+++ b/test/attributes.test.ts",508 "@@ -6,4 +6,5 @@",509 ' import { escape } from "../src/escape.ts";',510 " ",511 ' test("quotes", () => {',512 '+test.skip("a quote in a code span", () => {});',513 ' expect(escape(\'"\')).toBe(""");',514 "",515 ].join("\n"),516 },517 ],518 expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),519 id: DecisionId.make("dec-000002"),520 openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),521 project: vellum,522 subject: DecisionSubject.cases.Waiver.make({523 ask: AskId.make("escape-attribute-quotes"),524 at: { line: 9, path: RepoPath.make("test/attributes.test.ts") },525 marker: ".skip(",526 reason: "A quote in a code span needs the escaper's context.",527 }),528};529530const pageOf = (531 read: DecisionRead,532 chosen?: Decision,533 failure?: ReactElement534) => {535 const data: DecisionPageData = {536 decision: waiver.id,537 now,538 project: vellum,539 read,540 };541542 const files = DecisionRead.guards.Found(read)543 ? Option.match(waiverPatchOf(read.decision), {544 onNone: () => [],545 onSome: (patch) => patchFiles(patch, [], "test"),546 })547 : [];548549 return markupOf(550 <DecisionView551 data={data}552 files={files}553 here="/oscabriel/vellum/decisions/dec-000002"554 onDecide={() => {}}555 taken={chosen}556 {...(failure === undefined ? {} : { failure })}557 />558 );559};560561const found = DecisionRead.cases.Found.make({562 decision: waiver,563 placed: [],564 soon: true,565});566567describe(DecisionView, () => {568 it("titles the page with the subject and says when it expires, its default and whose move it is", () => {569 const text = plainTextOf(pageOf(found));570571 expect(text).toContain(572 "Allow .skip( at test/attributes.test.ts:9 in the answer to escape-attribute-quotes"573 );574 expect(text).toContain("Expires in 22 h");575 expect(text).toContain("default: decline");576 expect(text).toContain("your move");577 });578579 it("draws a waiver's marker at its line, in the answer's diff of that file", () => {580 const markup = pageOf(found);581 const line = markup.indexOf('data-line="9"');582 const note = markup.indexOf('data-note-line="9"');583 const after = markup.indexOf('data-line="10"');584585 expect(markup).toContain('data-file="test/attributes.test.ts"');586 expect(line).toBeGreaterThan(-1);587 expect(note).toBeGreaterThan(line);588 expect(after).toBeGreaterThan(note);589 expect(markup.slice(note, after)).toContain('data-marker=".skip("');590 });591592 it("says each fact of the evidence once: who pushed the answer, and no second answer or restated escape", () => {593 const text = plainTextOf(594 pageOf(595 DecisionRead.cases.Found.make({596 decision: {597 ...waiver,598 evidence: [599 ...waiver.evidence,600 { label: "answer", value: "bram at 97caa5b (push-97caa5b-bram)" },601 {602 label: "escape",603 value:604 "test/attributes.test.ts:9: .skip( -- A quote in a code span needs the escaper's context.",605 },606 ],607 },608 placed: [],609 soon: true,610 })611 )612 );613614 expect(text).toContain("Pushed by bram at 97caa5b (push-97caa5b-bram)");615 expect(text.match(/\bAnswer\b/gu)).toHaveLength(1);616 expect(text).not.toContain("test/attributes.test.ts:9: .skip(");617 });618619 it("says under each choice what it does", () => {620 const markup = pageOf(found);621622 expect(markup).toContain('data-consequence="accept"');623 expect(markup).toContain('data-consequence="decline"');624 expect(plainTextOf(markup)).toContain(625 "The answer goes on through the gate with .skip( allowed there, with you as Decided-by."626 );627 });628629 it("once decided, shows the record and no choices", () => {630 const markup = pageOf(found, {631 ...waiver,632 decided: { at: now, by: okonkwo, choice: "accept", note: "Split out." },633 });634635 expect(markup).not.toContain("data-choice=");636 expect(markup).toContain('data-decided="accept"');637 expect(plainTextOf(markup)).toContain("Accepted");638 expect(plainTextOf(markup)).toContain("Split out.");639 });640641 it("says why a choice came back refused, before the choices", () => {642 const closed = new DecisionClosed({ decision: waiver.id });643644 const markup = pageOf(645 found,646 undefined,647 <ProposalFailure648 cause={Cause.fail(closed)}649 doing="take this decision"650 here="/oscabriel/vellum/decisions/dec-000002"651 />652 );653654 const refusal = markup.indexOf('data-refusal="DecisionClosed"');655656 expect(refusal).toBeGreaterThan(-1);657 expect(refusal).toBeLessThan(markup.indexOf("data-choices="));658 });659660 it("signed out, says what a decision is and who takes it, with no choices and no evidence", () => {661 const markup = pageOf(DecisionRead.cases.SignedOut.make({}));662 const text = plainTextOf(markup);663664 expect(markup).not.toContain("data-choice=");665 expect(markup).not.toContain(".skip(");666 expect(text).toContain("A maintainer takes it on their Today");667 expect(markup).toContain('href="/oscabriel/vellum/people"');668 expect(text).toContain(`${Brand.cli} today --project oscabriel/vellum`);669 });670});