Skip to content
Myr

today.test.ts

This file

Path

apps/cli/test/tui/today.test.ts

688 lines · 21.4 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { createTestRenderer } from "@opentui/core/testing";4import { createElement } from "@opentui/react";5import { testRender } from "@opentui/react/test-utils";6import { Brand } from "@repo/brand";7import { toCommand } from "@repo/protocol/cli";8import { Client, Contracts, TodayOf } from "@repo/protocol/contracts";9import type { Decide } from "@repo/protocol/contracts";10import { DecisionClosed, NotDecider } from "@repo/protocol/refusal";11import { explain } from "@repo/protocol/render";12import { asTester, unanswered } from "@repo/protocol/testing";13import {14  ConfigProvider,15  DateTime,16  Effect,17  Exit,18  Layer,19  Option,20  Ref,21  Schema,22  Stdio,23} from "effect";24import { Command } from "effect/cli";25import { RpcTest } from "effect/rpc";26import { TestConsole } from "effect/testing";2728import { Output, OutputLive } from "../../src/output.ts";29import { policyFor } from "../../src/policy.ts";30import type { Policy } from "../../src/policy.ts";31import { refusalsIn, views } from "../../src/render.ts";32import { today as todayCommand } from "../../src/tui/command.ts";33import { OpenScreen, runTodayTui, TuiRefused } from "../../src/tui/run.ts";34import type { Screen } from "../../src/tui/run.ts";35import { screenOn } from "../../src/tui/screen.ts";36import { reduce, start } from "../../src/tui/today.ts";37import type { DecideCall, TodayViewState } from "../../src/tui/today.ts";38import { TodayView } from "../../src/tui/view.ts";39import { runProgram } from "../remote-server.ts";40import { datekit, okonkwo, proposal, stray, today, vouch } from "./fixture.ts";4142const press = (state: TodayViewState, keys: readonly string[]) => {43  const calls: DecideCall[] = [];44  let now = state;4546  for (const key of keys) {47    const step = reduce(now, key);4849    calls.push(...Option.toArray(step.call));50    now = step.state;51  }5253  return { calls, state: now };54};5556describe("the keys a maintainer presses on Today", () => {57  it("declines the second decision with d, its default, at once", () => {58    const { calls } = press(start(today), ["down", "d"]);5960    expect(calls).toStrictEqual([61      { choice: "decline", decision: vouch.id, project: datekit },62    ]);63  });6465  it("asks before a choice other than the default, and sends it on y", () => {66    const asked = press(start(today), ["down", "a"]);6768    expect([asked.calls, asked.state.confirming]).toStrictEqual([69      [],70      Option.some({ choice: "accept", decision: vouch.id, project: datekit }),71    ]);7273    expect(press(asked.state, ["y"]).calls).toStrictEqual([74      { choice: "accept", decision: vouch.id, project: datekit },75    ]);76  });7778  it("keeps the decision open when the maintainer says n, or moves on", () => {79    const asked = press(start(today), ["down", "a"]).state;8081    expect(press(asked, ["n", "y"]).calls).toStrictEqual([]);82    expect(press(asked, ["up", "y"])).toStrictEqual({83      calls: [],84      state: { ...asked, confirming: Option.none(), cursor: 0 },85    });86  });8788  it("offers a stray push its own choices: r reverts at once, a adopts after y, d does nothing", () => {89    expect(press(start(today), ["d", "r"]).calls).toStrictEqual([90      { choice: "revert", decision: stray.id, project: datekit },91    ]);9293    const adopting = press(start(today), ["a"]);94    const adopt = { choice: "adopt", decision: stray.id, project: datekit };9596    expect([adopting.calls, adopting.state.confirming]).toStrictEqual([97      [],98      Option.some(adopt),99    ]);100    expect(press(adopting.state, ["y"]).calls).toStrictEqual([adopt]);101  });102103  it("keeps the cursor on Today's decisions, and closes on q", () => {104    const { state } = press(start(today), ["down", "down", "down"]);105106    expect([107      press(start(today), ["up"]).state.cursor,108      state.cursor,109    ]).toStrictEqual([0, 2]);110    expect(reduce(state, "q").quit).toBeTruthy();111    expect(reduce(state, "down").quit).toBeFalsy();112  });113});114115const screenOf = (state: TodayViewState, height = 40) =>116  Effect.acquireUseRelease(117    Effect.promise(() =>118      testRender(createElement(TodayView, { state }), { height, width: 120 })119    ),120    (setup) =>121      Effect.promise(() => setup.renderOnce()).pipe(122        Effect.map(() =>123          setup124            .captureCharFrame()125            .split("\n")126            .map((row) => row.trimEnd())127        )128      ),129    (setup) =>130      Effect.sync(() => {131        setup.renderer.destroy();132      })133  );134135const rowsWith = (rows: readonly string[], text: string) =>136  rows.filter((row) => row.includes(text));137138describe("Today as the terminal shows it", () => {139  it.live("says whose Today it is and how much of the budget is used", () =>140    Effect.gen(function* () {141      const rows = yield* screenOf(start(today));142143      expect(rowsWith(rows, "Today for okonkwo")).toHaveLength(1);144      expect(rowsWith(rows, "Budget: 2 of 5 decisions used")).toStrictEqual([145        "Budget: 2 of 5 decisions used, 3 left today · 1 finish, counted apart",146      ]);147      expect(rowsWith(rows, "1 more waits for tomorrow")).toHaveLength(1);148    })149  );150151  it.live("lists the decisions in expiry order, the cursor on the first", () =>152    Effect.gen(function* () {153      const rows = yield* screenOf(start(today));154155      // A decision's first row: the cursor's mark, then its project and id.156      const listed = rows.flatMap((row) => {157        const found =158          /^(?<mark>[> ]) {1,3}(?:! )?oscabriel\/datekit\/(?<id>dec-\d+) /u.exec(159            row160          )?.groups;161162        return found === undefined ? [] : [`${found.mark}${found.id}`];163      });164165      expect(listed).toStrictEqual([166        ">dec-000002",167        " dec-000003",168        " dec-000001",169      ]);170    })171  );172173  it.live(174    "marks each decision's default, and the one expiring within the day",175    () =>176      Effect.gen(function* () {177        const rows = yield* screenOf(start(today));178179        const defaults = rows.flatMap(180          (row) =>181            /if nobody decides: (?<choice>\w+)/u.exec(row)?.groups?.choice ?? []182        );183184        expect(defaults).toStrictEqual(["revert", "decline", "accept"]);185        expect(186          rows187            .filter((row) => row.includes("if nobody decides:"))188            .map((row) => row.includes("within the day"))189        ).toStrictEqual([true, false, false]);190        expect(rowsWith(rows, "! oscabriel/datekit/")).toHaveLength(1);191      })192  );193194  it.live("shows each decision's evidence and the newcomers to welcome", () =>195    Effect.gen(function* () {196      const rows = yield* screenOf(start(today));197198      expect(199        rowsWith(rows, "pushed by: a token outside the platform")200      ).toHaveLength(1);201      expect(rowsWith(rows, "Newcomers to welcome: ada, grace")).toHaveLength(202        1203      );204    })205  );206207  it.live(208    "keeps the decision under the cursor on a short terminal, counting those above it",209    () =>210      Effect.gen(function* () {211        const rows = yield* screenOf(212          press(start(today), ["down", "down"]).state,213          12214        );215216        expect(rows.filter((row) => row.startsWith(">"))).toStrictEqual([217          ">   oscabriel/datekit/dec-000001  open the ask prop-000001 proposes",218        ]);219        expect(rowsWith(rows, "above")).toStrictEqual([220          "2 decisions above; up to read them",221        ]);222      })223  );224225  it.live(226    "names the keys the decision under the cursor takes, and asks before a non-default",227    () =>228      Effect.gen(function* () {229        const first = yield* screenOf(start(today));230231        expect(rowsWith(first, "a adopt")).toStrictEqual([232          "up/down move · a adopt · r revert · q quit",233        ]);234235        const asking = yield* screenOf(236          press(start(today), ["down", "a"]).state237        );238239        expect(240          rowsWith(asking, "Accept oscabriel/datekit/dec-000003?")241        ).toStrictEqual([242          "Accept oscabriel/datekit/dec-000003? Its default is decline. y to send it, n to keep it open.",243        ]);244      })245  );246});247248const surroundings = (input: {249  readonly env: Readonly<Record<string, string>>;250  readonly stdoutIsTTY: boolean;251  readonly stdinIsTTY: boolean;252}) =>253  Layer.mergeAll(254    policyFor({ env: input.env, isTTY: input.stdoutIsTTY }),255    Stdio.layerTest({ stdinIsTerminal: Effect.succeed(input.stdinIsTTY) }),256    Layer.mock(Client)({})257  );258259const refusalIn = (layer: ReturnType<typeof surroundings>) =>260  runTodayTui({ project: Option.none() }).pipe(261    Effect.flip,262    Effect.map((failure) =>263      Schema.is(TuiRefused)(failure)264        ? { message: failure.message, next: failure.next }265        : failure266    ),267    Effect.provide(layer)268  );269270describe("who may open Today full-screen", () => {271  it.effect(272    "refuses an agent, before calling the platform, and points to today --json",273    () =>274      Effect.gen(function* () {275        const refused = yield* refusalIn(276          surroundings({277            env: { CLAUDECODE: "1" },278            stdinIsTTY: true,279            stdoutIsTTY: true,280          })281        );282283        expect(refused).toStrictEqual({284          message: `${Brand.cli} today --tui needs a person at a terminal, but the env names the harness claude-code: run ${Brand.cli} today --json instead`,285          next: `${Brand.cli} today --json`,286        });287      })288  );289290  it.effect.each([291    {292      reason: "stdout is not a terminal",293      stdinIsTTY: true,294      stdoutIsTTY: false,295    },296    { reason: "stdin is not a terminal", stdinIsTTY: false, stdoutIsTTY: true },297  ])("refuses when $reason", ({ reason, stdinIsTTY, stdoutIsTTY }) =>298    Effect.gen(function* () {299      const refused = yield* refusalIn(300        surroundings({ env: {}, stdinIsTTY, stdoutIsTTY })301      );302303      expect(refused).toStrictEqual({304        message: `${Brand.cli} today --tui needs a person at a terminal, but ${reason}: run ${Brand.cli} today --json instead`,305        next: `${Brand.cli} today --json`,306      });307    })308  );309});310311describe("Today full-screen with no policy given", () => {312  it.effect(313    "reads the process's own, as the CLI's tree runs it: an agent's env refuses",314    () =>315      Effect.gen(function* () {316        const exit = yield* Effect.exit(317          runTodayTui({ project: Option.none() }).pipe(318            Effect.provide(319              Layer.mergeAll(320                ConfigProvider.layer(321                  ConfigProvider.fromEnv({ env: { CLAUDECODE: "1" } })322                ),323                Stdio.layerTest({324                  stdinIsTerminal: Effect.succeed(true),325                  stdoutIsTerminal: Effect.succeed(true),326                }),327                Layer.mock(Client)({})328              )329            )330          )331        );332333        expect(334          Option.map(Exit.findErrorOption(exit), (failed) =>335            Schema.is(TuiRefused)(failed) ? failed.reason : failed336          )337        ).toStrictEqual(Option.some("the env names the harness claude-code"));338      })339  );340});341342// Every key is pressed before any is read, so `forget` drops each one not read yet.343const scripted = (keys: readonly string[]) =>344  Effect.gen(function* () {345    const left = yield* Ref.make(keys);346    const shown = yield* Ref.make<readonly TodayViewState[]>([]);347348    const screen: Screen = {349      forget: Ref.set(left, []),350      key: Ref.modify(left, ([next = "q", ...rest]) => [next, rest]),351      show: (state) => Ref.update(shown, (all) => [...all, state]),352    };353354    return { screen, shown };355  });356357const platform = (closed: ReadonlySet<string>) =>358  Effect.gen(function* () {359    const decided = yield* Ref.make<360      readonly (typeof Decide.payloadSchema.Type)[]361    >([]);362363    const handlers = Layer.mergeAll(364      unanswered,365      Contracts.toLayerHandler("today", () =>366        Effect.map(Ref.get(decided), (calls) => ({367          ...today,368          decisions: today.decisions.filter(369            ({ id }) => !calls.some(({ decision }) => decision === id)370          ),371        }))372      ),373      Contracts.toLayerHandler("decide", (payload) =>374        closed.has(payload.decision)375          ? Effect.fail(new DecisionClosed({ decision: payload.decision }))376          : Effect.gen(function* () {377              yield* Ref.update(decided, (all) => [...all, payload]);378379              const decision =380                today.decisions.find(({ id }) => id === payload.decision) ??381                vouch;382383              return {384                decision: {385                  ...decision,386                  decided: {387                    at: DateTime.makeUnsafe("2026-10-08T08:00:00Z"),388                    by: okonkwo,389                    choice: payload.choice,390                  },391                },392              };393            })394      )395    );396397    const client = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(398      Layer.provide([handlers, asTester])399    );400401    return { client, decided };402  });403404const atTerminal =405  (client: Layer.Layer<Client>, screen: Screen) =>406  <A, E>(effect: Effect.Effect<A, E, Client | Policy | Stdio.Stdio>) =>407    effect.pipe(408      Effect.provideService(OpenScreen, Effect.succeed(screen)),409      Effect.provide(410        Layer.mergeAll(411          policyFor({ env: {}, isTTY: true }),412          Stdio.layerTest({ stdinIsTerminal: Effect.succeed(true) }),413          client414        )415      )416    );417418const ids = (state: TodayViewState | undefined) =>419  state?.today.decisions.map(({ id }) => id);420421describe("Today full-screen, worked by a maintainer", () => {422  it.effect(423    "sends d on the second decision as a decline, then shows Today without it",424    () =>425      Effect.gen(function* () {426        const { client, decided } = yield* platform(new Set());427        const { screen, shown } = yield* scripted(["down", "d"]);428429        yield* atTerminal(430          client,431          screen432        )(runTodayTui({ project: Option.none() }));433434        const states = yield* Ref.get(shown);435        const last = states.at(-1);436437        expect(yield* Ref.get(decided)).toStrictEqual([438          { choice: "decline", decision: vouch.id, project: datekit },439        ]);440        expect(states.map(({ notice }) => notice)).toContainEqual([441          "Sending decline on oscabriel/datekit/dec-000003…",442        ]);443        expect([last?.notice, ids(last), last?.cursor]).toStrictEqual([444          ["Decided: decline on oscabriel/datekit/dec-000003"],445          [proposal.id, stray.id],446          1,447        ]);448      })449  );450451  it.effect(452    "drops the keys pressed while a choice was on its way, so a second press decides nothing",453    () =>454      Effect.gen(function* () {455        const { client, decided } = yield* platform(new Set());456457        // y accepts the vouch; the second a would accept the proposal that458        // takes its place, at once, since accept is the proposal's default.459        const { screen } = yield* scripted(["down", "a", "y", "a"]);460461        yield* atTerminal(462          client,463          screen464        )(runTodayTui({ project: Option.none() }));465466        expect(yield* Ref.get(decided)).toStrictEqual([467          { choice: "accept", decision: vouch.id, project: datekit },468        ]);469      })470  );471472  it.effect(473    "shows a refused choice in the renderer's words, and keeps Today as it was",474    () =>475      Effect.gen(function* () {476        const { client } = yield* platform(new Set([stray.id]));477        const { screen, shown } = yield* scripted(["r"]);478479        yield* atTerminal(480          client,481          screen482        )(runTodayTui({ project: Option.none() }));483484        const last = (yield* Ref.get(shown)).at(-1);485486        expect([last?.notice, ids(last)]).toStrictEqual([487          explain([new DecisionClosed({ decision: stray.id })]),488          today.decisions.map(({ id }) => id),489        ]);490      })491  );492});493494describe("the terminal Today is drawn on", () => {495  it.live("draws each state in place of the last, and reads keys by name", () =>496    Effect.scoped(497      Effect.gen(function* () {498        const setup = yield* Effect.acquireRelease(499          Effect.promise(() => createTestRenderer({ height: 40, width: 120 })),500          ({ renderer }) =>501            Effect.sync(() => {502              renderer.destroy();503            })504        );505506        const screen = yield* screenOn(setup.renderer);507508        const drawn = (state: TodayViewState) =>509          Effect.gen(function* () {510            yield* screen.show(state);511            yield* Effect.promise(() => setup.renderOnce());512513            return setup.captureCharFrame().split("\n");514          });515516        yield* drawn(start(today));517        const moved = yield* drawn(press(start(today), ["down"]).state);518519        expect(rowsWith(moved, "Today for okonkwo")).toHaveLength(1);520        expect(rowsWith(moved, "> ").map((row) => row.trim())).toStrictEqual([521          ">   oscabriel/datekit/dec-000003  vouch for ada",522        ]);523524        setup.mockInput.pressArrow("down");525        setup.mockInput.pressKey("d");526        setup.mockInput.pressKey("c", { ctrl: true });527528        expect([529          yield* screen.key,530          yield* screen.key,531          yield* screen.key,532        ]).toStrictEqual(["down", "d", "ctrl+c"]);533534        setup.mockInput.pressKey("a");535        yield* screen.forget;536        setup.mockInput.pressKey("q");537538        expect(yield* screen.key).toBe("q");539      })540    )541  );542});543544const lines = (chunks: readonly unknown[]) =>545  chunks.flatMap((chunk) => String(chunk).split("\n"));546547const projectedToday = toCommand(TodayOf, Effect.service(Client), {548  output: Effect.service(Output),549  refusalsIn,550  render: views.today,551});552553const runToday = (554  args: readonly string[],555  input: {556    readonly client: Layer.Layer<Client>;557    readonly command?: typeof projectedToday;558    readonly env: Readonly<Record<string, string>>;559  }560) => {561  const policy = policyFor({ env: input.env, isTTY: true });562563  return Effect.gen(function* () {564    const exit: Exit.Exit<void, unknown> = yield* input.command === undefined565      ? Effect.exit(Command.runWith(todayCommand, { version: "0.0.0" })(args))566      : Effect.exit(Command.runWith(input.command, { version: "0.0.0" })(args));567568    return {569      err: lines(yield* TestConsole.errorLines),570      exit,571      out: lines(yield* TestConsole.logLines),572    };573  }).pipe(574    Effect.provideService(OpenScreen, Effect.die("no screen opens here")),575    Effect.provide(576      Layer.mergeAll(577        NodeServices.layer,578        // Its own console: a layer built twice in one memo map is shared.579        Layer.fresh(TestConsole.layer),580        input.client,581        policy,582        OutputLive.pipe(Layer.provide(policy)),583        Stdio.layerTest({ stdinIsTerminal: Effect.succeed(true) })584      )585    )586  );587};588589describe("the today command, with and without --tui", () => {590  it.effect(591    "refuses --tui under an agent with the same refusal, and calls nothing",592    () =>593      Effect.gen(function* () {594        const { exit } = yield* runToday(["--tui"], {595          client: Layer.mock(Client)({}),596          env: { CLAUDECODE: "1" },597        });598599        const failure = Exit.findErrorOption(exit);600601        expect(602          Option.map(failure, (failed) =>603            Schema.is(TuiRefused)(failed) ? failed.next : failed604          )605        ).toStrictEqual(Option.some(`${Brand.cli} today --json`));606      })607  );608609  it.effect(610    "is the CLI's today: under an agent, --tui ends in one line and exit 2",611    () =>612      Effect.gen(function* () {613        const { code, err, out } = yield* runProgram(["today", "--tui"], {614          env: { CLAUDECODE: "1" },615          handlers: unanswered,616        });617618        expect({ code, err, out }).toStrictEqual({619          code: 2,620          err: [621            `${Brand.cli} today --tui needs a person at a terminal, but the env names the harness claude-code: run ${Brand.cli} today --json instead`,622          ],623          out: [],624        });625      })626  );627628  it.effect("refuses --tui with --json: one document is for a script", () =>629    Effect.gen(function* () {630      const { exit } = yield* runToday(["--tui", "--json"], {631        client: Layer.mock(Client)({}),632        env: {},633      });634635      expect(636        Option.map(Exit.findErrorOption(exit), (failed) =>637          Schema.is(TuiRefused)(failed) ? failed.reason : failed638        )639      ).toStrictEqual(Option.some("--json asks for one document for a script"));640    })641  );642643  it.effect("prints Today's own refusal once, before any screen opens", () =>644    Effect.gen(function* () {645      const handlers = Layer.mergeAll(646        unanswered,647        Contracts.toLayerHandler("today", () => Effect.fail(new NotDecider()))648      );649650      const client = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(651        Layer.provide([handlers, asTester])652      );653654      const { err, exit } = yield* runToday(["--tui"], { client, env: {} });655656      expect([657        err,658        Option.map(Exit.findErrorOption(exit), String),659      ]).toStrictEqual([explain([new NotDecider()]), Option.some("Reported")]);660    })661  );662663  it.effect.each([{ flags: [] }, { flags: ["--json"] }])(664    "prints Today as the projected command does, given $flags",665    ({ flags }) =>666      Effect.gen(function* () {667        const { client } = yield* platform(new Set());668669        const handlers = Layer.mergeAll(670          unanswered,671          Contracts.toLayerHandler("today", () => Effect.succeed(today))672        );673674        const projected = yield* runToday(flags, {675          client: Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(676            Layer.provide([handlers, asTester])677          ),678          command: projectedToday,679          env: {},680        });681682        const ours = yield* runToday(flags, { client, env: {} });683684        expect(ours.out).toStrictEqual(projected.out);685        expect(ours.out.join("\n")).toContain("okonkwo");686      })687  );688});