Add /home: a signed-in reader's claims, decisions waiting and asks to take
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parent 9000f4e · Browse files · 6 files·+565 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+565 added−8 removed
- tests:+132 added−0 removed
- other:+433 added−8 removed
Provenance
- Commit
b229cdb- Tree
8c4be6c- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
9000f4e
6 files changed+565 added−8 removed
modified:apps/web/src/features/docs/head.ts+1 added-2 removed
19 unmodified lines20212223242524252619 unmodified lines
/** The index's head. */export const docsIndexHead = () => pageHead({ description: "Guides for answering asks, running a project and connecting an agent, and a reference read from the platform's own schema.", description: "Guides, and a reference read from the platform's schema.", title: "Docs", });added:apps/web/src/features/home/home-page.tsx+310 added
1+/**2+ * A signed-in reader's own page: their claims, each with where its answer3+ * stands; the decisions waiting for them when they decide somewhere; the4+ * open asks they may take; and the way to their record. No score and no5+ * count of credit (DESIGN.md). Signed out, it says what the page is and how6+ * to sign in. A view: what the server read, and the instant, in; markup out.7+ */8+import { Brand } from "@repo/brand";9+import type { AnswerView } from "@repo/protocol/domain/answer";10+import type { ClaimState, ClaimView } from "@repo/protocol/domain/claim";11+import type { Today } from "@repo/protocol/domain/decision";12+import type { FrontPageEntry } from "@repo/protocol/domain/front-page";13+import { Outcome } from "@repo/protocol/domain/outcome";14+import type { Handle } from "@repo/protocol/ids";15+import { Array as Arr, DateTime } from "effect";16+17+import { signInHref } from "../auth/session-slot.tsx";18+import {19+ decisionHref,20+ describeSubject,21+ subjectKind,22+} from "../decision/subject.ts";23+import { CommandLine } from "../shared/command.tsx";24+import { EmptyState } from "../shared/empty.tsx";25+import { AppLink } from "../shared/link.tsx";26+import {27+ answerPath,28+ ASKS_PATH,29+ askPath,30+ HOME_PATH,31+ personPath,32+} from "../shared/paths.ts";33+import { UnreachableNotice } from "../shared/pending.tsx";34+import { AskRow, MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";35+import type { RowState } from "../shared/row.tsx";36+import { Workspace } from "../shared/shell/workspace.tsx";37+import { When } from "../shared/time.tsx";38+import { orderDecisions } from "../today/read.ts";39+import { HomeRead } from "./read.ts";40+41+/** What the page is, said to a reader who is not signed in. */42+const WHAT_HOME_IS =43+ "Home is your own page: the asks you hold and where each answer stands, the decisions waiting for you, and the asks you may take next.";44+45+/** The decisions the page lists; the rest are on Today. */46+const DECISIONS_SHOWN = 5;47+48+const LINK =49+ "decoration-rule hover:decoration-foreground font-medium underline underline-offset-4";50+51+/** A claim still running: its holder's to push to. */52+const running = (claim: ClaimView) =>53+ claim.state === "live" || claim.state === "warned";54+55+/** An answer's latest outcome as a row's state. */56+const outcomeState = (answer: AnswerView): RowState =>57+ Outcome.match(answer.outcome, {58+ AwaitingDecision: (): RowState => ({ mark: "waiting", word: "Waiting" }),59+ AwaitingFinish: (): RowState => ({ mark: "waiting", word: "Waiting" }),60+ Checking: (): RowState => ({ mark: "checking", word: "Checking" }),61+ Landed: (): RowState => ({ mark: "landed", word: "Landed" }),62+ Refused: (): RowState => ({ mark: "refused", word: "Refused" }),63+ WaitingOnParent: (): RowState => ({ mark: "waiting", word: "Waiting" }),64+ });65+66+/** A claim with no answer yet, as a row's state. */67+const CLAIM_STATES = {68+ answered: { mark: "passed", word: "Answered" },69+ lapsed: { mark: "notNeeded", word: "Lapsed" },70+ live: { mark: "claimed", word: "Claimed" },71+ released: { mark: "notNeeded", word: "Released" },72+ warned: { mark: "waiting", word: "Push soon" },73+} as const satisfies Record<ClaimState, RowState>;74+75+/**76+ * Each claim's latest answer. An answer names its ask but not its project,77+ * so it is matched only where one claim of the reader's holds that ask.78+ */79+const latestAnswers = (80+ claims: readonly ClaimView[],81+ answers: readonly AnswerView[]82+): ReadonlyMap<ClaimView, AnswerView> => {83+ const byAsk = Arr.groupBy(claims, ({ ask }) => ask);84+85+ return new Map(86+ claims.flatMap((claim) => {87+ if ((byAsk[claim.ask]?.length ?? 0) !== 1) {88+ return [];89+ }90+91+ const [latest] = answers92+ .filter(({ ask }) => ask === claim.ask)93+ .toSorted(94+ (a, b) => DateTime.toEpochMillis(b.at) - DateTime.toEpochMillis(a.at)95+ );96+97+ return latest === undefined ? [] : [[claim, latest] as const];98+ })99+ );100+};101+102+/** Running claims first, then the newest. */103+const claimOrder = (a: ClaimView, b: ClaimView) =>104+ Number(running(b)) - Number(running(a)) ||105+ DateTime.toEpochMillis(b.openedAt) - DateTime.toEpochMillis(a.openedAt);106+107+const ClaimRows = ({108+ answers,109+ claims,110+ now,111+}: {112+ readonly answers: readonly AnswerView[];113+ readonly claims: readonly ClaimView[];114+ readonly now: DateTime.Utc;115+}) => {116+ const latest = latestAnswers(claims, answers);117+118+ return (119+ <RowGroup120+ counts={`${claims.filter(running).length} running`}121+ label="Your claims"122+ name="Your claims"123+ under="bar"124+ >125+ {claims.toSorted(claimOrder).map((claim) => {126+ const answer = latest.get(claim);127+128+ return (129+ <Row130+ data={{131+ "data-claim": claim.ask,132+ "data-project": claim.project,133+ "data-state": claim.state,134+ }}135+ href={136+ answer === undefined137+ ? askPath(claim.project, claim.ask)138+ : answerPath(claim.project, claim.ask)139+ }140+ id={`${claim.project}/${claim.ask}`}141+ key={`${claim.project}/${claim.ask}`}142+ meta={143+ <MetaLine144+ parts={[145+ claim.project,146+ <MetaCode key="fork">{claim.fork}</MetaCode>,147+ running(claim) ? (148+ <span key="lapses">149+ lapses <When at={claim.lapsesAt} now={now} />150+ </span>151+ ) : undefined,152+ ]}153+ />154+ }155+ mono156+ state={157+ answer === undefined158+ ? CLAIM_STATES[claim.state]159+ : outcomeState(answer)160+ }161+ title={claim.ask}162+ />163+ );164+ })}165+ </RowGroup>166+ );167+};168+169+const DecisionRows = ({ today }: { readonly today: Today }) => {170+ const waiting = today.decisions.length + today.overflow;171+172+ return (173+ <RowGroup174+ counts={`${waiting} waiting`}175+ label="Decisions waiting"176+ name={<AppLink to="/today">Decisions waiting</AppLink>}177+ under="bar"178+ >179+ {orderDecisions(today)180+ .slice(0, DECISIONS_SHOWN)181+ .map((decision) => (182+ <Row183+ data={{184+ "data-decision": decision.id,185+ "data-project": decision.project,186+ }}187+ href={decisionHref(decision)}188+ id={`${decision.project}/${decision.id}`}189+ key={`${decision.project}/${decision.id}`}190+ meta={191+ <MetaLine192+ parts={[193+ decision.project,194+ subjectKind(decision.subject),195+ <MetaCode key="id">{decision.id}</MetaCode>,196+ ]}197+ />198+ }199+ state={{ mark: "now", word: "Yours to decide" }}200+ title={describeSubject(decision.subject)}201+ />202+ ))}203+ </RowGroup>204+ );205+};206+207+const AskRows = ({ asks }: { readonly asks: readonly FrontPageEntry[] }) => (208+ <RowGroup209+ label="Asks you may take"210+ name={<AppLink to={ASKS_PATH}>Asks you may take</AppLink>}211+ under="bar"212+ >213+ {asks.map(({ ask, project }) => (214+ <AskRow215+ key={`${project}/${ask.ask}`}216+ listing={ask}217+ project={project}218+ showProject219+ takeable220+ />221+ ))}222+ </RowGroup>223+);224+225+/** The way to the reader's record. */226+const Record = ({ handle }: { readonly handle: Handle }) => (227+ <>228+ Signed in as {handle}.{" "}229+ <AppLink className={LINK} to={personPath(handle)}>230+ Your record231+ </AppLink>232+ </>233+);234+235+const Signed = ({236+ read,237+ now,238+}: {239+ readonly read: typeof HomeRead.cases.Read.Type;240+ readonly now: DateTime.Utc;241+}) => (242+ <Workspace243+ crumbs={[{ label: "Home" }]}244+ meta={<Record handle={read.handle} />}245+ title="Home"246+ variant="list"247+ >248+ <div className="flex flex-col gap-8">249+ {read.claims.length === 0 ? (250+ <EmptyState251+ command={`${Brand.cli} front`}252+ onward={253+ <AppLink className={LINK} to={ASKS_PATH}>254+ The open asks255+ </AppLink>256+ }257+ title="You hold no claim. Find an ask to take, then claim it."258+ />259+ ) : (260+ <ClaimRows answers={read.answers} claims={read.claims} now={now} />261+ )}262+ {read.today === undefined ? null : <DecisionRows today={read.today} />}263+ {read.asks.length === 0 ? (264+ <EmptyState265+ onward={266+ <AppLink className={LINK} to={ASKS_PATH}>267+ Every open ask268+ </AppLink>269+ }270+ title="No open ask is yours to take right now."271+ />272+ ) : (273+ <AskRows asks={read.asks} />274+ )}275+ </div>276+ </Workspace>277+);278+279+/** Signed out: what the page is, the way in, and the command. */280+const SignedOut = () => (281+ <Workspace crumbs={[{ label: "Home" }]} title="Home">282+ <div className="flex max-w-[70ch] flex-col items-start gap-3">283+ <p className="text-body">{WHAT_HOME_IS}</p>284+ <p className="text-ui">285+ <a className={LINK} href={signInHref(HOME_PATH)}>286+ Sign in287+ </a>{" "}288+ to see yours, or read it from a terminal:289+ </p>290+ <CommandLine command={`${Brand.cli} status`} />291+ </div>292+ </Workspace>293+);294+295+export const HomeView = ({296+ now,297+ read,298+}: {299+ readonly now: DateTime.Utc;300+ readonly read: HomeRead;301+}) =>302+ HomeRead.match(read, {303+ Read: (signed) => <Signed now={now} read={signed} />,304+ SignedOut: () => <SignedOut />,305+ Unreachable: () => (306+ <Workspace crumbs={[{ label: "Home" }]} title="Home">307+ <UnreachableNotice />308+ </Workspace>309+ ),310+ });added:apps/web/src/features/home/read.ts+92 added
1+/**2+ * What `/home` reads, in a module with no view of its own: a route's loader3+ * runs before its page's view loads.4+ *5+ * - `HomeRead`: the reader's claims and answers (`status`), their Today when6+ * they decide somewhere, the open asks they may take (`frontPage`, read7+ * as them), or why there is none of it.8+ * - `readHome`: that read, made with whatever `Client` the caller gives9+ * (the server's, carrying the reader's own session).10+ */11+import { Client } from "@repo/protocol/contracts";12+import { AnswerView } from "@repo/protocol/domain/answer";13+import { ClaimView } from "@repo/protocol/domain/claim";14+import { Today } from "@repo/protocol/domain/decision";15+import { FrontPageEntry } from "@repo/protocol/domain/front-page";16+import { Handle } from "@repo/protocol/ids";17+import { Unauthenticated } from "@repo/protocol/principal";18+import { Cause, DateTime, Effect, Exit, Option, Schema } from "effect";19+20+/** The asks the page lists: the first few the reader may take; the rest are at `/asks`. */21+const ASKS_SHOWN = 8;22+23+/** What the page read for its reader: their work, or why there is none. */24+export const HomeRead = Schema.TaggedUnion({25+ Read: {26+ answers: Schema.Array(AnswerView),27+ asks: Schema.Array(FrontPageEntry),28+ claims: Schema.Array(ClaimView),29+ handle: Handle,30+ /** Absent for a reader who decides nowhere, or whose Today did not come. */31+ today: Schema.optionalKey(Today),32+ },33+ SignedOut: {},34+ Unreachable: {},35+});36+37+export type HomeRead = typeof HomeRead.Type;38+39+/** What the loader sends: the read, and the instant it was made. */40+export const HomePageData = Schema.Struct({41+ now: Schema.DateTimeUtcFromString,42+ read: HomeRead,43+});44+45+export type HomePageData = typeof HomePageData.Type;46+47+const isUnauthenticated = Schema.is(Unauthenticated);48+49+/** A failed `status`, as the page says it: signed out, or the platform did not answer. */50+const readOfCause = (cause: Cause.Cause<unknown>): HomeRead =>51+ Option.exists(Cause.findErrorOption(cause), isUnauthenticated)52+ ? HomeRead.cases.SignedOut.make({})53+ : HomeRead.cases.Unreachable.make({});54+55+/** The reader's home, or why there is none, encoded for the page. */56+export const readHome = Effect.gen(function* () {57+ const client = yield* Client;58+59+ const [status, today, front] = yield* Effect.all(60+ [61+ Effect.exit(client.status({})),62+ // A reader who decides nowhere has no Today: the block is left out.63+ Effect.option(client.today({})),64+ Effect.option(client.frontPage({})),65+ ],66+ { concurrency: "unbounded" }67+ );68+69+ const read = Exit.match(status, {70+ onFailure: readOfCause,71+ onSuccess: ({ answers, claims, handle }) =>72+ HomeRead.cases.Read.make({73+ answers,74+ asks: Option.match(front, {75+ onNone: () => [],76+ onSome: ({ entries }) =>77+ entries.filter(({ takeable }) => takeable).slice(0, ASKS_SHOWN),78+ }),79+ claims,80+ handle,81+ ...Option.match(today, {82+ onNone: () => ({}),83+ onSome: (decisions) => ({ today: decisions }),84+ }),85+ }),86+ });87+88+ return yield* Schema.encodeEffect(HomePageData)({89+ now: yield* DateTime.now,90+ read,91+ });92+});modified:apps/web/src/routes/home.tsx+30 added-6 removed
12345678941011121378141516171810192021222324252627282930313233341314353637383940import { createFileRoute } from "@tanstack/react-router";import { createServerFn } from "@tanstack/react-start";import { getRequest } from "@tanstack/react-start/server";import { env } from "cloudflare:workers";import { Effect, Schema } from "effect";
import { HomeView } from "../features/home/home-page.tsx";import { HomePageData, readHome } from "../features/home/read.ts";import { pageHead } from "../features/shared/head.ts";import { Workspace } from "../features/shared/shell/workspace.tsx";import { reloadOnEnter } from "../features/shared/shell/selection.ts";import { personalPage } from "../server/cache-headers.ts";import { serverClient } from "../server/client.ts";
// `/home`: a signed-in reader's own page, where the landing sends them. A// page about its reader is kept by no cache.// `/home`: the signed-in reader's own page, where the landing sends them.// The loader reads it on the server with the reader's own session (their// cookie goes with the call), so the page arrives with its rows. A page// about its reader is kept by no cache.
const HomePage = () => <Workspace title="Home">{null}</Workspace>;/** A page about its reader, kept by no cache. */export const homeHeaders = () => personalPage;
const homePage = createServerFn({ method: "GET" }).handler(() => Effect.runPromise( readHome.pipe(Effect.provide(serverClient(env, getRequest()))) ));
const HomePage = () => { const data = Schema.decodeSync(HomePageData)(Route.useLoaderData());
return <HomeView now={data.now} read={data.read} />;};
export const Route = createFileRoute("/home")({ component: HomePage, headers: () => personalPage, loader: () => homePage(), shouldReload: reloadOnEnter, headers: homeHeaders, head: () => pageHead({ title: "Home" }), component: HomePage,});modified:apps/web/test/edge-cache.test.ts+1 added
457 unmodified lines458 );459 460 expect(reading.toSorted()).toStrictEqual([461 "../src/routes/$project/decisions/$decision.tsx",462+ "../src/routes/home.tsx",463 "../src/routes/today.tsx",464 ]);465 466 for (const path of reading) {24 unmodified linesadded:apps/web/test/home.test.tsx+131 added
1+/**2+ * `/home`, a signed-in reader's own page, read on the server with their3+ * session from the dev world and its fixtures: their claims with where each4+ * answer stands, the decisions waiting when they decide somewhere, the asks5+ * they may take, and their record. Signed out, it says what the page is6+ * and how to sign in. A page about its reader, kept by no cache.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+import { Client, Contracts } from "@repo/protocol/contracts";11+import { Handle } from "@repo/protocol/ids";12+import { Effect, Layer, Schema } from "effect";13+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";14+import { RpcClient, RpcSerialization } from "effect/rpc";15+16+import { devServer } from "../src/dev/server.ts";17+import { devToken } from "../src/dev/sessions.ts";18+import { HomeView } from "../src/features/home/home-page.tsx";19+import { HomePageData, readHome } from "../src/features/home/read.ts";20+import { homeHeaders, Route } from "../src/routes/home.tsx";21+import { renderAt } from "./render.tsx";22+23+/** A `Client` of a fresh dev world with its fixtures, signed in as `handle` (or as nobody). */24+const fixturesClient = (handle?: string) =>25+ Layer.unwrap(26+ Effect.gen(function* () {27+ const { dispose, handler } = devServer({ fixtures: "on" });28+29+ yield* Effect.addFinalizer(() => Effect.promise(dispose));30+31+ return Layer.effect(Client)(RpcClient.make(Contracts)).pipe(32+ Layer.provide(33+ RpcClient.layerProtocolHttp({34+ transformClient: HttpClient.mapRequest((request) =>35+ handle === undefined36+ ? request37+ : HttpClientRequest.bearerToken(38+ request,39+ devToken(Handle.make(handle))40+ )41+ ),42+ url: "http://localhost/rpc",43+ })44+ ),45+ Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),46+ Layer.provide(47+ Layer.succeed(FetchHttpClient.Fetch, (input, init) =>48+ handler(new Request(input, init))49+ )50+ )51+ );52+ })53+ );54+55+/** The page as the route renders it from what `readHome` sent. */56+const pageFrom = (encoded: typeof HomePageData.Encoded) =>57+ Effect.gen(function* () {58+ const data = yield* Schema.decodeEffect(HomePageData)(encoded);59+60+ return yield* renderAt(61+ "/home",62+ <HomeView now={data.now} read={data.read} />63+ );64+ });65+66+const textIn = (markup: string) =>67+ markup68+ .replaceAll(/<[^>]+>/gu, " ")69+ .replaceAll("'", "'")70+ .replaceAll(/\s+/gu, " ")71+ .trim();72+73+/** The sections' names, in order. */74+const sectionsOf = (markup: string) =>75+ [...markup.matchAll(/<section\b[^>]*aria-label="(?<name>[^"]+)"/gu)].map(76+ (found) => found.groups?.name77+ );78+79+describe("home, read on the server with the reader's session", () => {80+ it.live(81+ "gives a contributor their claims, the asks they may take and their record, and no decisions",82+ () =>83+ Effect.gen(function* () {84+ const markup = yield* pageFrom(yield* readHome);85+86+ expect(sectionsOf(markup)).toStrictEqual([87+ "Your claims",88+ "Asks you may take",89+ ]);90+ expect(markup).toMatch(/data-claim="[^"]+"[^>]*data-project="vellum"/u);91+ expect(markup).toContain('href="/people/bram"');92+ expect(markup).toContain('href="/asks"');93+ }).pipe(Effect.provide(fixturesClient("bram")), Effect.scoped),94+ 60_00095+ );96+97+ it.live(98+ "gives a decider the decisions waiting for them, each linking its page, and Today",99+ () =>100+ Effect.gen(function* () {101+ const markup = yield* pageFrom(yield* readHome);102+103+ expect(sectionsOf(markup)).toContain("Decisions waiting");104+ expect(markup).toMatch(/href="\/[a-z-]+\/decisions\/[^"]+"/u);105+ expect(markup).toContain('href="/today"');106+ }).pipe(Effect.provide(fixturesClient("ines-v")), Effect.scoped),107+ 60_000108+ );109+110+ it.live(111+ "signed out, says what the page is, how to sign in and come back, and the command",112+ () =>113+ Effect.gen(function* () {114+ const markup = yield* pageFrom(yield* readHome);115+116+ expect(textIn(markup)).toContain(`${Brand.cli} status`);117+ expect(markup).toContain(118+ `href="/auth/signin?return=${encodeURIComponent("/home")}"`119+ );120+ expect(sectionsOf(markup)).toStrictEqual([]);121+ }).pipe(Effect.provide(fixturesClient()), Effect.scoped),122+ 60_000123+ );124+125+ it("is kept by no cache: its response is private and never stored", () => {126+ expect(Route.options.headers).toBe(homeHeaders);127+ expect(homeHeaders()).toStrictEqual({128+ "Cache-Control": "private, no-store",129+ });130+ });131+});