Skip to content
Myr

finish.test.tsx

This file

Path

apps/web/test/finish.test.tsx

498 lines · 14.1 KiB · TypeScript

Last changed by

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { Verdict } from "@repo/protocol/domain/answer";4import type { Ask } from "@repo/protocol/domain/ask";5import { CheckSpec } from "@repo/protocol/domain/check";6import { Glob } from "@repo/protocol/domain/common";7import { DecisionSubject } from "@repo/protocol/domain/decision";8import type { Decision } from "@repo/protocol/domain/decision";9import { Outcome } from "@repo/protocol/domain/outcome";10import {11  AskId,12  CheckVersion,13  CommitSha,14  DecisionId,15  Handle,16  KindName,17  LandedSha,18  LaneName,19  PatchId,20  ProjectName,21  ProposalId,22  RepoPath,23  TreeSha,24} from "@repo/protocol/ids";25import { Weakened } from "@repo/protocol/refusal";26import { DateTime, Option } from "effect";27import type { ReactElement } from "react";28import { renderToStaticMarkup } from "react-dom/server";2930import type { PlacedRefusal } from "../src/features/finish/annotation.tsx";31import { patchFiles } from "../src/features/finish/files.ts";32import { FinishView } from "../src/features/finish/finish-view.tsx";33import type {34  FinishDecision,35  FinishViewProps,36} from "../src/features/finish/finish-view.tsx";37import { changedFiles, patchOf } from "../src/features/finish/patch.ts";38import {39  marksKey,40  readMarks,41  writeMark,42} from "../src/features/finish/read-marks.ts";4344const ENTITIES: ReadonlyMap<string, string> = new Map([45  ["&#x27;", "'"],46  ["&amp;", "&"],47  ["&gt;", ">"],48  ["&lt;", "<"],49  ["&quot;", '"'],50]);5152const markupOf = (element: ReactElement) => renderToStaticMarkup(element);5354const textIn = (markup: string) =>55  markup56    .replaceAll(/<[^>]+>/gu, " ")57    .replaceAll(58      /&(?:#x27|amp|gt|lt|quot);/gu,59      (entity) => ENTITIES.get(entity) ?? entity60    )61    .replaceAll(/\s+/gu, " ");6263const textOf = (element: ReactElement) => textIn(markupOf(element));6465const PLATFORM_URL = "https://platform-test.example.workers.dev";6667const datekit = ProjectName.make("oscabriel/datekit");6869const parseIso = AskId.make("parse-iso");7071const head = CommitSha.make("e".repeat(40));7273const base = CommitSha.make("1".repeat(40));7475const okonkwo = Handle.make("okonkwo");7677const PATCH = [78  "diff --git a/src/parse.ts b/src/parse.ts",79  "index 1111111..2222222 100644",80  "--- a/src/parse.ts",81  "+++ b/src/parse.ts",82  "@@ -1,2 +1,2 @@",83  "-export const parse = (text: string) => new Date(text);",84  "+export const parse = (text: string) => fromIso(text);",85  " export const format = String;",86  "diff --git a/test/parse.test.ts b/test/parse.test.ts",87  "index 3333333..4444444 100644",88  "--- a/test/parse.test.ts",89  "+++ b/test/parse.test.ts",90  "@@ -1 +1,2 @@",91  ' import { parse } from "../src/parse.ts";',92  '+test("leap day", () => parse("2028-02-29"));',93  "diff --git a/src/iso.ts b/src/iso.ts",94  "new file mode 100644",95  "index 0000000..5555555",96  "--- /dev/null",97  "+++ b/src/iso.ts",98  "@@ -0,0 +1 @@",99  "+export const fromIso = (text: string) => text;",100  "diff --git a/src/legacy.ts b/src/legacy.ts",101  "deleted file mode 100644",102  "index 6666666..0000000",103  "--- a/src/legacy.ts",104  "+++ /dev/null",105  "@@ -1 +0,0 @@",106  "-export const legacy = true;",107  "diff --git a/docs/old.md b/docs/new.md",108  "similarity index 100%",109  "rename from docs/old.md",110  "rename to docs/new.md",111  "",112].join("\n");113114const FILES = [115  "src/parse.ts",116  "test/parse.test.ts",117  "src/iso.ts",118  "src/legacy.ts",119  "docs/new.md",120];121122const finishOf = (evidence: Decision["evidence"]): FinishDecision => ({123  deciders: [okonkwo],124  default: "decline",125  evidence,126  expiresAt: DateTime.makeUnsafe("2026-10-09T12:00:00Z"),127  id: DecisionId.make("dec-000007"),128  openedAt: DateTime.makeUnsafe("2026-10-07T09:00:00Z"),129  project: datekit,130  subject: DecisionSubject.cases.Finish.make({ ask: parseIso, head }),131});132133const withPatch = finishOf([134  { label: "answer", value: `ines-v at ${head}` },135  { label: "patch", value: PATCH },136]);137138const withoutPatch = finishOf([139  { label: "answer", value: `ines-v at ${head}` },140]);141142const ask: Ask = {143  askedBy: okonkwo,144  blockedBy: [],145  brief: { want: "An ISO date with a leap day parses to that day." },146  check: CheckSpec.cases.RedThenGreen.make({147    path: RepoPath.make("test/parse.test.ts"),148  }),149  file: RepoPath.make(`${Brand.configDir}/asks/parse-iso.ask.ts`),150  id: parseIso,151  kind: KindName.make("fix"),152  openedAt: DateTime.makeUnsafe("2026-10-05T09:00:00Z"),153  openedIn: LandedSha.make("9".repeat(40)),154  project: datekit,155  state: "claimed",156  territory: { module: "datekit", paths: [Glob.make("src/**")] },157};158159const verdict: Verdict = {160  ask: parseIso,161  at: DateTime.makeUnsafe("2026-10-07T08:00:00Z"),162  base,163  checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),164  head,165  heldBack: [],166  lanes: [167    {168      command: "bun test",169      durationMs: 1200,170      lane: LaneName.make("unit"),171      result: "passed",172    },173  ],174  outcome: Outcome.cases.AwaitingFinish.make({ decider: okonkwo }),175  patchId: PatchId.make("2".repeat(64)),176  project: datekit,177  stage: "human",178  tree: TreeSha.make("3".repeat(40)),179  verifier: "platform",180};181182const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");183184const filesOf = (decision: FinishDecision) =>185  Option.match(patchOf(decision), {186    onNone: () => [],187    onSome: (patch) => patchFiles(patch, ["src/**"], "test"),188  });189190const pageOf = (191  decision: FinishDecision,192  extra: Partial<FinishViewProps> = {}193) => (194  <FinishView195    decision={decision}196    files={filesOf(decision)}197    now={now}198    onDecide={() => {}}199    platformUrl={PLATFORM_URL}200    {...extra}201  />202);203204const drawnFilesOf = (markup: string) =>205  [...markup.matchAll(/<section aria-label="(?<file>[^"]+)" data-file=/gu)].map(206    (match) => match.groups?.file207  );208209const placed: PlacedRefusal = {210  line: 2,211  path: "test/parse.test.ts",212  refusal: new Weakened({213    at: { line: 2, path: RepoPath.make("test/parse.test.ts") },214    weakening: { marker: ".only(" },215  }),216  round: 1,217};218219describe(FinishView, () => {220  it("lists the changed files on the server, the territory's first, then tests, then the rest", () => {221    expect(drawnFilesOf(markupOf(pageOf(withPatch)))).toStrictEqual([222      "src/iso.ts",223      "src/legacy.ts",224      "src/parse.ts",225      "test/parse.test.ts",226      "docs/new.md",227    ]);228229    for (const file of FILES) {230      expect(textOf(pageOf(withPatch))).toContain(file);231    }232  });233234  it("leaves the drawing to the browser: the server sends the diff as plain text", () => {235    const markup = markupOf(pageOf(withPatch));236237    expect(markup).not.toContain("<diffs-container");238    expect(markup).toContain('data-diff="plain"');239    expect(markup).toContain(240      "export const parse = (text: string) =&gt; fromIso(text);"241    );242  });243244  it("draws a refusal under the line its `at` names, in the file it names", () => {245    const markup = markupOf(pageOf(withPatch, { placed: [placed] }));246    const file = markup.indexOf('data-file="test/parse.test.ts"');247    const line = markup.indexOf('data-line="2"', file);248    const note = markup.indexOf('data-note-line="2"', file);249250    expect(file).toBeGreaterThan(-1);251    expect(note).toBeGreaterThan(line);252    expect(markup.slice(note)).toContain('data-refusal="Weakened"');253    expect(textOf(pageOf(withPatch, { placed: [placed] }))).toContain(254      "Refused here in round 1"255    );256  });257258  it("counts the files read, never a person, and offers Mark read on each file", () => {259    const markup = markupOf(260      pageOf(withPatch, { read: new Set(["src/parse.ts"]) })261    );262263    expect(264      textOf(pageOf(withPatch, { read: new Set(["src/parse.ts"]) }))265    ).toContain("1 of 5 files read");266    expect(markup).toContain('data-mark-read="src/iso.ts"');267    expect(markup).toMatch(268      /aria-pressed="true"[^>]*data-mark-read="src\/parse.ts"/u269    );270    expect(textOf(pageOf(withPatch))).toContain("Mark read");271    expect(textOf(pageOf(withPatch))).not.toMatch(/review/iu);272  });273274  it("says a newer head was pushed, above the diff, and keeps the diff the decision names", () => {275    const text = textOf(pageOf(withPatch, { newerHead: base }));276277    expect(text).toContain("A new answer was pushed");278    expect(text).toContain("Reload the diff");279    expect(text).toContain(280      "export const parse = (text: string) => fromIso(text);"281    );282  });283284  it("numbers the three lines that finish it", () => {285    const markup = markupOf(pageOf(withPatch));286287    const list =288      /<ol[^>]*data-finish-lines=""[^>]*>(?<items>[\s\S]*?)<\/ol>/u.exec(markup)289        ?.groups?.items;290291    expect([...(list ?? "").matchAll(/<li\b/gu)]).toHaveLength(3);292  });293294  it("without a patch, shows the lines that fetch the head and finish it, and no diff", () => {295    const element = pageOf(withoutPatch);296    const text = textOf(element);297298    expect(text).toContain(`git fetch ${PLATFORM_URL}/`);299    expect(text).toContain(` ${head}`);300    expect(text).toContain(301      `${Brand.cli} finish parse-iso --project oscabriel/datekit`302    );303    expect(markupOf(element)).not.toContain("<diffs-container");304    expect(markupOf(element)).not.toContain('data-diff="');305  });306307  it("fetches from the answer's fork when the decision names it, and finishes from the verdict's base", () => {308    const named = finishOf([309      ...withoutPatch.evidence,310      { label: "fork", value: "datekit--parse-iso--ines-v" },311    ]);312313    const text = textOf(pageOf(named, { verdict }));314315    expect(text).toContain(316      `git fetch ${PLATFORM_URL}/datekit--parse-iso--ines-v.git ${head}`317    );318    expect(text).toContain(`--base ${base}`);319  });320321  it("shows the ask's want and the verdict beside the diff", () => {322    const element = pageOf(withPatch, { ask, verdict });323324    expect(textOf(element)).toContain(325      "An ISO date with a leap day parses to that day."326    );327    expect(markupOf(element)).toContain('data-outcome="AwaitingFinish"');328  });329330  it("offers its choices with what each does", () => {331    const text = textOf(pageOf(withPatch));332333    expect(text).toContain(334      "Lands the answer as it is, with you as Finished-by."335    );336    expect(text).toContain(337      "Nothing lands; the answer keeps waiting for a finish."338    );339  });340});341342describe("a finish taken on its page", () => {343  it("keeps the choice's record at the diff's foot, where its choices were, and offers them no more", () => {344    const markup = markupOf(345      pageOf({346        ...withPatch,347        decided: { at: now, by: okonkwo, choice: "accept" },348      })349    );350351    const bar = markup.slice(markup.indexOf("data-decision-bar"));352353    expect(markup).not.toContain("data-choice=");354    expect(bar).toContain('data-decided="accept"');355    expect(textIn(bar)).toContain(356      "Accepted · Lands the answer as it is, with you as Finished-by."357    );358  });359});360361const storageOver = (kept: Map<string, string>): Storage => ({362  clear: () => {363    kept.clear();364  },365  getItem: (key) => kept.get(key) ?? null,366  key: (index) => [...kept.keys()][index] ?? null,367  get length() {368    return kept.size;369  },370  removeItem: (key) => {371    kept.delete(key);372  },373  setItem: (key, value) => {374    kept.set(key, value);375  },376});377378const refusing: Storage = {379  clear: () => {380    throw new Error("refused");381  },382  getItem: () => {383    throw new Error("refused");384  },385  key: () => {386    throw new Error("refused");387  },388  length: 0,389  removeItem: () => {390    throw new Error("refused");391  },392  setItem: () => {393    throw new Error("refused");394  },395};396397describe("the read marks", () => {398  const key = marksKey("datekit", "dec-000007");399400  const files = filesOf(withPatch).map(({ file, patchId }) => ({401    patchId,402    path: file.path,403  }));404405  const [first] = files;406407  it("marks a file read in this browser, against its change", () => {408    const storage = storageOver(new Map());409410    if (first !== undefined) {411      writeMark(storage, key, head, first, true);412    }413414    expect([...readMarks(storage, key, head, files)]).toStrictEqual([415      "src/iso.ts",416    ]);417  });418419  it("forgets every mark once a new head is pushed", () => {420    const storage = storageOver(new Map());421422    if (first !== undefined) {423      writeMark(storage, key, head, first, true);424    }425426    expect(readMarks(storage, key, base, files).size).toBe(0);427  });428429  it("reads a file unread when its change is not the one marked", () => {430    const storage = storageOver(new Map());431432    if (first !== undefined) {433      writeMark(storage, key, head, { ...first, patchId: "00000000" }, true);434    }435436    expect(readMarks(storage, key, head, files).size).toBe(0);437  });438439  it("keeps working, with no marks, when the storage refuses", () => {440    expect(() => {441      if (first !== undefined) {442        writeMark(refusing, key, head, first, true);443      }444    }).not.toThrow();445    expect(readMarks(refusing, key, head, files).size).toBe(0);446    expect(readMarks(undefined, key, head, files).size).toBe(0);447  });448});449450describe(patchOf, () => {451  it("gives the diff a Finish decision carries, and nothing for one without", () => {452    expect(patchOf(withPatch)).toStrictEqual(Option.some(PATCH));453    expect(patchOf(withoutPatch)).toStrictEqual(Option.none());454  });455456  it("never gives a diff for another subject, whatever its evidence says", () => {457    const proposal: Decision = {458      ...withPatch,459      subject: DecisionSubject.cases.OpenProposal.make({460        proposal: ProposalId.make("prop-000001"),461      }),462    };463464    expect(patchOf(proposal)).toStrictEqual(Option.none());465  });466});467468describe(changedFiles, () => {469  it("lists each file a diff changes, by where it ends up, or where it was when deleted", () => {470    expect(changedFiles(PATCH)).toStrictEqual(FILES);471  });472473  it("names a path with a space without the tab git ends its file lines with", () => {474    // git ends `---`/`+++` with a tab when the path holds a space.475    const spaced = [476      "diff --git a/docs/read me.md b/docs/read me.md",477      "index 1111111..2222222 100644",478      "--- a/docs/read me.md\t",479      "+++ b/docs/read me.md\t",480      "@@ -1 +1 @@",481      "-Old.",482      "+New.",483      "diff --git a/old notes.md b/old notes.md",484      "deleted file mode 100644",485      "index 3333333..0000000",486      "--- a/old notes.md\t",487      "+++ /dev/null",488      "@@ -1 +0,0 @@",489      "-Gone.",490      "",491    ].join("\n");492493    expect(changedFiles(spaced)).toStrictEqual([494      "docs/read me.md",495      "old notes.md",496    ]);497  });498});