Skip to content
Myr

ask.test.tsx

This file

Path

apps/web/test/ask.test.tsx

660 lines · 20.1 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import type { Ask } from "@repo/protocol/domain/ask";5import { Outcome } from "@repo/protocol/domain/outcome";6import {7  AskId,8  BlobSha,9  CommitSha,10  Handle,11  ProjectName,12  RepoPath,13} from "@repo/protocol/ids";14import {15  OutOfScope,16  UnknownAsk,17  UnknownPath,18  UnknownProject,19} from "@repo/protocol/refusal";20import { explain } from "@repo/protocol/render";21import { asTester, unanswered } from "@repo/protocol/testing";22import { isNotFound } from "@tanstack/react-router";23import { Effect, Layer, Ref, Schema, Stream } from "effect";24import { RpcTest } from "effect/rpc";2526import { readAsk } from "../src/features/answer/reads.ts";27import { AskView } from "../src/features/ask/ask-page.tsx";28import { NoSuchAsk } from "../src/features/ask/refused.tsx";29import { askStates } from "../src/features/shared/ask-progress.ts";30import { Refusals } from "../src/features/shared/refusals.ts";31import {32  ask,33  askId,34  brief,35  claimedEvent,36  closedEvent,37  family,38  inOrder,39  judgedEvent,40  landedSha,41  markupOf,42  now,43  plainText,44  project,45  textOf,46  verdictOf,47} from "./ask-fixtures.ts";48import { textIn } from "./markup.ts";4950const platformUrl = "https://platform-test.example.workers.dev";5152const inPre = (markup: string) =>53  /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;5455const mainOf = (markup: string) =>56  /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";5758const trailOf = (markup: string) =>59  /<nav aria-label="Breadcrumb"[^>]*>(?<inner>.*?)<\/nav>/su.exec(markup)60    ?.groups?.inner ?? "";6162type AskProps = Parameters<typeof AskView>[0];6364const page = (shown = ask, more: Partial<AskProps> = {}) => (65  <AskView66    ask={shown}67    brief={brief}68    now={now}69    platformUrl={platformUrl}70    {...more}71  />72);7374const checkSource = (lines: number) => ({75  path: RepoPath.make("test/parse-week.test.ts"),76  sha: "f".repeat(40),77  text: Array.from(78    { length: lines },79    (_, index) => `expect(parseWeek("2026-W41-${index}")).not.toBeNull();`80  ).join("\n"),81});8283describe(AskView, () => {84  it("titles the page with the want, then reads the brief's sections in order", () => {85    const markup = markupOf(page());8687    expect(markup).toMatch(88      /<h1\b[^>]*>Parse ISO week dates like 2026-W41-3<\/h1>/u89    );90    expect(91      inOrder(textOf(page()), [92        "Current behaviour",93        "parseWeek returns null for 2026-W41-3.",94        "Out of scope",95        "Formatting week dates back to strings.",96        "Terms",97        "Week date: a date written as year, week and weekday.",98        "Context",99        "ISO 8601 numbers weeks from the Monday of the week holding 4 January.",100      ])101    ).toBeTruthy();102  });103104  it("sets a want of 80 characters at the headline, and a longer one a step down, whole", () => {105    const want =106      "The linter reports a heading that skips a level, such as a level-two heading followed by a level-four one.";107108    const long = markupOf(page({ ...ask, brief: { ...ask.brief, want } }));109110    expect(111      /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(long)?.groups?.classes112    ).toContain("text-title");113    expect(long).toContain(`>${want}</h1>`);114    expect(115      /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(markupOf(page()))?.groups116        ?.classes117    ).toContain("text-headline");118  });119120  it("leaves out a section the brief does not have", () => {121    const text = textOf(122      page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })123    );124125    expect(text).not.toContain("Current behaviour");126    expect(text).not.toContain("Out of scope");127    expect(text).not.toContain("Terms");128  });129130  it("names the project, its asks and the ask in the context bar's trail", () => {131    const trail = trailOf(markupOf(page()));132133    expect(inOrder(plainText(trail), ["datekit", "Asks", askId])).toBeTruthy();134    expect(trail).toContain('href="/oscabriel/datekit"');135  });136137  it("says an open ask is open to take, who it is held for, and gives its kind, asker and age", () => {138    const held = {139      ...ask,140      mentor: Handle.make("okonkwo"),141      reserve: "newcomers" as const,142    };143144    const text = textOf(page(held));145146    expect(text).toContain("Open to take");147    expect(text).toContain("Held for newcomers, mentored by okonkwo");148    expect(149      inOrder(text, ["fix", "asked by", "ines-v", "opened 2 d ago"])150    ).toBeTruthy();151    expect(markupOf(page(held))).toContain('href="/people/okonkwo"');152    expect(markupOf(page())).toContain('href="/people/ines-v"');153  });154155  it("gives the ask's territory and its check", () => {156    const text = textOf(page());157158    expect(159      inOrder(text, [160        "Territory and check",161        "@datekit/parse",162        "test/parse-week.test.ts",163      ])164    ).toBeTruthy();165    expect(markupOf(page())).toContain(166      'href="/oscabriel/datekit/blob/main/test/parse-week.test.ts"'167    );168  });169170  it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {171    expect(172      inOrder(textOf(page()), [173        `git clone ${platformUrl}/oscabriel/datekit.git`,174        `${Brand.cli} claim ${askId} --project oscabriel/datekit`,175        `${Brand.cli} check`,176      ])177    ).toBeTruthy();178  });179180  it("names who holds a claimed ask and offers no way to take it", () => {181    const states = askStates([claimedEvent(1, "tamsin")]);182183    const text = textIn(184      markupOf(page({ ...ask, state: "claimed" }, { states }))185    );186187    expect(text).toContain("Claimed by tamsin, no answer pushed yet");188    expect(text).toContain("tamsin's move");189    expect(text).not.toContain("Take it");190    expect(text).not.toContain(`${Brand.cli} claim`);191  });192193  it("says where a refused answer was refused, whose move it is and what to run", () => {194    const refusal = new OutOfScope({ paths: [RepoPath.make("README.md")] });195    const outcome = Outcome.cases.Refused.make({ refusals: [refusal] });196197    const states = askStates([198      claimedEvent(1, "tamsin"),199      judgedEvent(2, outcome),200    ]);201202    const text = textOf(203      page(204        { ...ask, state: "claimed" },205        { states, verdict: { ...verdictOf(outcome), stage: "shape" } }206      )207    );208209    expect(210      inOrder(text, [211        "Refused",212        "at Shape",213        "OutOfScope",214        "tamsin's move",215        refusal.next,216      ])217    ).toBeTruthy();218  });219220  it("says a landed ask landed, with its commit", () => {221    const states = askStates([222      claimedEvent(1, "tamsin"),223      judgedEvent(2, Outcome.cases.Landed.make({ sha: landedSha })),224      closedEvent(3),225    ]);226227    const markup = markupOf(page({ ...ask, state: "closed" }, { states }));228229    expect(textOf(page({ ...ask, state: "closed" }, { states }))).toContain(230      "Landed as 9b1c3e5"231    );232    expect(markup).toContain(`href="/oscabriel/datekit/commit/${landedSha}"`);233  });234235  it("gives a round the word its landing or verdict has since said, not the one it was judged with", () => {236    const states = askStates([237      claimedEvent(1, "tamsin"),238      judgedEvent(2, Outcome.cases.Checking.make({ stage: "human" })),239      closedEvent(3),240    ]);241242    const answers = plainText(243      mainOf(markupOf(page({ ...ask, state: "closed" }, { states })))244    );245246    expect(inOrder(answers, ["Round 1", "bbbbbbb", "Landed"])).toBeTruthy();247    expect(answers).not.toContain("Checking");248  });249250  it("lists one answer row per judged round, each linking its answer", () => {251    const states = askStates([252      claimedEvent(1, "tamsin"),253      judgedEvent(254        2,255        Outcome.cases.Refused.make({256          refusals: [new OutOfScope({ paths: [RepoPath.make("README.md")] })],257        }),258        CommitSha.make("e".repeat(40))259      ),260      judgedEvent(3, Outcome.cases.Checking.make({ stage: "checks" })),261    ]);262263    const main = mainOf(264      markupOf(page({ ...ask, state: "claimed" }, { states }))265    );266267    const rows = [268      ...main.matchAll(269        /href="\/oscabriel\/datekit\/answers\/parse-iso-week\?head=(?<head>[0-9a-f]+)"/gu270      ),271    ].map(({ groups }) => groups?.head);272273    expect(rows).toStrictEqual(["e".repeat(40), "b".repeat(40)]);274    expect(275      inOrder(plainText(main), [276        "Answers",277        "Round 1",278        "eeeeeee",279        "Refused",280        "Round 2",281        "bbbbbbb",282        "Checking",283      ])284    ).toBeTruthy();285  });286287  it("shows the check's source inline when it was read, its first 30 lines until asked for the whole", () => {288    const markup = mainOf(markupOf(page(ask, { check: checkSource(45) })));289    const text = plainText(markup);290291    expect(text).toContain('expect(parseWeek("2026-W41-29")).not.toBeNull();');292    expect(text).not.toContain(293      'expect(parseWeek("2026-W41-30")).not.toBeNull();'294    );295    expect(text).toContain("Show the whole check");296    expect(markup).toContain('data-code="plain"');297  });298299  it("shows only the check's path when its source could not be read", () => {300    const markup = mainOf(markupOf(page()));301302    expect(markup).not.toContain('data-code="plain"');303    expect(markup).toContain(304      'href="/oscabriel/datekit/blob/main/test/parse-week.test.ts"'305    );306  });307308  it("says a family's delete child waits for its siblings in the family's terms", () => {309    const { children, deleteChild, parent } = family;310    const states = askStates([closedEvent(1, children[0] ?? parent.id)]);311    const text = textOf(page(deleteChild, { parent, states }));312313    expect(text).toContain("Waiting for 2 of 3 children to land");314    expect(text).not.toContain("Waits on");315  });316317  it("says a delete child whose siblings all landed is open to take, and never that it waits", () => {318    const { children, deleteChild, parent } = family;319320    const states = askStates(321      children.map((child, index) => closedEvent(index + 1, child))322    );323324    const markup = markupOf(325      page({ ...deleteChild, state: "open" }, { parent, states })326    );327328    const text = textOf(329      page({ ...deleteChild, state: "open" }, { parent, states })330    );331332    expect(text).toContain("Open to take");333    expect(text).not.toContain("Waits on");334    expect(text).not.toContain("to land first");335    expect(mainOf(markup)).toContain(`data-family="${parent.id}"`);336  });337338  it("says a family's parent waits for its family in the family's terms, never as a list of ids", () => {339    const { children, deleteChild, parent } = family;340    const states = askStates([closedEvent(1, children[0] ?? parent.id)]);341    const markup = mainOf(markupOf(page(parent, { states })));342343    expect(plainText(markup)).toContain(344      "Waits for 2 of 3 children and the delete step to land first; a claim waits until they do."345    );346    expect(plainText(markup)).not.toContain("Waits on");347    expect(markup).toContain(348      `href="/oscabriel/datekit/asks/${deleteChild.id}"`349    );350  });351352  it("says a family's parent whose children all landed waits only for the delete step", () => {353    const { children, parent } = family;354355    const states = askStates(356      children.map((child, index) => closedEvent(index + 1, child))357    );358359    expect(plainText(mainOf(markupOf(page(parent, { states }))))).toContain(360      "Waits for the delete step to land first"361    );362  });363364  it("names the asks an ask outside a family waits on, each linking to its page", () => {365    const blocked = {366      ...ask,367      blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],368    };369370    const text = textOf(page(blocked));371    const markup = markupOf(page(blocked));372373    expect(374      inOrder(text, [375        "Waits on",376        "split-format",377        "split-parse",378        "to land first",379      ])380    ).toBeTruthy();381    expect(markup).toContain('href="/oscabriel/datekit/asks/split-format"');382    expect(markup).toContain('href="/oscabriel/datekit/asks/split-parse"');383  });384385  it("names nothing it waits on when nothing blocks it, or what blocked it landed", () => {386    expect(textOf(page())).not.toContain("Waits on");387388    const states = askStates([closedEvent(1, AskId.make("split-format"))]);389390    expect(391      textOf(392        page({ ...ask, blockedBy: [AskId.make("split-format")] }, { states })393      )394    ).not.toContain("Waits on");395  });396397  it("gives no claim line once the ask is closed", () => {398    const text = textOf(page({ ...ask, state: "closed" }));399400    expect(text).toContain("Closed");401    expect(text).not.toContain(`${Brand.cli} claim`);402  });403404  it("links to the ask's Markdown and to the verdict on its latest answer", () => {405    const markup = markupOf(page());406407    expect(markup).toContain(`href="/oscabriel/datekit/asks/${askId}.md"`);408    expect(markup).toContain(`href="/oscabriel/datekit/answers/${askId}"`);409  });410411  it("shows the brief exactly as an agent reads it", () => {412    expect(inPre(markupOf(page()))).toBe(inPre(markupOf(<pre>{brief}</pre>)));413  });414415  it("gives the project's posture when the list of projects has it", () => {416    const text = textOf(page(ask, { posture: "openWithSealedEvidence" }));417418    expect(text).toContain("Open with sealed evidence");419  });420});421422describe(NoSuchAsk, () => {423  it("shows the refusal a loader's not-found carried from the server, as git printed it", () => {424    const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });425426    // The not-found's data, as it crosses from the server: encoded, then cloned.427    const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));428429    expect(430      inOrder(textOf(<NoSuchAsk data={data} />), [431        "No such ask",432        ...explain([refusal]).map((line) => line.trim()),433        `${Brand.cli} asks`,434      ])435    ).toBeTruthy();436  });437438  it("says nothing is at an address that names no ask at all", () => {439    expect(textOf(<NoSuchAsk />)).toContain("Nothing is at this address");440  });441442  it("offers the way onward: the project, and the open asks", () => {443    const markup = markupOf(<NoSuchAsk project="datekit" />);444445    expect(markup).toContain('href="/oscabriel/datekit"');446    expect(markup).toContain('href="/asks"');447    expect(textOf(<NoSuchAsk project="datekit" />)).toContain("Open asks");448  });449450  it("names the project and its asks in the trail, and no crumb for the ask that is not there", () => {451    const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });452    const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));453454    const trail = trailOf(455      markupOf(<NoSuchAsk data={data} project="datekit" />)456    );457458    expect(inOrder(plainText(trail), ["datekit", "Asks"])).toBeTruthy();459    expect(trail).toContain('href="/oscabriel/datekit"');460    expect(trail).not.toContain("no-such-ask");461  });462463  it("links no project the platform says it does not have", () => {464    const refusal = new UnknownProject({465      project: ProjectName.make("oscabriel/nowhere"),466    });467468    const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));469    const markup = markupOf(<NoSuchAsk data={data} project="nowhere" />);470471    expect(markup).not.toContain('href="/nowhere"');472    expect(markup).toContain('href="/asks"');473  });474475  it("says what its route gives it when a not-found carries no refusal", () => {476    expect(477      textOf(<NoSuchAsk nothing="No answer is at this head." />)478    ).toContain("No answer is at this head.");479  });480});481482interface Asked {483  readonly asks: number;484  readonly files: number;485  readonly replays: number;486  readonly verdicts: number;487}488489const nothingAsked: Asked = { asks: 0, files: 0, replays: 0, verdicts: 0 };490491const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>492  Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));493494const replay = [495  claimedEvent(1, "tamsin"),496  claimedEvent(2, "okafor", AskId.make("format-week")),497];498499const platformOf = (500  asked: Ref.Ref<Asked>,501  {502    readable = true,503    shown = ask,504  }: { readonly readable?: boolean; readonly shown?: Ask } = {}505) =>506  Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(507    Layer.provide([508      Layer.mergeAll(509        unanswered,510        Contracts.toLayerHandler("showAsk", (payload) =>511          Effect.gen(function* () {512            yield* count(asked, "asks");513514            if (payload.ask === family.parent.id) {515              return { ask: family.parent, brief };516            }517518            if (payload.ask !== askId) {519              return yield* new UnknownAsk({ ask: payload.ask });520            }521522            return { ask: shown, brief };523          })524        ),525        Contracts.toLayerHandler("verdict", () =>526          Effect.as(count(asked, "verdicts"), {})527        ),528        Contracts.toLayerHandler("watch", () =>529          Stream.fromEffect(count(asked, "replays")).pipe(530            Stream.flatMap(() => Stream.fromIterable(replay))531          )532        ),533        Contracts.toLayerHandler("readFile", (payload) =>534          Effect.gen(function* () {535            yield* count(asked, "files");536537            if (!readable) {538              return yield* new UnknownPath({539                commit: CommitSha.make("a".repeat(40)),540                path: payload.path,541              });542            }543544            return {545              at: CommitSha.make("a".repeat(40)),546              binary: false,547              path: payload.path,548              sha: BlobSha.make("f".repeat(40)),549              size: 42,550              text: 'test("parses", () => {});',551              truncated: false,552            };553          })554        )555      ),556      asTester,557    ])558  );559560describe(readAsk, () => {561  it.effect(562    "reads the ask, its brief, its events and its check's source for the page",563    () =>564      Effect.gen(function* () {565        const asked = yield* Ref.make(nothingAsked);566567        const read = yield* readAsk({ ask: askId, project }).pipe(568          Effect.provide(platformOf(asked))569        );570571        expect({572          ask: read.ask.id,573          brief: read.brief,574          check: read.check?.text,575          events: read.events.map(({ seq }) => seq),576          lastSeq: read.lastSeq,577          parent: read.parent,578        }).toStrictEqual({579          ask: askId,580          brief,581          check: 'test("parses", () => {});',582          events: [1],583          lastSeq: 2,584          parent: undefined,585        });586        expect(yield* Ref.get(asked)).toStrictEqual({587          asks: 1,588          files: 1,589          replays: 1,590          verdicts: 1,591        });592      })593  );594595  it.effect(596    "reads a family member's parent, and shows the ask without its check's source when the file cannot be read",597    () =>598      Effect.gen(function* () {599        const asked = yield* Ref.make(nothingAsked);600601        const read = yield* readAsk({ ask: askId, project }).pipe(602          Effect.provide(603            platformOf(asked, {604              readable: false,605              shown: { ...family.child(0), check: ask.check, id: askId },606            })607          )608        );609610        expect(read.parent?.id).toBe(family.parent.id);611        expect(read.check).toBeUndefined();612        expect((yield* Ref.get(asked)).asks).toBe(2);613      })614  );615616  it.effect(617    "is a not-found carrying the UnknownAsk refusal for an ask the project lacks",618    () =>619      Effect.gen(function* () {620        const asked = yield* Ref.make(nothingAsked);621        const missing = AskId.make("no-such-ask");622623        const failed = yield* Effect.flip(624          readAsk({ ask: missing, project }).pipe(625            Effect.provide(platformOf(asked))626          )627        );628629        expect(isNotFound(failed)).toBeTruthy();630631        const carried = yield* Schema.decodeUnknownEffect(Refusals)(632          isNotFound(failed) ? failed.data : undefined633        );634635        expect(explain(carried)).toStrictEqual(636          explain([new UnknownAsk({ ask: missing })])637        );638      })639  );640641  it.effect(642    "is a not-found with no refusal, and asks nothing, for a name no ask can have",643    () =>644      Effect.gen(function* () {645        const asked = yield* Ref.make(nothingAsked);646647        const failed = yield* Effect.flip(648          readAsk({ ask: "Not_An-Ask", project }).pipe(649            Effect.provide(platformOf(asked))650          )651        );652653        expect(isNotFound(failed)).toBeTruthy();654        expect(655          isNotFound(failed) ? failed.data : "not a not-found"656        ).toBeUndefined();657        expect(yield* Ref.get(asked)).toStrictEqual(nothingAsked);658      })659  );660});