From d29cf7079973c2347160ee7e9c116f16c57a2c25 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Tue, 3 Nov 2026 22:25:10 +1100 Subject: [PATCH] Test the Files tab: tree, marks, search, mentions, opening and previews --- test/app/files.test.tsx | 321 ++++++++++++++++++++++++++++++++++++++++ test/app/harness.tsx | 8 +- test/files.test.ts | 78 ++++++++++ 3 files changed, 404 insertions(+), 3 deletions(-) create mode 100644 test/app/files.test.tsx create mode 100644 test/files.test.ts diff --git a/test/app/files.test.tsx b/test/app/files.test.tsx new file mode 100644 index 0000000..9a88a4e --- /dev/null +++ b/test/app/files.test.tsx @@ -0,0 +1,321 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { RGBA } from "@opentui/core"; +import { ProjectReadFileError } from "@t3tools/contracts"; + +import { colors } from "../../src/ui/theme.ts"; +import { withCompletedTurn, withWorking } from "./fixtures.ts"; +import { fakeSession, renderApp, v2ShellSnapshot } from "./harness.tsx"; + +let app: Awaited> | null = null; +const open = async (...args: Parameters) => (app = await renderApp(...args)); +const saved = { visual: process.env.VISUAL, editor: process.env.EDITOR }; +afterEach(() => { + app?.destroy(); + app = null; + for (const [key, value] of [["VISUAL", saved.visual], ["EDITOR", saved.editor]] as const) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +}); +type App = Awaited>; +const prefix = async (app: App, key: string) => { + await app.press("\\", { ctrl: true }); + await app.press(key); +}; +const waitFor = async (check: () => boolean) => { + for (let tries = 0; tries < 60 && !check(); tries++) await app?.settle(25); +}; +/** The foreground colour of the first cell showing `text`. */ +const fgOf = (app: App, text: string) => { + const { x, y } = app.find(text); + const line = app.renderer.currentRenderBuffer.getSpanLines()[y] as unknown as { spans: { text: string; fg: RGBA }[] }; + let left = 0; + for (const span of line.spans) { + left += Bun.stringWidth(span.text); + if (left > x) return span.fg.toString(); + } + throw new Error(`nothing at ${x},${y}`); +}; +const color = (hex: string) => RGBA.fromHex(hex).toString(); + +const FOLDERS: Record = { + "": [ + { path: "README.md", kind: "file" }, + { path: "src", kind: "directory" }, + { path: ".git", kind: "directory" }, + { path: "dist", kind: "directory", ignored: true }, + { path: "notes.txt", kind: "file" }, + { path: "debug.log", kind: "file" }, + ], + src: [ + { path: "src/b.ts", kind: "file" }, + { path: "src/a.ts", kind: "file" }, + ], +}; +const vcs = { + status: "live", + local: { isRepo: true, hasPrimaryRemote: true, isDefaultRef: true, refName: "main", hasWorkingTreeChanges: true, workingTree: { files: [{ path: "src/a.ts", insertions: 3, deletions: 1 }, { path: "notes.txt", insertions: 0, deletions: 0 }], insertions: 3, deletions: 1 } }, + remote: { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null }, +}; +const serverConfig = { providers: [], settings: {}, environment: { capabilities: { ignoredFileListing: true } } }; +/** A server with the folders above, and whatever else a test needs. */ +const withFiles = (results: Record = {}, more: Parameters[0] = {}) => + fakeSession({ vcs, serverConfig, results: { listEntries: (_cwd: string, path: string) => FOLDERS[path] ?? [], listIgnoredFiles: [{ path: "debug.log", byteLength: 10 }], ...results }, ...more }); +const listed = (app: App) => app.calls("listEntries").map((call) => call.args[1]); +const filesKeys = "j/k move · l open · / search · m mention · y copy path · p preview · r refresh · esc back · ctrl+\\ panes"; + +/** A workspace on this machine holding README.md and src/a.ts, as the project's folder. */ +function workspace() { + const root = mkdtempSync(join(tmpdir(), "t3tui-files-")); + writeFileSync(join(root, "README.md"), "# Hello\n\nSome *words*.\n"); + mkdirSync(join(root, "src")); + writeFileSync(join(root, "src/a.ts"), "export const a = 1;\n"); + writeFileSync(join(root, "logo.bin"), new Uint8Array(3 * 1024)); + return { root, snapshot: { ...v2ShellSnapshot, projects: [{ ...v2ShellSnapshot.projects[0]!, workspaceRoot: root }] } }; +} + +describe("the Files tab", () => { + test("is a tab after Details that lists the workspace's root only once it shows", async () => { + const app = await open({ width: 200, session: withFiles() }); + expect(app.frame()).toContain("Details Files"); + expect(app.calls("listEntries")).toHaveLength(0); + await app.press("F"); + expect(listed(app)).toEqual([""]); + expect(app.hints()).toBe(filesKeys); + const frame = app.frame(); + // Folders first, then files by name; .git is hidden. + const order = ["▸ dist", "▸ src", "debug.log", "notes.txt", "README.md"].map((name) => frame.indexOf(name)); + expect(order).toEqual(order.toSorted((a, b) => a - b)); + expect(frame).not.toContain(".git"); + expect(frame).toContain("/workspace/project"); + }); + + test("marks changes as the Changes list does, a folder with changes inside, and what git ignores", async () => { + const app = await open({ width: 200, session: withFiles() }); + await app.press("F"); + const line = (name: string) => app.frame().split("\n").find((text) => text.includes(name)) ?? ""; + expect(line("notes.txt").trimEnd()).toEndWith("?"); + expect(line("▸ src").trimEnd()).toEndWith("•"); + expect(line("README.md").trimEnd()).toEndWith("README.md"); + expect(fgOf(app, "dist")).toBe(color(colors.faint)); + expect(fgOf(app, "debug.log")).toBe(color(colors.faint)); + expect(fgOf(app, "README.md")).toBe(color(colors.text)); + await app.press("j"); + await app.press("l"); + expect(line("a.ts").trimEnd()).toEndWith("M"); + }); + + test("opens folders as they're listed, with … meanwhile, and h closes them or goes up", async () => { + let release = () => {}; + const slow = new Promise((resolve) => (release = resolve)); + const app = await open({ width: 200, session: withFiles({ listEntries: async (_cwd: string, path: string) => (path === "src" ? slow.then(() => FOLDERS.src) : FOLDERS[path]) }) }); + await app.press("F"); + await app.press("j"); + await app.press("l"); + const lines = app.frame().split("\n"); + expect(lines[lines.findIndex((text) => text.includes("▾ src")) + 1]?.trimEnd()).toEndWith("…"); + release(); + await waitFor(() => app.frame().includes("a.ts")); + expect(app.frame().indexOf("a.ts")).toBeLessThan(app.frame().indexOf("b.ts")); + await app.press("l"); + await app.press("h"); + await app.press("h"); + expect(app.frame()).toContain("▸ src"); + expect(app.frame()).not.toContain("a.ts"); + // Open again, it doesn't list again. + await app.press("l"); + expect(listed(app)).toEqual(["", "src"]); + }); + + test("keeps each workspace's tree for the run", async () => { + const app = await open({ width: 200, session: withFiles() }); + await app.press("F"); + await app.press("j"); + await app.press("l"); + await app.press("escape"); + await app.press("d"); + await app.press("d"); + await prefix(app, "2"); + expect(app.frame()).toContain("▾ src"); + expect(app.frame()).toContain("a.ts"); + }); + + test("ctrl+\\ l and 1-9 reach it like any other tab", async () => { + const app = await open({ width: 200, session: withFiles() }); + await prefix(app, "l"); + expect(app.hints()).toBe(filesKeys); + await prefix(app, "1"); + expect(app.frame()).toContain("Changes"); + await prefix(app, "l"); + await prefix(app, "1"); + await app.press("l"); + await prefix(app, "2"); + expect(app.hints()).toBe(filesKeys); + await prefix(app, "x"); + expect(app.hints()).toBe("Files stays; d hides the column."); + }); + + test("a click selects, a click on a folder opens it, and one on the selected file opens it", async () => { + const { snapshot } = workspace(); + process.env.EDITOR = "sleep 3; :"; + delete process.env.VISUAL; + const app = await open({ width: 200, session: withFiles({}, { snapshot }) }); + await app.press("F"); + const folder = app.find("▸ src"); + await app.click(folder.x, folder.y); + expect(app.frame()).toContain("a.ts"); + const readme = app.find("README.md"); + await app.click(readme.x, readme.y); + expect(app.frame()).not.toContain("README.md ✕"); + await app.click(readme.x, readme.y); + expect(app.frame()).toContain("README.md ✕"); + }); + + test("r and a turn finishing list the open folders again", async () => { + const fake = withFiles({}, { projection: withWorking() }); + const app = await open({ width: 200, session: fake }); + await app.press("F"); + await app.press("j"); + await app.press("l"); + await app.press("r"); + expect(listed(app)).toEqual(["", "src", "", "src"]); + fake.updateThread(withCompletedTurn()); + await waitFor(() => listed(app).length === 6); + expect(listed(app)).toEqual(["", "src", "", "src", "", "src"]); + }); +}); + +describe("searching files", () => { + test("/ searches the workspace, and esc goes back to the tree where it was", async () => { + const results = [{ path: "src/deep/thing.ts", kind: "file" }, { path: "src/deep", kind: "directory" }]; + const app = await open({ width: 200, session: withFiles({ searchEntries: results }) }); + await app.press("F"); + await app.press("j"); + await app.press("/"); + await app.type("thing"); + await waitFor(() => app.calls("searchEntries").length > 0); + expect(app.calls("searchEntries")[0]?.args).toEqual(["/workspace/project", "thing", 200]); + await waitFor(() => app.frame().includes("src/deep/thing.ts")); + expect(app.frame()).toContain("src/deep/"); + expect(app.frame()).not.toContain("README.md"); + await app.press("escape"); + expect(app.frame()).toContain("README.md"); + expect(app.frame()).not.toContain("thing.ts"); + // Still on src. + await app.press("l"); + expect(app.frame()).toContain("▾ src"); + }); + + test("enter on a folder found shows it in the tree, open", async () => { + const app = await open({ width: 200, session: withFiles({ searchEntries: [{ path: "src", kind: "directory" }] }) }); + await app.press("F"); + await app.press("/"); + await app.type("sr"); + await waitFor(() => app.frame().includes("src/")); + await app.press("return"); + expect(app.frame()).toContain("▾ src"); + expect(app.frame()).toContain("a.ts"); + }); + + test("tab goes to the results, where m mentions one", async () => { + const app = await open({ width: 200, session: withFiles({ searchEntries: [{ path: "src/a.ts", kind: "file" }] }) }); + await app.press("F"); + await app.press("/"); + await app.type("a.ts"); + await waitFor(() => app.frame().includes("src/a.ts")); + await app.press("tab"); + await app.press("m"); + expect(app.hints()).toBe("Added @src/a.ts"); + expect(app.frame()).toContain("@src/a.ts"); + }); +}); + +describe("acting on a file", () => { + test("m mentions the selected file or folder as a chip, as the @ menu does, and keeps the keys", async () => { + const app = await open({ width: 200, session: withFiles() }); + await app.press("F"); + await app.press("j"); + await app.press("m"); + expect(app.hints()).toBe("Added @src/"); + await app.press("j"); + await app.press("m"); + expect(app.frame()).toContain("@src/ @debug.log"); + // Sent as the @ menu sends them. + await prefix(app, "k"); + await app.press("i"); + await app.press("return"); + expect(app.calls("sendMessage")[0]?.args[1]).toBe("[src](src) [debug.log](debug.log)"); + }); + + test("y copies the path", async () => { + const app = await open({ width: 200, session: withFiles() }); + await app.press("F"); + await app.press("G"); + await app.press("y"); + expect(app.calls("copy")[0]?.args).toEqual(["README.md"]); + expect(app.hints()).toBe("Copied README.md"); + }); + + test("a file on this machine opens in $EDITOR in the column", async () => { + const { snapshot } = workspace(); + process.env.EDITOR = "sleep 3; :"; + delete process.env.VISUAL; + const app = await open({ width: 200, session: withFiles({}, { snapshot }) }); + await app.press("F"); + await app.press("G"); + await app.press("return"); + expect(app.frame()).toContain("Details Files README.md ✕"); + expect(app.hints()).toStartWith("keys: README.md"); + }); + + test("elsewhere, a file opens read-only in a preview tab, which ctrl+\\ x closes back to Files", async () => { + const app = await open({ width: 200, session: withFiles({ readFile: { relativePath: "src/a.ts", contents: "export const answer = 42;\n", byteLength: 26, truncated: false } }) }); + await app.press("F"); + await app.press("j"); + await app.press("l"); + await app.press("j"); + await app.press("l"); + expect(app.calls("readFile")[0]?.args).toEqual(["/workspace/project", "src/a.ts"]); + await waitFor(() => app.frame().includes("answer")); + expect(app.frame()).toContain("Details Files src/a.ts ✕"); + expect(app.frame()).toContain("read-only"); + expect(app.hints()).toStartWith("j/k scroll"); + await prefix(app, "x"); + expect(app.frame()).not.toContain("src/a.ts ✕"); + expect(app.hints()).toBe(filesKeys); + }); + + test("p previews a file on this machine too: markdown rendered", async () => { + const { root, snapshot } = workspace(); + const app = await open({ width: 200, session: withFiles({ readFile: { relativePath: "README.md", contents: "# Hello\n\nSome *words*.\n", byteLength: 22, truncated: false } }, { snapshot }) }); + await app.press("F"); + await app.press("G"); + await app.press("p"); + expect(app.calls("readFile")[0]?.args).toEqual([root, "README.md"]); + await waitFor(() => app.frame().includes("Some words.")); + expect(app.frame()).not.toContain("# Hello"); + }); + + test("a binary file is named with its size", async () => { + const { snapshot } = workspace(); + const binary = new ProjectReadFileError({ cwd: "/x", relativePath: "logo.bin", failure: "binary_file" }); + const app = await open({ width: 200, session: withFiles({ listEntries: () => [{ path: "logo.bin", kind: "file" }], readFile: () => Promise.reject(binary) }, { snapshot }) }); + await app.press("F"); + await app.press("p"); + await waitFor(() => app.frame().includes("Binary file")); + expect(app.frame()).toContain("Binary file, 3 KB"); + }); + + test("Files: show is in the palette, under F", async () => { + const app = await open({ session: withFiles() }); + await app.press("k", { ctrl: true }); + await app.type("files show"); + expect(app.frame()).toMatch(/Files: show\s+F/); + await app.press("return"); + expect(app.hints()).toBe(filesKeys); + expect(app.frame()).toContain("Details Files"); + }); +}); diff --git a/test/app/harness.tsx b/test/app/harness.tsx index 961eaa3..a360c65 100644 --- a/test/app/harness.tsx +++ b/test/app/harness.tsx @@ -32,7 +32,7 @@ export interface Call { /** * A session that serves fixed state and records every other call. Watchers get one live * value straight away; anything not listed resolves to undefined, or rejects with its - * `failures` message. + * `failures` message. A result given as a function answers from the call's arguments. */ export function fakeSession( state: { @@ -41,7 +41,7 @@ export function fakeSession( readonly status?: ConnectionStatus; /** Git status for every folder; loading by default. */ readonly vcs?: unknown; - readonly results?: Record; + readonly results?: Record unknown)>; /** The thread's terminals on the server, and what attaching to one streams. */ readonly terminals?: readonly unknown[]; readonly terminalEvents?: readonly unknown[]; @@ -86,7 +86,9 @@ export function fakeSession( calls.push({ method: name, args }); if (name.startsWith("watch") || name.startsWith("on")) return () => {}; const failure = state.failures?.[name]; - return failure ? Promise.reject(new Error(failure)) : Promise.resolve(state.results?.[name]); + const result = state.results?.[name]; + if (failure) return Promise.reject(new Error(failure)); + return typeof result === "function" ? Promise.resolve().then(() => result(...args)) : Promise.resolve(result); }; }, }) as unknown as T3Session; diff --git a/test/files.test.ts b/test/files.test.ts new file mode 100644 index 0000000..6b8fbcd --- /dev/null +++ b/test/files.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from "bun:test"; +import type { ProjectEntry } from "@t3tools/contracts"; +import { homedir } from "node:os"; + +import type { ChangedFile } from "../src/model/details.ts"; +import { fileRows, parentOf, previewKind, rootLabel, sizeLabel, type FileTreeInput } from "../src/model/files.ts"; + +const file = (path: string, extra: Partial = {}): ProjectEntry => ({ path, kind: "file", ...extra }) as ProjectEntry; +const folder = (path: string, extra: Partial = {}): ProjectEntry => ({ path, kind: "directory", ...extra }) as ProjectEntry; +const tree = (input: Partial): FileTreeInput => ({ directories: new Map(), expanded: new Set(), loading: new Set(), ignored: new Set(), changes: [], ...input }); +const change = (path: string, status: ChangedFile["status"]): ChangedFile => ({ path, status, insertions: status === "M" ? 1 : 0, deletions: 0 }); +const names = (input: FileTreeInput) => fileRows(input).map((row) => (row.kind === "loading" ? `${" ".repeat(row.depth)}…` : `${" ".repeat(row.depth)}${row.name}`)); + +describe("fileRows", () => { + const directories = new Map([ + ["", [file("b.md"), folder("src"), file("A.md"), folder(".git"), folder("docs")]], + ["src", [file("src/z.ts"), folder("src/ui"), file("src/a.ts")]], + ]); + + test("lists folders first, then files, by name whatever the case, and hides .git", () => { + expect(names(tree({ directories }))).toEqual(["docs", "src", "A.md", "b.md"]); + }); + + test("shows an open folder's entries under it, or … while it lists", () => { + expect(names(tree({ directories, expanded: new Set(["src"]) }))).toEqual(["docs", "src", " ui", " a.ts", " z.ts", "A.md", "b.md"]); + expect(names(tree({ directories, expanded: new Set(["docs"]), loading: new Set(["docs"]) }))).toEqual(["docs", " …", "src", "A.md", "b.md"]); + }); + + test("marks changed files, untracked folders and everything in them, and folders with changes inside", () => { + const changes = [change("src/a.ts", "M"), change("docs/", "?"), change("b.md", "?")]; + const rows = fileRows(tree({ directories: new Map([...directories, ["docs", [file("docs/new.md")]]]), expanded: new Set(["src", "docs"]), changes })); + const row = (path: string) => rows.find((candidate) => candidate.path === path); + expect(row("src/a.ts")).toMatchObject({ marker: "M" }); + expect(row("src/z.ts")).toMatchObject({ marker: null }); + expect(row("src")).toMatchObject({ marker: null, changedInside: true }); + expect(row("docs")).toMatchObject({ marker: "?", changedInside: false }); + expect(row("docs/new.md")).toMatchObject({ marker: "?" }); + expect(row("b.md")).toMatchObject({ marker: "?" }); + }); + + test("counts as ignored what the listing says, what listIgnoredFiles names, and everything in an ignored folder", () => { + const rows = fileRows( + tree({ + directories: new Map([ + ["", [folder("dist", { ignored: true }), file("debug.log"), file("a.md")]], + ["dist", [file("dist/out.js")]], + ]), + expanded: new Set(["dist"]), + ignored: new Set(["debug.log"]), + }), + ); + expect(rows.map((row) => row.kind !== "loading" && [row.path, row.ignored])).toEqual([["dist", true], ["dist/out.js", true], ["a.md", false], ["debug.log", true]]); + }); +}); + +test("parentOf", () => { + expect(parentOf("src/ui/a.ts")).toBe("src/ui"); + expect(parentOf("a.ts")).toBe(""); +}); + +test("previewKind goes by extension", () => { + expect(previewKind("docs/README.md")).toBe("markdown"); + expect(previewKind("logo.PNG")).toBe("image"); + expect(previewKind("src/a.ts")).toBe("code"); + expect(previewKind("Makefile")).toBe("code"); +}); + +test("rootLabel shortens the home folder, then cuts from the middle", () => { + expect(rootLabel(`${homedir()}/projects/t3tui`, 40)).toBe("~/projects/t3tui"); + expect(rootLabel(`${homedir()}/projects/deeply/nested/t3tui`, 12)).toBe("~/…/t3tui"); + expect(rootLabel("/srv/work/project", 12)).toBe("…/project"); +}); + +test("sizeLabel", () => { + expect(sizeLabel(512)).toBe("512 B"); + expect(sizeLabel(3 * 1024)).toBe("3 KB"); + expect(sizeLabel(5.5 * 1024 * 1024)).toBe("5.5 MB"); +});