diff --git a/test/app/app.test.tsx b/test/app/app.test.tsx new file mode 100644 index 0000000..a35a6b4 --- /dev/null +++ b/test/app/app.test.tsx @@ -0,0 +1,214 @@ +import { afterEach, describe, expect, test } from "bun:test"; + +import { withApproval, withQuestion } from "./fixtures.ts"; +import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx"; + +let app: Awaited> | null = null; +const open = async (...args: Parameters) => (app = await renderApp(...args)); +afterEach(() => { + app?.destroy(); + app = null; +}); + +describe("modes and hints", () => { + test("navigation lists the thread keys; i types, esc goes back", async () => { + const app = await open(); + expect(app.hints()).toBe("j/k threads · / filter · i type · c new · a attach · . actions · m model · ctrl+j terminal · l details · ctrl+k commands · q quit"); + await app.press("i"); + expect(app.hints()).toBe("enter send · shift+enter or \\ newline · ctrl+g editor · esc navigate · ctrl+n/p thread"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("the send shortcut setting changes the input hints", async () => { + const app = await open({ config: { sendShortcut: "ctrl-enter" } }); + await app.press("i"); + expect(app.hints()).toStartWith("ctrl+enter send · enter newline"); + }); + + test("/ filters the list; esc closes it", async () => { + const app = await open(); + await app.press("/"); + expect(app.hints()).toBe("enter done · esc close"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("f finds in the thread", async () => { + const app = await open(); + await app.press("f"); + expect(app.hints()).toBe("enter next match · shift+enter previous · ctrl+n/p match · esc close find"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("l focuses the details panel; h leaves it", async () => { + const app = await open(); + await app.press("l"); + expect(app.hints()).toBe("j/k move · enter open · t toggle automation · esc back"); + await app.press("h"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("d toggles the details column", async () => { + const app = await open(); + expect(app.frame()).not.toContain("Workspace"); + await app.press("d"); + expect(app.frame()).toContain("Workspace"); + await app.press("d"); + expect(app.frame()).not.toContain("Workspace"); + }); +}); + +describe("palette and pickers", () => { + test("ctrl+k opens the palette, typing filters it, esc closes it", async () => { + const app = await open(); + await app.press("k", { ctrl: true }); + expect(app.hints()).toBe("↑/↓ move · enter run · esc close"); + expect(app.frame()).toContain("New thread"); + await app.type("settings"); + expect(app.frame()).toContain("Settings"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("palette commands show their keys", async () => { + const app = await open(); + await app.press("k", { ctrl: true }); + await app.type("new thread"); + expect(app.frame()).toMatch(/New thread\s+c/); + }); + + test("running a command from the palette", async () => { + const app = await open(); + await app.press("k", { ctrl: true }); + await app.type("settings"); + await app.press("return"); + expect(app.hints()).toBe("j/k move · enter change · esc close"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test(". opens the thread's actions, and choosing one runs it", async () => { + const app = await open(); + await app.press("."); + expect(app.hints()).toBe("↑/↓ move · enter choose · esc close"); + await app.type("unread"); + await app.press("return"); + expect(app.calls("markUnread").map((call) => call.args[0])).toEqual([v2ThreadId]); + expect(app.hints()).toBe("Marked unread"); + }); +}); + +describe("approvals", () => { + test("y, Y and n answer the request", async () => { + const app = await open({ session: fakeSession({ projection: withApproval() }) }); + expect(app.hints()).toStartWith("y approve · Y always · n decline · j/k threads"); + await app.press("y"); + await app.press("Y"); + await app.press("n"); + expect(app.calls("respond").map((call) => call.args[2])).toEqual(["accept", "acceptForSession", "decline"]); + }); + + test("clicking a hint answers too", async () => { + const app = await open({ session: fakeSession({ projection: withApproval() }) }); + const hint = app.find("Y always"); + await app.click(hint.x, hint.y); + expect(app.calls("respond").map((call) => call.args[2])).toEqual(["acceptForSession"]); + }); + + test("while typing, the hints say an approval is waiting", async () => { + const app = await open({ session: fakeSession({ projection: withApproval() }) }); + await app.press("i"); + expect(app.hints()).toStartWith("approval waiting: esc, then y/n · enter send"); + }); +}); + +describe("questions", () => { + test("a digit picks an option and answers", async () => { + const app = await open({ session: fakeSession({ projection: withQuestion() }) }); + expect(app.hints()).toStartWith("1-9 pick · x dismiss"); + await app.press("2"); + await app.settle(300); + expect(app.calls("answer").map((call) => call.args[2])).toEqual([{ q1: "Blue" }]); + }); + + test("clicking an option answers", async () => { + const app = await open({ session: fakeSession({ projection: withQuestion() }) }); + const option = app.find("Red"); + await app.click(option.x, option.y); + await app.settle(300); + expect(app.calls("answer").map((call) => call.args[2])).toEqual([{ q1: "Red" }]); + }); + + test("x dismisses it", async () => { + const app = await open({ session: fakeSession({ projection: withQuestion() }) }); + await app.press("x"); + expect(app.calls("dismissQuestion")).toHaveLength(1); + }); +}); + +describe("composer", () => { + test("enter sends the message", async () => { + const app = await open(); + await app.press("i"); + await app.type("hello there"); + await app.press("return"); + expect(app.calls("sendMessage").map((call) => [call.args[0], call.args[1]])).toEqual([[v2ThreadId, "hello there"]]); + }); + + test("c starts a new thread draft; esc twice cancels it", async () => { + const app = await open(); + await app.press("c"); + expect(app.frame()).toContain("What should the new thread do?"); + await app.press("escape"); + expect(app.hints()).toBe("i write the first message · p project · m model & mode · w worktree · esc cancel"); + await app.press("w"); + expect(app.frame()).toContain("a new worktree from the default branch"); + await app.press("escape"); + expect(app.hints()).toStartWith("j/k threads"); + }); +}); + +describe("mouse", () => { + test("the header button opens the palette", async () => { + const app = await open(); + const button = app.find("commands ctrl+k"); + await app.click(button.x + 1, button.y); + expect(app.hints()).toBe("↑/↓ move · enter run · esc close"); + }); + + test("clicking a hint presses its key", async () => { + const app = await open(); + const hint = app.find("l details"); + await app.click(hint.x, hint.y); + expect(app.hints()).toBe("j/k move · enter open · t toggle automation · esc back"); + }); + + test("right-clicking a thread opens its actions", async () => { + const app = await open(); + const row = app.find("135d"); + await app.click(row.x, row.y, 2); + expect(app.hints()).toBe("↑/↓ move · enter choose · esc close"); + expect(app.frame()).toContain("Mark unread"); + }); + + test("clicking the composer starts typing; clicking the conversation leaves it", async () => { + const app = await open(); + const box = app.find("Press i to type"); + await app.click(box.x, box.y); + expect(app.hints()).toStartWith("enter send"); + await app.click(80, 10); + expect(app.hints()).toStartWith("j/k threads"); + }); + + test("dragging the divider resizes the list; right-click resets it", async () => { + const app = await open(); + const before = app.find("│").x; + await app.mockMouse.drag(before, 10, before + 10, 10); + await app.settle(); + expect(app.find("│").x).toBe(before + 10); + await app.click(before + 10, 10, 2); + expect(app.find("│").x).toBe(before); + }); +}); diff --git a/test/app/fixtures.ts b/test/app/fixtures.ts new file mode 100644 index 0000000..45689f1 --- /dev/null +++ b/test/app/fixtures.ts @@ -0,0 +1,33 @@ +import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { v2Projection } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; + +const at = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); + +/** The thread with a command waiting for approval. */ +export function withApproval(supportsFeedback = false): OrchestrationV2ThreadProjection { + return { + ...v2Projection, + runtimeRequests: [ + { id: "approval-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1", ...(supportsFeedback ? { supportsFeedback } : {}) }, createdAt: at, resolvedAt: null }, + ], + } as unknown as OrchestrationV2ThreadProjection; +} + +/** The thread asking one single-choice question. */ +export function withQuestion(): OrchestrationV2ThreadProjection { + return { + ...v2Projection, + runtimeRequests: [{ id: "question-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "user_input", status: "pending", responseCapability: { type: "message" }, createdAt: at, resolvedAt: null }], + turnItems: [ + { + id: "item-1", + type: "user_input_request", + requestId: "question-1", + responseMode: "message", + questions: [{ id: "q1", header: "Colour", question: "Which colour?", options: [{ label: "Red", description: "warm" }, { label: "Blue", description: "cool" }], multiSelect: false }], + }, + ], + } as unknown as OrchestrationV2ThreadProjection; +} diff --git a/test/app/harness.tsx b/test/app/harness.tsx new file mode 100644 index 0000000..cc46ee5 --- /dev/null +++ b/test/app/harness.tsx @@ -0,0 +1,105 @@ +import { testRender } from "@opentui/react/test-utils"; +import { createMockKeys, type KeyInput } from "@opentui/core/testing"; +import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts"; + +import type { T3Session } from "../../src/client/session.ts"; +import { DEFAULT_CONFIG, type Tui3Config } from "../../src/config.ts"; +import { App } from "../../src/ui/App.tsx"; +import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; + +export { v2Projection, v2ShellSnapshot, v2ThreadId }; + +// Updates from the app's own timers land outside act(); the warnings say nothing useful here. +const consoleError = console.error; +console.error = (...args: unknown[]) => { + if (typeof args[0] === "string" && args[0].includes("not wrapped in act")) return; + consoleError(...args); +}; + +export interface Call { + readonly method: string; + readonly args: readonly unknown[]; +} + +/** + * A session that serves fixed state and records every other call. Watchers get one live + * value straight away; anything not listed resolves to undefined. + */ +export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSnapshot; readonly projection?: OrchestrationV2ThreadProjection; readonly results?: Record } = {}) { + const calls: Call[] = []; + const snapshot = state.snapshot ?? v2ShellSnapshot; + const projection = state.projection ?? v2Projection; + const live = (value: T) => (listener: (value: T) => void) => { + listener(value); + return () => {}; + }; + const known: Record = { + getShell: () => ({ status: { type: "live" }, snapshot, serverUrl: "ws://test" }), + onShell: () => () => {}, + watchThread: (_id: ThreadId, listener: (value: unknown) => void) => live({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } })(listener), + watchServerConfig: live({ status: "loading", config: null }), + watchServers: live({ status: "live", items: [] }), + watchAutomations: live({ status: "live", items: [] }), + watchTerminals: live({ status: "live", items: [] }), + watchVcs: (_cwd: string, listener: (value: unknown) => void) => live({ status: "loading", local: null, remote: null })(listener), + }; + const session = new Proxy(known, { + get(target, name) { + if (typeof name !== "string") return undefined; + if (name in target) return target[name]; + if (name === "then") return undefined; + return (...args: unknown[]) => { + calls.push({ method: name, args }); + if (name.startsWith("watch") || name.startsWith("on")) return () => {}; + return Promise.resolve(state.results?.[name]); + }; + }, + }) as unknown as T3Session; + return { session, calls }; +} + +/** Renders the whole app against a fake session, with helpers to drive it by key and mouse. */ +export async function renderApp(options: { readonly session?: ReturnType; readonly config?: Partial; readonly width?: number; readonly height?: number } = {}) { + const fake = options.session ?? fakeSession(); + const config = { ...DEFAULT_CONFIG, ...options.config }; + const rig = await testRender(, { width: options.width ?? 140, height: options.height ?? 40 }); + // The app runs on timers and subscriptions, as it does live: tests wait for frames rather than wrap each update in act(). + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false; + const keys = createMockKeys(rig.renderer); + /** Lets effects, timers and React updates land, then draws a frame. */ + const settle = async (ms = 20) => { + await new Promise((resolve) => setTimeout(resolve, ms)); + await rig.renderOnce(); + }; + await settle(150); + const named: Record = { escape: "ESCAPE", return: "RETURN", tab: "TAB", up: "ARROW_UP", down: "ARROW_DOWN", left: "ARROW_LEFT", right: "ARROW_RIGHT", backspace: "BACKSPACE" }; + /** Presses a key by its OpenTUI name: "j", "Y", "escape", "return". */ + const press = async (key: string, modifiers?: Parameters[1]) => { + keys.pressKey(named[key] ?? key, modifiers); + // A lone esc waits 20ms in case it starts a longer sequence. + await settle(key === "escape" ? 60 : 20); + }; + const type = async (text: string) => { + await keys.typeText(text); + await settle(); + }; + const click = async (x: number, y: number, button: 0 | 2 = 0) => { + await rig.mockMouse.click(x, y, button); + await settle(); + }; + const frame = () => rig.captureCharFrame(); + /** The line the hint bar is on: the last one on screen. */ + const hints = () => frame().trimEnd().split("\n").at(-1)?.trim() ?? ""; + /** Where some text first appears on screen, for clicking it. */ + const find = (text: string) => { + const lines = frame().split("\n"); + for (let y = 0; y < lines.length; y++) { + const x = lines[y]!.indexOf(text); + if (x >= 0) return { x, y }; + } + throw new Error(`"${text}" is not on screen:\n${frame()}`); + }; + const calls = (method: string) => fake.calls.filter((call) => call.method === method); + const destroy = () => rig.renderer.destroy(); + return { ...rig, session: fake.session, press, type, click, settle, frame, hints, find, calls, destroy }; +}