Merge branch 'files': the Files tab, and the redraw leak fix

This commit is contained in:
callumalpass committed 2026-11-04 00:11:22 +11:00
commit 2845b6fe2b
18 files changed
+1318 -72

No files matched your search

+2 -1
View File
@@ -61,7 +61,8 @@ The keys you'll use most:
| `ctrl+j` | the thread's terminals on the server, in a drawer below the message box | | `ctrl+j` | the thread's terminals on the server, in a drawer below the message box |
| `ctrl+\` | the panes' prefix: then `ctrl+\` moves the keys between a terminal or editor and the conversation, `tab` to the next pane, `1`–`9` picks a tab, `x` closes it, `z` zooms, `n` opens a terminal | | `ctrl+\` | the panes' prefix: then `ctrl+\` moves the keys between a terminal or editor and the conversation, `tab` to the next pane, `1`–`9` picks a tab, `x` closes it, `z` zooms, `n` opens a terminal |
| `ctrl+g` | write the message in `$EDITOR`, in the message box's place | | `ctrl+g` | write the message in `$EDITOR`, in the message box's place |
| `d` | show or hide the right-hand column: details, a tab per open editor, and terminals placed at the side | | `d` | show or hide the right-hand column: details, the workspace's files, a tab per open editor or preview, and terminals placed at the side |
| `F` | browse the workspace's files: `/` searches, `enter` opens, `p` previews, `m` mentions it in the message |
| `ctrl+v` | in the message box: attach the clipboard's image (or paste its text) | | `ctrl+v` | in the message box: attach the clipboard's image (or paste its text) |
| `ctrl+c` | quit | | `ctrl+c` | quit |
+26 -6
View File
@@ -59,7 +59,8 @@ Navigation:
| `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes | | `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes |
| `A` | show archived threads / return to active threads | | `A` | show archived threads / return to active threads |
| `J` / `K` | move the selected pinned thread down / up | | `J` / `K` | move the selected pinned thread down / up |
| `d` | show or hide the right-hand column: thread details, and a tab for each open editor and, placed at the side, each terminal (kept for the next run) | | `d` | show or hide the right-hand column: thread details, the workspace's files, and a tab for each open editor, file preview and, placed at the side, each terminal (kept for the next run) |
| `F` | the Files tab: browse the thread's worktree, or its project folder (see [Files](#files)) |
| `B` | hide or show the thread list (kept for the next run) | | `B` | hide or show the thread list (kept for the next run) |
| `P` | show the thread's linked pull request | | `P` | show the thread's linked pull request |
| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `o` edits the selected changed file in a tab of the column, `t` turns an automation on or off, `esc` comes back | | `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `o` edits the selected changed file in a tab of the column, `t` turns an automation on or off, `esc` comes back |
@@ -102,7 +103,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- **Conversation:** each finished turn's work folds into one line (`Worked for 3m 12s`), your messages sit in a raised block with a bar down the left, and a running turn shows its live step and `Working for 12s`. Replies render as markdown while they stream, tables included, and settle into their final form when done; at the bottom the newest line stays in view, and scrolled up the text you're reading stays put. Threads open scrolled to the bottom. Long threads load as a window of recent turns; press `o` for older ones. - **Conversation:** each finished turn's work folds into one line (`Worked for 3m 12s`), your messages sit in a raised block with a bar down the left, and a running turn shows its live step and `Working for 12s`. Replies render as markdown while they stream, tables included, and settle into their final form when done; at the bottom the newest line stays in view, and scrolled up the text you're reading stays put. Threads open scrolled to the bottom. Long threads load as a window of recent turns; press `o` for older ones.
- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds the chat and returns the prompt to the message box, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the app. - **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds the chat and returns the prompt to the message box, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the app.
- **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops it. - **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops it.
- **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. While a file is open in an editor, or with terminals placed at the side, the column has a tab for each, with a strip of tabs at its top: click one, or press `ctrl+\` then its number. - **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. A strip of tabs at its top reads `Details · Files`, then a tab for each file open in an editor or a preview and each terminal placed at the side: click one, or press `ctrl+\` then its number.
- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes in place of the conversation: side by side when the conversation is at least 140 columns wide, unified otherwise. `Toggle split diff` in the palette switches between the two for the rest of the session. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged lines; press it again to collapse. Diffs of past checkpoints show only the changed lines. - **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes in place of the conversation: side by side when the conversation is at least 140 columns wide, unified otherwise. `Toggle split diff` in the palette switches between the two for the rest of the session. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged lines; press it again to collapse. Diffs of past checkpoints show only the changed lines.
- **Git:** the branch section offers the quick action (`Commit & push`, `Push`, `Create PR`…) and a menu of the rest. Every action asks first, says when you are on the default branch, and takes an optional commit message (leave it blank and T3 writes one). Progress shows on the bottom line. - **Git:** the branch section offers the quick action (`Commit & push`, `Push`, `Create PR`…) and a menu of the rest. Every action asks first, says when you are on the default branch, and takes an optional commit message (leave it blank and T3 writes one). Progress shows on the bottom line.
- **Pull requests:** `P` shows a linked pull request in place of the conversation (with several, you pick one): its state, author and branches, description, checks, reviews, recent comments and the review guide when one was written. `j`/`k` scroll, `o` opens it in the browser, `r` refreshes it, and `esc` closes it. From there, `c` comments and `R` reviews (approve / request changes / comment) in `$EDITOR`, `a` offers the host's actions (merge, close, ready…) behind a confirmation, `w` watches or stops watching, and `u` unlinks it. `Link pull request to thread` in the palette links one by URL or number, and `New thread from pull request…` checks one out into a draft in the project folder or its own worktree. - **Pull requests:** `P` shows a linked pull request in place of the conversation (with several, you pick one): its state, author and branches, description, checks, reviews, recent comments and the review guide when one was written. `j`/`k` scroll, `o` opens it in the browser, `r` refreshes it, and `esc` closes it. From there, `c` comments and `R` reviews (approve / request changes / comment) in `$EDITOR`, `a` offers the host's actions (merge, close, ready…) behind a confirmation, `w` watches or stops watching, and `u` unlinks it. `Link pull request to thread` in the palette links one by URL or number, and `New thread from pull request…` checks one out into a draft in the project folder or its own worktree.
@@ -119,7 +120,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- **Select and copy:** drag across any text, in the conversation or a terminal or editor, to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally) and `Copied` shows at the bottom. A program in a terminal or editor that takes the mouse itself, like an editor with mouse support, gets the drag instead. A single click still does what it did. A key press clears the highlight. Your terminal's own selection still works with shift held. - **Select and copy:** drag across any text, in the conversation or a terminal or editor, to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally) and `Copied` shows at the bottom. A program in a terminal or editor that takes the mouse itself, like an editor with mouse support, gets the drag instead. A single click still does what it did. A key press clears the highlight. Your terminal's own selection still works with shift held.
- **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top. - **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top.
- **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a reply, links are underlined in the accent colour and a click opens them in the browser (`xdg-open`, or `open` on macOS); a click on a path to a file in the workspace, like `src/ui/App.tsx:12`, opens it in a tab of the right-hand column. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. - **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a reply, links are underlined in the accent colour and a click opens them in the browser (`xdg-open`, or `open` on macOS); a click on a path to a file in the workspace, like `src/ui/App.tsx:12`, opens it in a tab of the right-hand column. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. In the Files tab, a click selects a row, a click on a folder opens or closes it, and a click on the selected file opens it.
- **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions). - **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions).
- **Panes:** clicking the conversation takes the keys out of the message box, details or a pane; clicking the message box types; clicking a pane gives it the keys. A click on a tab switches to it, the active tab's ✕ closes it, and a middle-click closes any tab. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, the right-hand column's left edge or the terminal drawer's top edge to resize it; right-click the edge to reset it. - **Panes:** clicking the conversation takes the keys out of the message box, details or a pane; clicking the message box types; clicking a pane gives it the keys. A click on a tab switches to it, the active tab's ✕ closes it, and a middle-click closes any tab. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, the right-hand column's left edge or the terminal drawer's top edge to resize it; right-click the edge to reset it.
@@ -172,7 +173,7 @@ While the drawer has focus, every key goes to its program, `esc` included, apart
## Panes ## Panes
The drawer, the message editor and the column's editor and terminal tabs are panes. Focus moves through whichever are open in one order: the conversation (and message box), the message editor, the drawer, the column, and back. The hint bar names the pane that has the keys, `keys: Terminal 1`, and its strip lights up: a raised background, the active tab in the accent, and an accent edge down its left. Panes without the keys go quiet, and so does the message box's bar. The drawer, the message editor and the column's Files, editor, preview and terminal tabs are panes. Focus moves through whichever are open in one order: the conversation (and message box), the message editor, the drawer, the column, and back. The hint bar names the pane that has the keys, `keys: Terminal 1`, and its strip lights up: a raised background, the active tab in the accent, and an accent edge down its left. Panes without the keys go quiet, and so does the message box's bar.
`ctrl+\` is a prefix, wherever the keys are, a program included. The hint bar shows the keys it waits for, `ctrl+\ … tab next · j drawer · l column · 1-9 tab · x close · z zoom · n new · esc cancel`, for about two seconds. Then: `ctrl+\` is a prefix, wherever the keys are, a program included. The hint bar shows the keys it waits for, `ctrl+\ … tab next · j drawer · l column · 1-9 tab · x close · z zoom · n new · esc cancel`, for about two seconds. Then:
@@ -181,16 +182,35 @@ The drawer, the message editor and the column's editor and terminal tabs are pan
| `ctrl+\` | move the keys between the conversation and the pane that last had them | | `ctrl+\` | move the keys between the conversation and the pane that last had them |
| `tab` / `shift+tab` | the next / previous pane in the order above | | `tab` / `shift+tab` | the next / previous pane in the order above |
| `j` | the drawer, opening it if it's hidden | | `j` | the drawer, opening it if it's hidden |
| `l` | the column's program tab (the one it showed last), showing the column if it's hidden | | `l` | the column's tab it showed last (from Details: the first editor, preview or terminal, else Files), showing the column if it's hidden |
| `k` / `h` | back to the conversation | | `k` / `h` | back to the conversation |
| `1`–`9` | that tab of the focused strip: the drawer's terminals, or the column's tabs; with no pane focused, the drawer's | | `1`–`9` | that tab of the focused strip: the drawer's terminals, or the column's tabs; with no pane focused, the drawer's |
| `x` | close the focused tab: a terminal after asking; Neovim is asked to quit (`:confirm qa`, so it asks about unsaved changes itself); other editors are left for you to quit, since closing them could lose work | | `x` | close the focused tab: a preview at once; a terminal after asking; Neovim is asked to quit (`:confirm qa`, so it asks about unsaved changes itself); other editors are left for you to quit, since closing them could lose work |
| `z` | zoom: the focused pane (or, from the conversation, the last one) fills the conversation's area until `z` again; the thread list stays | | `z` | zoom: the focused pane (or, from the conversation, the last one) fills the conversation's area until `z` again; the thread list stays |
| `n` | a new terminal | | `n` | a new terminal |
| `esc`, any other key | cancel | | `esc`, any other key | cancel |
A key after the prefix never reaches the program, and a program can't receive `ctrl+\` itself. `Pane: next` and `Pane: zoom` are in the palette too. A key after the prefix never reaches the program, and a program can't receive `ctrl+\` itself. `Pane: next` and `Pane: zoom` are in the palette too.
## Files
`F`, or `Files: show` in the palette, shows the column's Files tab with the keys in it: the thread's worktree, or its project folder when it has none, as a tree. The top line names the root (`~/…/project`). Folders list when you first open them (`…` while they load) and stay open per workspace until t3tui quits. Folders come first; `.git` is left out. What git ignores is faint, and the Changes list's marks sit on the right: `M` for a modified file, `?` for an untracked one (and everything in an untracked folder), and a faint `•` on a folder with changes inside. Open folders list again when a turn finishes or git's status changes, each time the tab is shown, and on `r`.
| Key | Action |
| --- | --- |
| `j`/`k`, arrows | move |
| `l` / `enter` / `→` | open a folder, or open a file: in an editor tab when it's on this machine, otherwise in a read-only preview |
| `h` / `←` | close the folder, or go to its parent |
| `g` / `G` | first / last row |
| `/` | search the workspace: type, then `↑`/`↓` and `enter` (a folder shows in the tree), `tab` to move into the results; `esc` returns to the tree where you left it |
| `m` | mention the file or folder in the message box, as the `@` menu does; the keys stay in the tree |
| `y` | copy the path |
| `p` | preview the file, even when it's on this machine |
| `r` | list everything again |
| `esc` | back to the conversation |
Results take the same keys (`j`/`k`, `enter`, `m`, `y`, `p`). A preview is a tab of its own, titled with the path: code is highlighted by its extension, markdown is rendered, images are drawn, and other binary files show their size. `j`/`k` scroll it, `space`/`pgdn` and `pgup` page, `g`/`G` go to the ends, and `ctrl+\ x` or the tab's ✕ closes it and returns to Files. Files are read through the server, so previews work over SSH too. The Files tab can't be closed; `d` hides the column. Creating, renaming or deleting files is left to the agent or your editor.
## Workspace ## Workspace
`b` opens the branch picker: local and remote refs, existing worktrees, `Create and switch ref…`, and `Pull`. Selecting a ref reuses its worktree if it has one; selecting the default branch returns to the project folder. `Create worktree…` asks for a new branch name and moves this thread there. `Remove worktree…` asks first, then removes the worktree only if no other thread uses it and Git allows it (it never forces). Moving the thread to another folder detaches its provider session. `b` opens the branch picker: local and remote refs, existing worktrees, `Create and switch ref…`, and `Pull`. Selecting a ref reuses its worktree if it has one; selecting the default branch returns to the project folder. `Create worktree…` asks for a new branch name and moves this thread there. `Remove worktree…` asks first, then removes the worktree only if no other thread uses it and Git allows it (it never forces). Moving the thread to another folder detaches its provider session.
+63 -4
View File
@@ -5,11 +5,13 @@
* same with the terminal drawer open, in both themes. Then the panes, one * same with the terminal drawer open, in both themes. Then the panes, one
* page each (demo-pane-*.html): the drawer with and without the keys, the * page each (demo-pane-*.html): the drawer with and without the keys, the
* ctrl+\ prefix waiting, zoom, the strip of running programs, side * ctrl+\ prefix waiting, zoom, the strip of running programs, side
* placement's one strip, two files in one Neovim, and the palette. * placement's one strip, two files in one Neovim, and the palette. Then the Files
* tab: the tree with git's marks and ignored entries, a search, and previews of
* code and markdown.
* *
* Run with `bun run scripts/demo-capture.tsx`. * Run with `bun run scripts/demo-capture.tsx`.
*/ */
import { mkdtempSync } from "node:fs"; import { mkdtempSync, readFileSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises"; import { mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
@@ -449,7 +451,32 @@ const editBoth = async (app: DemoApp) => {
await app.settle(600); await app.settle(600);
}; };
const scenes: readonly { readonly name: string; readonly layout?: Layout; readonly steps: (app: DemoApp) => Promise<void> }[] = [ /** The demo project as the server lists it, a folder at a time, with a few changes and what git ignores. */
const entry = (path: string, kind: "file" | "directory" = "file", ignored = false) => ({ path, kind, ...(ignored ? { ignored } : {}) });
const folders: Record<string, readonly unknown[]> = {
"": [entry(".github", "directory"), entry("dist", "directory", true), entry("node_modules", "directory", true), entry("scripts", "directory"), entry("src", "directory"), entry("test", "directory"), entry(".gitignore"), entry("bun.lock"), entry("debug.log", "file", true), entry("package.json"), entry("README.md"), entry("tsconfig.json")],
scripts: [entry("scripts/build.ts"), entry("scripts/compile.ts"), entry("scripts/demo-capture.tsx")],
src: [entry("src/client", "directory"), entry("src/model", "directory"), entry("src/ui", "directory"), entry("src/bin.ts"), entry("src/config.ts"), entry("src/layout.ts")],
"src/ui": ["App.tsx", "Button.tsx", "DetailsPanel.tsx", "FilePreview.tsx", "FilesPanel.tsx", "TerminalPane.tsx", "text.ts", "theme.ts", "useFiles.ts", "usePanes.ts"].map((name) => entry(`src/ui/${name}`)),
};
const filesVcs = { ...vcs, local: { ...vcs.local, workingTree: { files: [...vcs.local.workingTree.files, { path: "src/ui/usePanes.ts", insertions: 12, deletions: 3 }, { path: "src/ui/FilesPanel.tsx", insertions: 0, deletions: 0 }], insertions: 20, deletions: 5 } } };
const repoRoot = join(import.meta.dir, "..");
const filesResults = {
listEntries: (_cwd: string, path: string) => folders[path] ?? [],
searchEntries: () => ["src/ui/TerminalPane.tsx", "src/ui/usePanes.ts", "src/ui/FilePreview.tsx", "src/ui/FilesPanel.tsx", "test/app/pane.test.tsx"].map((path) => entry(path)),
// This repository's own files stand in for the demo project's.
readFile: (_cwd: string, path: string) => {
const contents = readFileSync(join(repoRoot, path), "utf8");
return { relativePath: path, contents, byteLength: contents.length, truncated: false };
},
};
/** Down the Files tab to `name`, or until it stops moving. */
const selectFile = async (app: DemoApp, name: string) => {
const row = new RegExp(`▌[ ▸▾]*${name.replace(".", "\\.")}(\\s|$)`);
for (let tries = 0; tries < 30 && !row.test(app.frame()); tries++) await app.press("j");
};
const scenes: readonly { readonly name: string; readonly layout?: Layout; readonly files?: boolean; readonly steps: (app: DemoApp) => Promise<void> }[] = [
{ name: "drawer-focused", steps: (app) => app.press("j", { ctrl: true }) }, { name: "drawer-focused", steps: (app) => app.press("j", { ctrl: true }) },
{ name: "drawer-unfocused", steps: async (app) => { { name: "drawer-unfocused", steps: async (app) => {
await app.press("j", { ctrl: true }); await app.press("j", { ctrl: true });
@@ -488,12 +515,44 @@ const scenes: readonly { readonly name: string; readonly layout?: Layout; readon
await app.press("k", { ctrl: true }); await app.press("k", { ctrl: true });
await app.type("terminal"); await app.type("terminal");
} }, } },
{ name: "files-tree", layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, files: true, steps: async (app) => {
await app.press("F");
await selectFile(app, "src");
await app.press("l");
await selectFile(app, "ui");
await app.press("l");
await selectFile(app, "usePanes.ts");
} },
{ name: "files-search", layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, files: true, steps: async (app) => {
await app.press("F");
await app.press("/");
await app.type("pane");
await app.settle(300);
await app.press("down");
} },
{ name: "files-preview-code", layout: { ...DEFAULT_LAYOUT, detailsWidth: 70 }, files: true, steps: async (app) => {
await app.press("F");
await selectFile(app, "src");
await app.press("l");
await selectFile(app, "ui");
await app.press("l");
await selectFile(app, "text.ts");
await app.press("p");
await app.settle(500);
} },
{ name: "files-preview-markdown", layout: { ...DEFAULT_LAYOUT, detailsWidth: 70 }, files: true, steps: async (app) => {
await app.press("F");
await selectFile(app, "README.md");
await app.press("p");
await app.settle(500);
} },
]; ];
applyTheme("dark"); applyTheme("dark");
for (const scene of scenes) { for (const scene of scenes) {
const terminalEvents = [{ type: "snapshot", threadId: OPEN_THREAD, terminalId: "term-1", createdAt: new Date(NOW).toISOString(), snapshot: { history: terminalHistory } }]; const terminalEvents = [{ type: "snapshot", threadId: OPEN_THREAD, terminalId: "term-1", createdAt: new Date(NOW).toISOString(), snapshot: { history: terminalHistory } }];
const app = await renderApp({ session: fakeSession({ snapshot: localSnapshot, projection, terminals, terminalEvents, vcs }), width: 190, height: 50, ...(scene.layout ? { layout: scene.layout } : {}) }); const session = scene.files ? fakeSession({ snapshot: localSnapshot, projection, vcs: filesVcs, results: filesResults }) : fakeSession({ snapshot: localSnapshot, projection, terminals, terminalEvents, vcs });
const app = await renderApp({ session, width: 190, height: 50, ...(scene.layout ? { layout: scene.layout } : {}) });
try { try {
await scene.steps(app); await scene.steps(app);
await app.settle(120); await app.settle(120);
+28
View File
@@ -42,6 +42,8 @@ import {
type ModelSelection, type ModelSelection,
type OrchestrationMessageContext, type OrchestrationMessageContext,
type ProjectEntry, type ProjectEntry,
type ProjectIgnoredFile,
type ProjectReadFileResult,
type RuntimeMode, type RuntimeMode,
type TerminalAttachStreamEvent, type TerminalAttachStreamEvent,
type TerminalSummary, type TerminalSummary,
@@ -783,6 +785,32 @@ export class T3Session {
return result.entries; return result.entries;
} }
/** One folder of `cwd` (its root for ""), as the web's file explorer lists it a folder at a time. */
async listEntries(cwd: string, directoryPath: string): Promise<readonly ProjectEntry[]> {
const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsListEntries]({ cwd, directoryPath }));
return result.entries;
}
/** Untracked files git ignores under `cwd`; wholly ignored folders are left out. */
async listIgnoredFiles(cwd: string): Promise<readonly ProjectIgnoredFile[]> {
const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsListIgnoredFiles]({ cwd }));
return result.files;
}
/** A workspace file's text; binary files fail with failure `binary_file`. */
readFile(cwd: string, relativePath: string): Promise<ProjectReadFileResult> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsReadFile]({ cwd, relativePath }));
}
/** A workspace file from the server, through an asset URL as the web's previews fetch it: its bytes, or only its size from the headers. */
async fetchWorkspaceFile(threadId: ThreadId, path: string): Promise<Response> {
const { rpc, target } = this.requireConnection();
const minted = await Effect.runPromise(rpc[WS_METHODS.assetsCreateUrl]({ resource: { _tag: "workspace-file", threadId, path } }));
const response = await fetch(new URL(minted.relativeUrl, target.httpBaseUrl));
if (!response.ok) throw new Error(`File request failed (${response.status})`);
return response;
}
/** Pull requests for a scope, as the web's list and the composer's `#` menu read them. */ /** Pull requests for a scope, as the web's list and the composer's `#` menu read them. */
async pullRequestsList(input: PullRequestListInput): Promise<PullRequestListResult> { async pullRequestsList(input: PullRequestListInput): Promise<PullRequestListResult> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.pullRequestsList](input)); return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.pullRequestsList](input));
+88
View File
@@ -0,0 +1,88 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { homedir } from "node:os";
import type { ChangedFile } from "./details.ts";
/** A line of the Files tab: an entry, or the `…` under a folder still loading. */
export type FileRow =
| {
readonly kind: "file" | "directory";
readonly path: string;
readonly name: string;
readonly depth: number;
readonly expanded: boolean;
readonly ignored: boolean;
/** The Changes list's mark for it, or for a whole untracked folder. */
readonly marker: ChangedFile["status"] | null;
/** A folder with changes somewhere inside it. */
readonly changedInside: boolean;
}
| { readonly kind: "loading"; readonly path: string; readonly depth: number };
export interface FileTreeInput {
/** Each listed folder's entries, by its path ("" for the root). */
readonly directories: ReadonlyMap<string, readonly ProjectEntry[]>;
readonly expanded: ReadonlySet<string>;
readonly loading: ReadonlySet<string>;
/** Paths git ignores, as listIgnoredFiles reports them. */
readonly ignored: ReadonlySet<string>;
/** The working tree's changes, as the Changes list has them. */
readonly changes: readonly ChangedFile[];
}
/** The folder a path is in, "" at the root. */
export const parentOf = (path: string) => path.slice(0, Math.max(0, path.lastIndexOf("/")));
/** Folders first, then by name, as file explorers sort. */
export function sortEntries(entries: readonly ProjectEntry[]): ProjectEntry[] {
return entries
.filter((entry) => nameOf(entry.path) !== ".git")
.toSorted((a, b) => (a.kind === b.kind ? nameOf(a.path).localeCompare(nameOf(b.path), undefined, { sensitivity: "base" }) : a.kind === "directory" ? -1 : 1));
}
/** The tree as rows: each listed folder's entries under it, expanded folders open. */
export function fileRows(input: FileTreeInput): FileRow[] {
const untracked = input.changes.filter((file) => file.path.endsWith("/")).map((file) => file.path);
const changed = new Map(input.changes.map((file) => [file.path, file.status] as const));
const rows: FileRow[] = [];
const visit = (directory: string, depth: number, ignoredAbove: boolean) => {
for (const entry of sortEntries(input.directories.get(directory) ?? [])) {
const folder = entry.kind === "directory";
const expanded = folder && input.expanded.has(entry.path);
const ignored = ignoredAbove || entry.ignored === true || input.ignored.has(entry.path);
const marker = changed.get(folder ? `${entry.path}/` : entry.path) ?? (untracked.some((path) => entry.path.startsWith(path)) ? "?" : null);
const changedInside = folder && marker === null && input.changes.some((file) => file.path.startsWith(`${entry.path}/`));
rows.push({ kind: entry.kind, path: entry.path, name: nameOf(entry.path), depth, expanded, ignored, marker, changedInside });
if (!expanded) continue;
if (input.directories.has(entry.path)) visit(entry.path, depth + 1, ignored);
else if (input.loading.has(entry.path)) rows.push({ kind: "loading", path: entry.path, depth: depth + 1 });
}
};
visit("", 0, false);
return rows;
}
/** How the preview tab shows a file: highlighted code, rendered markdown, or an image. */
export function previewKind(path: string): "code" | "markdown" | "image" {
const extension = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
if (extension === "md" || extension === "markdown") return "markdown";
return IMAGE_EXTENSIONS.has(extension) ? "image" : "code";
}
const IMAGE_EXTENSIONS: ReadonlySet<string> = new Set(["png", "jpg", "jpeg", "gif", "webp"]);
/** `~/…/project`: the root with the home folder shortened, cut from the middle to `width`. */
export function rootLabel(root: string, width: number): string {
const home = homedir();
const path = root === home || root.startsWith(`${home}/`) ? `~${root.slice(home.length)}` : root;
if (path.length <= width) return path;
const name = nameOf(path);
const head = path.startsWith("~/") ? "~/…/" : "…/";
return head.length + name.length <= width ? `${head}${name}` : `…${name.slice(Math.max(0, name.length - width + 1))}`;
}
/** `12 KB`, as the binary note says it. */
export function sizeLabel(bytes: number): string {
return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1);
+89 -18
View File
@@ -5,7 +5,7 @@ import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContex
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
import { existsSync, statSync } from "node:fs"; import { existsSync, statSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { isAbsolute, relative } from "node:path"; import { isAbsolute, join, relative } from "node:path";
import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -29,9 +29,12 @@ import { ComposerMenu } from "./ComposerMenu.tsx";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
import { DetailsPanel } from "./DetailsPanel.tsx"; import { DetailsPanel } from "./DetailsPanel.tsx";
import { DiffView, type DiffState } from "./DiffView.tsx"; import { DiffView, type DiffState } from "./DiffView.tsx";
import { FilePreview } from "./FilePreview.tsx";
import { FilesPanel } from "./FilesPanel.tsx";
import { DraftView } from "./DraftView.tsx"; import { DraftView } from "./DraftView.tsx";
import { useComposerMenu } from "./useComposerMenu.ts"; import { useComposerMenu } from "./useComposerMenu.ts";
import { useDetails } from "./useDetails.ts"; import { useDetails } from "./useDetails.ts";
import { useFiles } from "./useFiles.ts";
import { useDraft } from "./useDraft.ts"; import { useDraft } from "./useDraft.ts";
import { useModelPicker } from "./useModelPicker.ts"; import { useModelPicker } from "./useModelPicker.ts";
import { useQuestion } from "./useQuestion.ts"; import { useQuestion } from "./useQuestion.ts";
@@ -587,6 +590,25 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
useEffect(() => { useEffect(() => {
if (mode === "details") panes.showColumnTab("details"); if (mode === "details") panes.showColumnTab("details");
}, [mode]); }, [mode]);
const files = useFiles({
session,
live,
cwd: draft ? null : panel.cwd,
visible: panel.show && panes.columnKind === "files",
changes: panel.details?.changes?.files ?? [],
working,
ignoredListing: providerConfig?.environment.capabilities.ignoredFileListing === true,
open: (path) => openFile(path),
preview: (path) => panel.cwd && panes.openPreview(path, panel.cwd),
mention: (path, kind) => {
if (composerMenu.mention({ path, kind })) say(`Added @${path}${kind === "directory" ? "/" : ""}`);
else say("There's no message box to mention it in.", true);
},
copy: (path) => copy(path, path),
leave: () => setMode("nav"),
say,
});
const previewScrollRef = useRef<ScrollBoxRenderable | null>(null);
/** The composer's text in $EDITOR, in the composer's place; what's saved comes back when it exits. */ /** The composer's text in $EDITOR, in the composer's place; what's saved comes back when it exits. */
const openEditor = () => { const openEditor = () => {
@@ -639,6 +661,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
}); });
}; };
/** A file from the Files tab: in $EDITOR when it's on this machine, else read-only in a preview tab. */
const openFile = (path: string) => {
const cwd = panel.cwd;
if (!cwd) return;
if (existsSync(join(cwd, path))) editFile(path, cwd);
else panes.openPreview(path, cwd);
};
/** A click on a link opens it in the browser; on a path to a workspace file, in the column's editor. A drag doesn't. */ /** A click on a link opens it in the browser; on a path to a workspace file, in the column's editor. A drag doesn't. */
const openAt = (x: number, y: number) => { const openAt = (x: number, y: number) => {
if (renderer.getSelection()?.getSelectedText()) return; if (renderer.getSelection()?.getSelectedText()) return;
@@ -909,6 +939,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
library.commands(threadId).map((command) => fromCommand(command)), library.commands(threadId).map((command) => fromCommand(command)),
workspace.commands.map((command) => fromCommand(command)), workspace.commands.map((command) => fromCommand(command)),
threadId && !draft && { keys: ["f"], run: openFind, command: { id: "find", title: "Find in thread", keywords: ["search", "messages", "plans"] } }, threadId && !draft && { keys: ["f"], run: openFind, command: { id: "find", title: "Find in thread", keywords: ["search", "messages", "plans"] } },
threadId && !draft && { keys: ["F"], run: panes.showFiles, command: { id: "files", title: "Files: show", keywords: ["explorer", "tree", "browse", "project", "workspace"] } },
// Only P is a navigation key; the rest are the PR view's own (below). // Only P is a navigation key; the rest are the PR view's own (below).
pullRequests.commands.filter((command) => command.id === "pull-requests").map((command) => fromCommand(command)), pullRequests.commands.filter((command) => command.id === "pull-requests").map((command) => fromCommand(command)),
{ keys: ["j", "↓"], label: "j/k", run: () => (attached ? scrollBy(1) : move(1)), hint: attached ? "scroll" : "threads" }, { keys: ["j", "↓"], label: "j/k", run: () => (attached ? scrollBy(1) : move(1)), hint: attached ? "scroll" : "threads" },
@@ -1007,6 +1038,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
{ keys: ["G"], run: () => scrollToEnd(scrollRef.current) }, { keys: ["G"], run: () => scrollToEnd(scrollRef.current) },
pullRequests.viewKeys, pullRequests.viewKeys,
); );
const previewKeys = keys(
{ keys: ["j", "↓"], label: "j/k", run: () => previewScrollRef.current?.scrollBy(1), hint: "scroll" },
{ keys: ["k", "↑"], run: () => previewScrollRef.current?.scrollBy(-1) },
{ keys: ["space", "pagedown"], run: () => previewScrollRef.current?.scrollBy(Math.max(1, height - 10)) },
{ keys: ["pageup"], run: () => previewScrollRef.current?.scrollBy(-Math.max(1, height - 10)) },
{ keys: ["g"], run: () => previewScrollRef.current?.scrollTo(0) },
{ keys: ["G"], run: () => scrollToEnd(previewScrollRef.current) },
{ keys: [], label: "ctrl+\\ x", run: () => panes.closeTab(panes.columnTab), hint: "close" },
{ keys: ["esc"], run: () => setMode("nav"), hint: "back" },
);
const findKeys = keys( const findKeys = keys(
find.bindings, find.bindings,
{ keys: ["esc"], run: () => setMode("nav"), hint: "close find" }, { keys: ["esc"], run: () => setMode("nav"), hint: "close find" },
@@ -1044,7 +1085,9 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
} }
// After ctrl+\, the next key is the prefix's; handleKey takes it. // After ctrl+\, the next key is the prefix's; handleKey takes it.
if (panes.prefix) return { layers: [], hints: panes.keys.afterPrefix }; if (panes.prefix) return { layers: [], hints: panes.keys.afterPrefix };
// In a terminal, ctrl+j hides it again, as it leaves a terminal attached full screen. // Files and previews take their own keys; a terminal takes all but ctrl+\, and ctrl+j hides it again.
if (mode === "pane" && panes.focusedPane === "column" && panes.columnKind === "files") return { layers: [files.keys, globalKeys], hints: [...files.keys, prefixKey] };
if (mode === "pane" && panes.focusedPane === "column" && panes.columnKind === "preview") return { layers: [previewKeys, globalKeys], hints: [...previewKeys, prefixKey] };
if (mode === "pane") return { layers: [keys(prefixKey, panes.terminalFocused && terminalKey)], hints: panes.keys.focused }; if (mode === "pane") return { layers: [keys(prefixKey, panes.terminalFocused && terminalKey)], hints: panes.keys.focused };
// The secret field takes every key while it's focused. // The secret field takes every key while it's focused.
if (secret.focused) return { layers: [secret.bindings, [prefixKey, quitKey]], hints: secret.bindings }; if (secret.focused) return { layers: [secret.bindings, [prefixKey, quitKey]], hints: secret.bindings };
@@ -1099,21 +1142,24 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const groups = useMemo(() => (mode === "palette" ? messageMatchGroups(paletteGroups({ query: paletteQuery, commands, snapshot: paletteSnapshot, now }), paletteSearch.result, paletteSnapshot, paletteQuery, now) : []), [mode, paletteQuery, commandKey, paletteSnapshot, paletteSearch.result]); const groups = useMemo(() => (mode === "palette" ? messageMatchGroups(paletteGroups({ query: paletteQuery, commands, snapshot: paletteSnapshot, now }), paletteSearch.result, paletteSnapshot, paletteQuery, now) : []), [mode, paletteQuery, commandKey, paletteSnapshot, paletteSearch.result]);
const entries = paletteEntries(groups); const entries = paletteEntries(groups);
// The mouse in the conversation: stable callbacks, since its rows are memoized. // The mouse in the conversation: stable callbacks in a stable object, since its rows are memoized.
const conversationMouse: ConversationMouse = { // A new object each render re-rendered every row, and every reply's markdown, each second.
selectTurn: useEvent((messageId: string) => turns.select(messageId)), const selectTurn = useEvent((messageId: string) => turns.select(messageId));
toggleFold: useEvent((id: string) => const toggleFold = useEvent((id: string) =>
setExpandedIds((previous) => { setExpandedIds((previous) => {
const next = new Set(previous); const next = new Set(previous);
if (!next.delete(id)) next.add(id); if (!next.delete(id)) next.add(id);
return next; return next;
}), }),
), );
loadEarlier: useEvent(() => loadEarlier()), const loadEarlierClick = useEvent(() => loadEarlier());
menu: useEvent((target: ConversationTarget) => openConversationMenu(target)), const openMenu = useEvent((target: ConversationTarget) => openConversationMenu(target));
openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)), const openTurnDiff = useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount));
click: useEvent((x: number, y: number) => openAt(x, y)), const click = useEvent((x: number, y: number) => openAt(x, y));
}; const conversationMouse = useMemo<ConversationMouse>(
() => ({ selectTurn, toggleFold, loadEarlier: loadEarlierClick, menu: openMenu, openTurnDiff, click }),
[selectTurn, toggleFold, loadEarlierClick, openMenu, openTurnDiff, click],
);
const copy = (label: string, text: string) => { const copy = (label: string, text: string) => {
void clipboard.copy(text); void clipboard.copy(text);
say(`Copied ${label}`); say(`Copied ${label}`);
@@ -1578,7 +1624,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
{panes.columnTabs.length > 1 ? ( {panes.columnTabs.length > 1 ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={panes.focusedPane === "column" ? colors.element : colors.panel}> <box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={panes.focusedPane === "column" ? colors.element : colors.panel}>
<Tabs <Tabs
tabs={panes.columnTabs.map((tab) => ({ id: tab.id, label: tab.label, closable: tab.kind !== "details", shorten: (room: number) => (tab.kind === "editor" ? truncatePath(tab.label, room) : truncateNumbered(tab.label, room)) }))} tabs={panes.columnTabs.map((tab) => ({ id: tab.id, label: tab.label, closable: tab.kind !== "details" && tab.kind !== "files", shorten: (room: number) => (tab.kind === "editor" || tab.kind === "preview" ? truncatePath(tab.label, room) : truncateNumbered(tab.label, room)) }))}
active={panes.columnTab} active={panes.columnTab}
focused={panes.focusedPane === "column"} focused={panes.focusedPane === "column"}
width={columnWidth - 2 - (placement === "side" && panes.terminal ? NEW_TAB_WIDTH : 0)} width={columnWidth - 2 - (placement === "side" && panes.terminal ? NEW_TAB_WIDTH : 0)}
@@ -1590,6 +1636,31 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
</box> </box>
) : null} ) : null}
{panes.columnTab === "details" ? detailsPanel(columnFills) : null} {panes.columnTab === "details" ? detailsPanel(columnFills) : null}
{panes.columnKind === "files" ? (
<FilesPanel
root={draft ? null : panel.cwd}
rows={files.rows}
selected={files.selected}
search={files.search}
width={columnWidth}
focused={panes.focusedPane === "column"}
loading={files.loadingRoot}
error={files.error}
onClick={(path) => {
panes.showFiles();
files.click(path);
}}
onQuery={files.onQuery}
onSubmit={files.submit}
onClickResult={(index) => {
panes.showFiles();
files.clickResult(index);
}}
/>
) : null}
{panes.previews.filter((preview) => preview.id === panes.columnTab).map((preview) => (
<FilePreview key={preview.id} session={session} threadId={threadId} cwd={preview.cwd} path={preview.path} width={columnWidth} focused={panes.focusedPane === "column"} scrollRef={previewScrollRef} />
))}
{panes.editors.map((editor) => ( {panes.editors.map((editor) => (
<box key={editor.program.id} flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab === editor.program.id}> <box key={editor.program.id} flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab === editor.program.id}>
<TerminalPane <TerminalPane
+113
View File
@@ -0,0 +1,113 @@
import { pathToFiletype, type ImageRenderable, type ScrollBoxRenderable } from "@opentui/core";
import type { ThreadId } from "@t3tools/contracts";
import { existsSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { useEffect, useRef, useState, type RefObject } from "react";
import type { T3Session } from "../client/session.ts";
import { previewKind, sizeLabel } from "../model/files.ts";
import { truncatePath } from "./text.ts";
import { colors, scrollbarOptions, useCodeStyle, useMarkdownStyle } from "./theme.ts";
type Loaded =
| { readonly kind: "text"; readonly text: string; readonly truncated: boolean; readonly bytes: number }
| { readonly kind: "image"; readonly bytes: Uint8Array }
| { readonly kind: "binary"; readonly bytes: number | null }
| { readonly kind: "error"; readonly message: string };
/** The fewest rows an image takes, and the most. */
const IMAGE_ROWS = 30;
/**
* A workspace file read-only in a tab of the column: source highlighted by its extension,
* markdown rendered, images drawn, and other binary files named with their size. Text comes
* through the server's readFile; images from disk when they're on this machine, else the server.
*/
export function FilePreview(props: { readonly session: T3Session; readonly threadId: ThreadId | undefined; readonly cwd: string; readonly path: string; readonly width: number; readonly focused: boolean; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
const { session, threadId, cwd, path } = props;
const codeStyle = useCodeStyle();
const markdownStyle = useMarkdownStyle();
const [loaded, setLoaded] = useState<Loaded | null>(null);
const kind = previewKind(path);
useEffect(() => {
let cancelled = false;
const done = (next: Loaded) => !cancelled && setLoaded(next);
const failed = (error: unknown) => done({ kind: "error", message: error instanceof Error ? error.message : String(error) });
const local = join(cwd, path);
const here = existsSync(local);
if (kind === "image") {
if (here) done({ kind: "image", bytes: readFileSync(local) });
else if (threadId) session.fetchWorkspaceFile(threadId, local).then((response) => response.arrayBuffer()).then((buffer) => done({ kind: "image", bytes: new Uint8Array(buffer) }), failed);
else failed(new Error("No thread to fetch the image through."));
} else {
session.readFile(cwd, path).then(
(file) => done({ kind: "text", text: file.contents, truncated: file.truncated, bytes: file.byteLength }),
(error: unknown) => {
if ((error as { failure?: string }).failure !== "binary_file") return failed(error);
if (here) return done({ kind: "binary", bytes: statSync(local).size });
if (!threadId) return done({ kind: "binary", bytes: null });
// Only the size, from the headers; the bytes aren't wanted.
session.fetchWorkspaceFile(threadId, local).then((response) => {
void response.body?.cancel();
const length = Number(response.headers.get("content-length"));
done({ kind: "binary", bytes: Number.isFinite(length) && length > 0 ? length : null });
}, () => done({ kind: "binary", bytes: null }));
},
);
}
return () => {
cancelled = true;
};
}, [session, threadId, cwd, path, kind]);
const inner = Math.max(10, props.width - 3);
return (
<box flexDirection="column" flexGrow={1} minHeight={0} backgroundColor={colors.panel}>
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1}>
<text fg={props.focused ? colors.text : colors.muted} wrapMode="none">{truncatePath(path, Math.max(8, inner - 10))}</text>
<box flexGrow={1} />
<text fg={colors.faint} wrapMode="none" flexShrink={0}>read-only</text>
</box>
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1} scrollbarOptions={scrollbarOptions()}>
{!loaded ? (
<text fg={colors.faint}>Loading…</text>
) : loaded.kind === "error" ? (
<text fg={colors.bad}>{`Could not read the file: ${loaded.message}`}</text>
) : loaded.kind === "binary" ? (
<text fg={colors.muted}>{loaded.bytes === null ? "Binary file" : `Binary file, ${sizeLabel(loaded.bytes)}`}</text>
) : loaded.kind === "image" ? (
<PreviewImage bytes={loaded.bytes} width={inner} />
) : (
<box flexDirection="column" flexShrink={0}>
{loaded.truncated ? <text fg={colors.warn}>{`Showing the start of a ${sizeLabel(loaded.bytes)} file.`}</text> : null}
{kind === "markdown" ? (
<markdown content={loaded.text} syntaxStyle={markdownStyle} conceal tableOptions={{ widthMode: "content", wrapMode: "word", cellPaddingX: 1, borderColor: colors.border }} />
) : (
<code content={loaded.text} {...(pathToFiletype(path) ? { filetype: pathToFiletype(path)! } : {})} syntaxStyle={codeStyle} fg={colors.text} wrapMode="none" />
)}
</box>
)}
</scrollbox>
</box>
);
}
/** An image fitted to the column, in the terminal's best image protocol; a note if it can't be drawn. */
function PreviewImage(props: { readonly bytes: Uint8Array; readonly width: number }) {
const image = useRef<ImageRenderable | null>(null);
const [size, setSize] = useState({ width: props.width, height: IMAGE_ROWS });
const [failed, setFailed] = useState(false);
if (failed) return <text fg={colors.muted}>{`Image, ${sizeLabel(props.bytes.length)}; it can't be drawn here.`}</text>;
return (
<image
ref={image}
source={props.bytes}
fit="fit"
protocol="auto"
width={size.width}
height={size.height}
onLoad={() => image.current && setSize(image.current.getFittedSize(props.width, IMAGE_ROWS))}
onError={() => setFailed(true)}
/>
);
}
+114
View File
@@ -0,0 +1,114 @@
import type { MouseEvent } from "@opentui/core";
import { useEffect, useState } from "react";
import { rootLabel, type FileRow } from "../model/files.ts";
import { ClickRow, wheelStep } from "./Button.tsx";
import { BAR } from "./edges.ts";
import { truncate, truncatePath } from "./text.ts";
import { colors } from "./theme.ts";
import type { FileSearch } from "./useFiles.ts";
/**
* The Files tab: the root on top, then the tree, or the `/` search's results in its place.
* Folders open with ▸/▾; git's M and ? sit on the right, a faint • on folders with changes
* inside, and what git ignores is faint.
*/
export function FilesPanel(props: {
readonly root: string | null;
readonly rows: readonly FileRow[];
readonly selected: string | null;
readonly search: FileSearch | null;
readonly width: number;
readonly focused: boolean;
readonly loading: boolean;
readonly error: string | null;
readonly onClick: (path: string) => void;
readonly onQuery: (value: string) => void;
readonly onSubmit: () => void;
readonly onClickResult: (index: number) => void;
}) {
const { rows, search, focused } = props;
const [height, setHeight] = useState(0);
const [top, setTop] = useState(0);
const count = search ? (search.results?.length ?? 0) : rows.length;
const at = search ? search.selected : Math.max(0, rows.findIndex((row) => row.kind !== "loading" && row.path === props.selected));
// The selection stays in view; the wheel scrolls past it until it moves again.
useEffect(() => {
setTop((current) => (at < current ? at : height > 0 && at >= current + height ? at - height + 1 : current));
}, [at, height]);
const start = Math.max(0, Math.min(top, count - height));
// The selection bar and a column of padding either side of the text.
const inner = Math.max(8, props.width - 3);
const selectedBg = focused ? colors.selectedBg : colors.element;
return (
<box flexDirection="column" flexGrow={1} minHeight={0} overflow="hidden" backgroundColor={colors.panel}>
<text fg={colors.muted} paddingLeft={1} wrapMode="none" flexShrink={0}>{props.root ? rootLabel(props.root, inner) : "No workspace"}</text>
{search?.editing ? (
<box border={["left"]} customBorderChars={BAR} borderColor={colors.accent} backgroundColor={colors.element} height={1} flexShrink={0}>
<input focused={focused} placeholder="Search files…" value={search.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.element} focusedBackgroundColor={colors.element} />
</box>
) : search ? (
<text fg={colors.accent} wrapMode="none" flexShrink={0}>{` /${search.query}`}</text>
) : null}
<box
flexDirection="column"
flexGrow={1}
minHeight={0}
overflow="hidden"
onSizeChange={function (this: { height: number }) {
setHeight(this.height);
}}
onMouseScroll={(event: MouseEvent) => {
const step = wheelStep(event);
if (step) setTop(Math.max(0, Math.min(count - height, start + step * 3)));
}}
>
{search ? (
search.results === null ? (
<text fg={colors.faint} paddingLeft={1}>Searching…</text>
) : search.results.length === 0 ? (
<text fg={colors.faint} paddingLeft={1}>{search.query.trim() ? "No matching files or folders." : "Type to search the workspace."}</text>
) : (
search.results.slice(start, start + height).map((entry, offset) => {
const index = start + offset;
const active = index === search.selected;
const label = `${entry.path}${entry.kind === "directory" ? "/" : ""}`;
return (
<ClickRow key={entry.path} flexDirection="row" paddingRight={1} selected={active} selectedBg={selectedBg} onPress={() => props.onClickResult(index)}>
<text fg={colors.accent} flexShrink={0} selectable={false}>{active ? "▌" : " "}</text>
<text fg={entry.ignored ? colors.faint : colors.text} wrapMode="none" selectable={false}>{truncatePath(label, inner)}</text>
</ClickRow>
);
})
)
) : props.error ? (
<text fg={colors.bad} paddingLeft={1}>{`Could not list the folder: ${props.error}`}</text>
) : props.loading ? (
<text fg={colors.faint} paddingLeft={1}>Loading…</text>
) : rows.length === 0 ? (
<text fg={colors.faint} paddingLeft={1}>No files.</text>
) : (
rows.slice(start, start + height).map((row) => <Row key={`${row.kind}:${row.path}`} row={row} inner={inner} selected={row.kind !== "loading" && row.path === props.selected} selectedBg={selectedBg} onClick={props.onClick} />)
)}
</box>
</box>
);
}
function Row(props: { readonly row: FileRow; readonly inner: number; readonly selected: boolean; readonly selectedBg: string; readonly onClick: (path: string) => void }) {
const { row, inner, selected } = props;
const indent = " ".repeat(row.depth);
if (row.kind === "loading") return <text fg={colors.faint} selectable={false}>{` ${indent} …`}</text>;
const glyph = row.kind === "directory" ? (row.expanded ? "▾ " : "▸ ") : " ";
const mark = row.marker ?? (row.changedInside ? "•" : "");
const name = truncate(row.name, Math.max(4, inner - indent.length - glyph.length - (mark ? mark.length + 1 : 0)));
return (
<ClickRow flexDirection="row" paddingRight={1} selected={selected} selectedBg={props.selectedBg} onPress={() => props.onClick(row.path)}>
<text fg={colors.accent} flexShrink={0} selectable={false}>{selected ? "▌" : " "}</text>
<text fg={colors.faint} flexShrink={0} selectable={false}>{`${indent}${glyph}`}</text>
<text fg={row.ignored ? colors.faint : colors.text} wrapMode="none" selectable={false}>{name}</text>
<box flexGrow={1} />
{mark ? <text fg={row.marker ? colors.muted : colors.faint} flexShrink={0} selectable={false}>{mark}</text> : null}
</ClickRow>
);
}
+28
View File
@@ -83,6 +83,7 @@ export const colors: Palette = { ...DARK };
export function applyTheme(theme: ThemeMode | Palette): void { export function applyTheme(theme: ThemeMode | Palette): void {
Object.assign(colors, theme === "light" ? LIGHT : theme === "dark" ? DARK : theme); Object.assign(colors, theme === "light" ? LIGHT : theme === "dark" ? DARK : theme);
markdownStyles = new WeakMap(); markdownStyles = new WeakMap();
codeStyles = new WeakMap();
} }
/** Dark or light, by the background's luminance; null if the terminal didn't say. */ /** Dark or light, by the background's luminance; null if the terminal didn't say. */
@@ -192,3 +193,30 @@ export function useMarkdownStyle(): SyntaxStyle {
markdownStyles.set(owner, style); markdownStyles.set(owner, style);
return style; return style;
} }
let codeStyles = new WeakMap<NativeResourceOwner, SyntaxStyle>();
/** Source files in the preview tab: the palette's few hues on the tree-sitter scopes that matter. */
export function useCodeStyle(): SyntaxStyle {
const owner = useRenderer().nativeScene;
let style = codeStyles.get(owner);
if (style) return style;
style = SyntaxStyle.fromStyles({
default: { fg: colors.text },
keyword: { fg: colors.input },
string: { fg: colors.good },
comment: { fg: colors.faint, italic: true },
number: { fg: colors.plan },
boolean: { fg: colors.plan },
constant: { fg: colors.plan },
function: { fg: colors.accent },
type: { fg: colors.info },
constructor: { fg: colors.info },
operator: { fg: colors.muted },
punctuation: { fg: colors.muted },
"markup.heading": { fg: colors.text, bold: true },
"markup.raw": { fg: colors.plan },
}, owner);
codeStyles.set(owner, style);
return style;
}
+1 -1
View File
@@ -20,7 +20,7 @@ export function markChip(composer: TextareaRenderable, start: number, end: numbe
} }
/** Inserts `label` at the cursor as a chip, apart from the words either side. */ /** Inserts `label` at the cursor as a chip, apart from the words either side. */
function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void { export function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void {
const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1]; const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1];
if (before && !/\s/.test(before)) composer.insertText(" "); if (before && !/\s/.test(before)) composer.insertText(" ");
const start = composer.cursorOffset; const start = composer.cursorOffset;
+11 -2
View File
@@ -5,7 +5,7 @@ import { useEffect, useRef, useState, type RefObject } from "react";
import type { T3Session } from "../client/session.ts"; import type { T3Session } from "../client/session.ts";
import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts"; import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
import { keys, type Binding } from "../model/keymap.ts"; import { keys, type Binding } from "../model/keymap.ts";
import { markChip } from "./useComposerChips.ts"; import { insertChip, markChip } from "./useComposerChips.ts";
import { useComposerPullRequests } from "./usePullRequests.ts"; import { useComposerPullRequests } from "./usePullRequests.ts";
/** /**
@@ -117,6 +117,15 @@ export function useComposerMenu(deps: {
deps.onChosen(item); deps.onChosen(item);
}; };
/** A file or folder mentioned from outside the menu (the Files tab): its chip at the cursor, as choosing it here puts it. */
const mention = (entry: ProjectEntry): boolean => {
const composer = composerRef.current;
const [item] = pathItems([entry]);
if (!composer || !item?.chip) return false;
insertChip(composer, item.chip, { sent: (item.replacement ?? "").trimEnd() });
sync();
return true;
};
/** The mentions still in this text, as the message's context. */ /** The mentions still in this text, as the message's context. */
const context = (text: string): OrchestrationMessageContext | undefined => messageContext(text, mentions.current.get(composerKey) ?? new Map()); const context = (text: string): OrchestrationMessageContext | undefined => messageContext(text, mentions.current.get(composerKey) ?? new Map());
/** The message went: its mentions go with it. */ /** The message went: its mentions go with it. */
@@ -143,5 +152,5 @@ export function useComposerMenu(deps: {
) )
: []; : [];
return { menu, selected, sync, pick: (at: number) => menu && choose(menu.items[at]), context, forget, remember, bindings }; return { menu, selected, sync, mention, pick: (at: number) => menu && choose(menu.items[at]), context, forget, remember, bindings };
} }
+284
View File
@@ -0,0 +1,284 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react";
import type { T3Session } from "../client/session.ts";
import type { ChangedFile } from "../model/details.ts";
import { fileRows, parentOf } from "../model/files.ts";
import { keys } from "../model/keymap.ts";
/** As many results as the web's file search shows. */
const SEARCH_LIMIT = 200;
/** Re-lists after a burst of changes settle. */
const REFRESH_DELAY_MS = 300;
/** A workspace's tree as this run has seen it: the folders listed, which are open, and the selection. */
interface Workspace {
readonly directories: ReadonlyMap<string, readonly ProjectEntry[]>;
readonly expanded: ReadonlySet<string>;
readonly ignored: ReadonlySet<string>;
readonly selected: string | null;
}
const EMPTY: Workspace = { directories: new Map(), expanded: new Set(), ignored: new Set(), selected: null };
export interface FileSearch {
readonly query: string;
/** The query line has the keys. */
readonly editing: boolean;
/** null while the search runs. */
readonly results: readonly ProjectEntry[] | null;
readonly selected: number;
}
/**
* The Files tab: the workspace's folders listed lazily as they open, with git's marks and
* ignored entries, a `/` search over the workspace, and the keys that open, preview, mention
* and copy what's selected. Each workspace keeps its tree for the run.
*/
export function useFiles(deps: {
readonly session: T3Session;
readonly live: boolean;
/** The thread's worktree, else its project's root. */
readonly cwd: string | null;
/** The tab is on screen: the root lists the first time it is. */
readonly visible: boolean;
/** The working tree's changes, as the Changes list has them. */
readonly changes: readonly ChangedFile[];
/** A turn runs; one finishing re-lists the open folders. */
readonly working: boolean;
/** The server answers listIgnoredFiles. */
readonly ignoredListing: boolean;
readonly open: (path: string) => void;
readonly preview: (path: string) => void;
readonly mention: (path: string, kind: ProjectEntry["kind"]) => void;
readonly copy: (path: string) => void;
/** Gives the keys back. */
readonly leave: () => void;
readonly say: (text: string, bad?: boolean) => void;
}) {
const { session, cwd, visible, live, say } = deps;
const [workspaces, setWorkspaces] = useState<ReadonlyMap<string, Workspace>>(new Map());
/** Folders being listed, as `cwd\0path`. */
const [loading, setLoading] = useState<ReadonlySet<string>>(new Set());
const [rootError, setRootError] = useState<{ readonly cwd: string; readonly message: string } | null>(null);
const [search, setSearch] = useState<FileSearch | null>(null);
const workspace = (cwd ? workspaces.get(cwd) : undefined) ?? EMPTY;
const update = (at: string, change: (previous: Workspace) => Workspace) => setWorkspaces((previous) => new Map(previous).set(at, change(previous.get(at) ?? EMPTY)));
const inFlight = useRef(new Set<string>());
const list = (at: string, path: string) => {
const key = `${at}\0${path}`;
if (inFlight.current.has(key)) return;
inFlight.current.add(key);
setLoading((previous) => new Set(previous).add(key));
session.listEntries(at, path).then(
(entries) => {
// A folder's listing can include deeper paths; this one shows its own children.
update(at, (previous) => ({ ...previous, directories: new Map(previous.directories).set(path, entries.filter((entry) => parentOf(entry.path) === path)) }));
if (path === "") setRootError(null);
},
(error) => (path === "" ? setRootError({ cwd: at, message: messageOf(error) }) : say(`Could not list ${path}: ${messageOf(error)}`, true)),
).finally(() => {
inFlight.current.delete(key);
setLoading((previous) => {
const next = new Set(previous);
next.delete(key);
return next;
});
});
};
const listIgnored = (at: string) => {
if (!deps.ignoredListing) return;
session.listIgnoredFiles(at).then(
(files) => update(at, (previous) => ({ ...previous, ignored: new Set(files.map((file) => file.path)) })),
() => {},
);
};
/** Lists again the root and every open folder that's listed, and what git ignores. */
const refresh = () => {
if (!cwd) return;
for (const path of ["", ...workspace.expanded]) if (path === "" || workspace.directories.has(path)) list(cwd, path);
listIgnored(cwd);
if (search?.query.trim()) runSearch(search.query);
};
// The root lists the first time the tab shows for a workspace; after that, showing it re-lists.
const listed = cwd !== null && workspace.directories.has("");
useEffect(() => {
if (!visible || !cwd || !live) return;
if (!listed) {
list(cwd, "");
listIgnored(cwd);
} else refresh();
// eslint-disable-next-line react-hooks/exhaustive-deps -- runs as the tab shows, or the workspace changes.
}, [visible, cwd, live]);
// A turn finishing, or git's changes moving, re-lists the open folders while the tab shows.
const changesKey = deps.changes.map((file) => `${file.status}${file.path}`).join("\n");
const settled = useRef({ changesKey, working: deps.working });
useEffect(() => {
const previous = settled.current;
settled.current = { changesKey, working: deps.working };
if (!visible || !listed || (previous.changesKey === changesKey && !(previous.working && !deps.working))) return;
const timer = setTimeout(refresh, REFRESH_DELAY_MS);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps -- runs when the changes or the turn do.
}, [changesKey, deps.working]);
const rows = useMemo(
() =>
fileRows({
directories: workspace.directories,
expanded: workspace.expanded,
loading: new Set([...loading].flatMap((key) => (cwd && key.startsWith(`${cwd}\0`) ? [key.slice(cwd.length + 1)] : []))),
ignored: workspace.ignored,
changes: deps.changes,
}),
[workspace, loading, cwd, deps.changes],
);
const entries = rows.filter((row) => row.kind !== "loading");
const selectedIndex = Math.max(0, entries.findIndex((row) => row.path === workspace.selected));
const selected = entries[selectedIndex];
const select = (path: string) => cwd && update(cwd, (previous) => ({ ...previous, selected: path }));
const setExpanded = (path: string, open: boolean) => {
if (!cwd) return;
update(cwd, (previous) => {
const expanded = new Set(previous.expanded);
if (open) expanded.add(path);
else expanded.delete(path);
return { ...previous, expanded };
});
if (open && !workspace.directories.has(path)) list(cwd, path);
};
const move = (delta: number) => {
const next = entries[Math.max(0, Math.min(entries.length - 1, selectedIndex + delta))];
if (next) select(next.path);
};
/** l: opens a folder, or steps into one already open; opens a file. */
const forward = () => {
if (!selected) return;
if (selected.kind === "file") return deps.open(selected.path);
if (!selected.expanded) return setExpanded(selected.path, true);
const child = entries[selectedIndex + 1];
if (child && parentOf(child.path) === selected.path) select(child.path);
};
/** h: closes a folder, or goes to the folder it's in. */
const back = () => {
if (!selected) return;
if (selected.kind === "directory" && selected.expanded) return setExpanded(selected.path, false);
const parent = parentOf(selected.path);
if (parent) select(parent);
};
/** A click: selects, opens or closes a folder, and opens a file already selected. */
const click = (path: string) => {
const row = entries.find((candidate) => candidate.path === path);
if (!row) return;
const wasSelected = selected?.path === path;
select(path);
if (row.kind === "directory") setExpanded(path, !row.expanded);
else if (wasSelected) deps.open(path);
};
// Search: debounced as the composer's @ search is.
const runSearch = (query: string) => {
const at = cwd;
if (!at) return;
session.searchEntries(at, query.trim(), SEARCH_LIMIT).then(
(results) => setSearch((previous) => (previous?.query === query ? { ...previous, results: results.filter((entry) => !entry.path.split("/").includes(".git")) } : previous)),
(error) => {
setSearch((previous) => (previous?.query === query ? { ...previous, results: [] } : previous));
say(`Search failed: ${messageOf(error)}`, true);
},
);
};
useEffect(() => setSearch(null), [cwd]);
const query = search?.query ?? "";
useEffect(() => {
if (!query.trim()) return;
const timer = setTimeout(() => runSearch(query), 120);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps -- runs as the query changes.
}, [query, cwd]);
const onQuery = (value: string) => setSearch((previous) => ({ query: value, editing: previous?.editing ?? true, results: value.trim() ? null : [], selected: 0 }));
const results = search?.results ?? [];
const result = results[Math.min(search?.selected ?? 0, results.length - 1)];
const moveResult = (delta: number) => setSearch((previous) => previous && { ...previous, selected: Math.max(0, Math.min(results.length - 1, previous.selected + delta)) });
const clearSearch = () => setSearch(null);
/** A folder found by search shows in the tree, open, its parents open above it. */
const reveal = (path: string) => {
if (!cwd) return;
const parts = path.split("/");
const folders = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
update(cwd, (previous) => ({ ...previous, expanded: new Set([...previous.expanded, ...folders]), selected: path }));
for (const folder of folders) if (!workspace.directories.has(folder)) list(cwd, folder);
clearSearch();
};
const openResult = (entry: ProjectEntry | undefined) => {
if (!entry) return;
if (entry.kind === "directory") return reveal(entry.path);
setSearch((previous) => previous && { ...previous, editing: false });
deps.open(entry.path);
};
const target = search ? result : selected;
const mention = () => target && deps.mention(target.path, target.kind);
const copy = () => target && deps.copy(target.path);
const preview = () => target?.kind === "file" && deps.preview(target.path);
const startSearch = () => setSearch((previous) => ({ query: previous?.query ?? "", editing: true, results: previous?.results ?? [], selected: previous?.selected ?? 0 }));
/** While the query line has the keys: what it doesn't type. */
const searchKeys = keys(
{ keys: ["↓", "ctrl+n"], label: "↑/↓", run: () => moveResult(1), hint: "move" },
{ keys: ["↑", "ctrl+p"], run: () => moveResult(-1) },
// The query line's own submit opens it.
{ keys: [], label: "enter", hint: "open" },
{ keys: ["tab"], run: () => setSearch((previous) => previous && { ...previous, editing: false }), hint: "results" },
{ keys: ["esc"], run: clearSearch, hint: "clear" },
);
/** While the results have the keys. */
const resultKeys = keys(
{ keys: ["j", "↓"], label: "j/k", run: () => moveResult(1), hint: "move" },
{ keys: ["k", "↑"], run: () => moveResult(-1) },
{ keys: ["enter", "l", "→"], run: () => openResult(result), hint: "open" },
{ keys: ["m"], run: mention, hint: "mention" },
{ keys: ["y"], run: copy, hint: "copy path" },
{ keys: ["p"], run: preview, hint: "preview" },
{ keys: ["/"], run: startSearch, hint: "search" },
{ keys: ["g"], run: () => moveResult(-results.length) },
{ keys: ["G"], run: () => moveResult(results.length) },
{ keys: ["esc"], run: clearSearch, hint: "clear" },
);
const treeKeys = keys(
{ keys: ["j", "↓"], label: "j/k", run: () => move(1), hint: "move" },
{ keys: ["k", "↑"], run: () => move(-1) },
{ keys: ["l", "enter", "→"], run: forward, hint: "open" },
{ keys: ["h", "←"], run: back },
{ keys: ["/"], run: startSearch, hint: "search" },
{ keys: ["m"], run: mention, hint: "mention" },
{ keys: ["y"], run: copy, hint: "copy path" },
{ keys: ["p"], run: preview, hint: "preview" },
{ keys: ["r"], run: refresh, hint: "refresh" },
{ keys: ["g"], run: () => move(-entries.length) },
{ keys: ["G"], run: () => move(entries.length) },
{ keys: ["esc"], run: deps.leave, hint: "back" },
);
return {
rows,
selected: selected?.path ?? null,
search,
loadingRoot: !listed && cwd !== null && (loading.has(`${cwd}\0`) || !rootError),
error: rootError?.cwd === cwd ? rootError.message : null,
click,
onQuery,
/** Enter in the query line: opens the highlighted result. */
submit: () => openResult(result),
/** A click on a search result: selects it, or opens it once selected. */
clickResult: (index: number) => {
if (index === search?.selected && !search.editing) return openResult(results[index]);
setSearch((previous) => previous && { ...previous, editing: false, selected: index });
},
keys: search?.editing ? searchKeys : search ? resultKeys : treeKeys,
};
}
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
+46 -16
View File
@@ -14,6 +14,7 @@ const PANE_ORDER: readonly PaneFocus[] = ["message", "drawer", "column"];
/** How long ctrl+\ waits for the key after it. */ /** How long ctrl+\ waits for the key after it. */
const PREFIX_MS = 2000; const PREFIX_MS = 2000;
const DETAILS = "details"; const DETAILS = "details";
const FILES = "files";
/** The column's tab for the shown terminal, in side placement. */ /** The column's tab for the shown terminal, in side placement. */
const TERMINAL = "terminal"; const TERMINAL = "terminal";
type LocalProgram = Extract<PaneProgram, { kind: "local" }>; type LocalProgram = Extract<PaneProgram, { kind: "local" }>;
@@ -27,16 +28,22 @@ export interface EditorProgram {
export interface EditorTab extends EditorProgram { export interface EditorTab extends EditorProgram {
readonly path: string; readonly path: string;
} }
/** A workspace file shown read-only in a tab of the column: its path relative to `cwd`. */
export interface PreviewTab {
readonly id: string;
readonly path: string;
readonly cwd: string;
}
export interface ColumnTab { export interface ColumnTab {
readonly id: string; readonly id: string;
readonly label: string; readonly label: string;
readonly kind: "details" | "editor" | "terminal"; readonly kind: "details" | "files" | "editor" | "preview" | "terminal";
} }
/** /**
* The panes around the conversation: each thread's terminals (in the drawer below it, or as * The panes around the conversation: each thread's terminals (in the drawer below it, or as
* tabs of the right-hand column), files in $EDITOR in the column's tabs, and the message in * tabs of the right-hand column), the Files tab, files in $EDITOR or previewed in the column's
* $EDITOR in the composer's place. Which one has the keys, and the ctrl+\ prefix that moves * tabs, and the message in $EDITOR in the composer's place. Which one has the keys, and the ctrl+\ prefix that moves
* them, picks tabs, closes and zooms. * them, picks tabs, closes and zooms.
*/ */
export function usePanes(deps: { export function usePanes(deps: {
@@ -67,6 +74,7 @@ export function usePanes(deps: {
/** Terminals this run has shown, which the strip under the message box names while the drawer is hidden. */ /** Terminals this run has shown, which the strip under the message box names while the drawer is hidden. */
const [seen, setSeen] = useState<ReadonlySet<string>>(new Set()); const [seen, setSeen] = useState<ReadonlySet<string>>(new Set());
const [editors, setEditors] = useState<readonly EditorTab[]>([]); const [editors, setEditors] = useState<readonly EditorTab[]>([]);
const [previews, setPreviews] = useState<readonly PreviewTab[]>([]);
const [message, setMessage] = useState<EditorProgram | null>(null); const [message, setMessage] = useState<EditorProgram | null>(null);
const [tab, setTab] = useState<string>(DETAILS); const [tab, setTab] = useState<string>(DETAILS);
const [target, setTarget] = useState<PaneFocus>("drawer"); const [target, setTarget] = useState<PaneFocus>("drawer");
@@ -93,19 +101,22 @@ export function usePanes(deps: {
const terminalTabId = (terminalId: string) => `${TERMINAL}:${terminalId}`; const terminalTabId = (terminalId: string) => `${TERMINAL}:${terminalId}`;
const columnTabs: ColumnTab[] = [ const columnTabs: ColumnTab[] = [
{ id: DETAILS, label: "Details", kind: "details" }, { id: DETAILS, label: "Details", kind: "details" },
{ id: FILES, label: "Files", kind: "files" },
...editors.map((editor): ColumnTab => ({ id: editor.program.id, label: editor.path, kind: "editor" })), ...editors.map((editor): ColumnTab => ({ id: editor.program.id, label: editor.path, kind: "editor" })),
...previews.map((preview): ColumnTab => ({ id: preview.id, label: preview.path, kind: "preview" })),
...(side && terminal ? tabs.map((candidate): ColumnTab => ({ id: terminalTabId(candidate.terminalId), label: candidate.label, kind: "terminal" })) : []), ...(side && terminal ? tabs.map((candidate): ColumnTab => ({ id: terminalTabId(candidate.terminalId), label: candidate.label, kind: "terminal" })) : []),
]; ];
const columnTab = tab === TERMINAL && side && terminal ? terminalTabId(terminal.terminalId) : editors.some((editor) => editor.program.id === tab) ? tab : DETAILS; const columnTab = tab === TERMINAL && side && terminal ? terminalTabId(terminal.terminalId) : tab === FILES || editors.some((editor) => editor.program.id === tab) || previews.some((preview) => preview.id === tab) ? tab : DETAILS;
const activeColumnTab = columnTabs.find((candidate) => candidate.id === columnTab)!; const activeColumnTab = columnTabs.find((candidate) => candidate.id === columnTab)!;
const programTabs = columnTabs.filter((candidate) => candidate.kind !== "details"); /** The tabs that hold something of their own: programs and previews. */
const programTabs = columnTabs.filter((candidate) => candidate.kind !== "details" && candidate.kind !== "files");
const shown: Record<PaneFocus, boolean> = { const shown: Record<PaneFocus, boolean> = {
message: message !== null, message: message !== null,
drawer: terminal !== null && !side, drawer: terminal !== null && !side,
column: column && columnTab !== DETAILS, column: column && columnTab !== DETAILS,
}; };
/** What focus can move to: open panes, and the column while it holds a program, even hidden. */ /** What focus can move to: open panes, and the column while it shows Files or holds a program, even hidden. */
const open: Record<PaneFocus, boolean> = { ...shown, column: programTabs.length > 0 }; const open: Record<PaneFocus, boolean> = { ...shown, column: shown.column || programTabs.length > 0 };
const available = PANE_ORDER.filter((pane) => open[pane]); const available = PANE_ORDER.filter((pane) => open[pane]);
const focusedPane = focused && shown[target] ? target : null; const focusedPane = focused && shown[target] ? target : null;
const zoomShown = zoomed !== null && (zoomed === "column" ? column : shown[zoomed]); const zoomShown = zoomed !== null && (zoomed === "column" ? column : shown[zoomed]);
@@ -130,12 +141,12 @@ export function usePanes(deps: {
}; };
}, [column, sockets]); }, [column, sockets]);
/** Gives a pane the keys; the column on `tab`, or the program tab it showed last. */ /** Gives a pane the keys; the column on `tab`, or the tab it showed last, or Files. */
const enter = (pane: PaneFocus, tab?: string) => { const enter = (pane: PaneFocus, tab?: string) => {
if (pane === "column" && tab) showColumnTab(tab); if (pane === "column" && tab) showColumnTab(tab);
else if (pane === "column" && columnTab === DETAILS) { else if (pane === "column" && columnTab === DETAILS) {
const next = programTabs.find((candidate) => candidate.id === lastProgramTab.current || (lastProgramTab.current === TERMINAL && candidate.kind === "terminal")) ?? programTabs[0]; const next = columnTabs.find((candidate) => candidate.id === lastProgramTab.current || (lastProgramTab.current === TERMINAL && candidate.kind === "terminal")) ?? programTabs[0];
if (next) showColumnTab(next.id); showColumnTab(next?.id ?? FILES);
} else if (pane === "column") showColumnTab(columnTab); } else if (pane === "column") showColumnTab(columnTab);
setTarget(pane); setTarget(pane);
deps.focus(true); deps.focus(true);
@@ -177,7 +188,7 @@ export function usePanes(deps: {
const hideTerminal = () => { const hideTerminal = () => {
if (!threadId || !drawer) return; if (!threadId || !drawer) return;
setDrawer(threadId, { ...drawer, open: false }); setDrawer(threadId, { ...drawer, open: false });
if (side) tabGone(editors.length > 0); if (side) tabGone(editors.length + previews.length > 0);
}; };
const terminalShown = terminal !== null && (!side || (column && activeColumnTab.kind === "terminal")); const terminalShown = terminal !== null && (!side || (column && activeColumnTab.kind === "terminal"));
/** ctrl+j: hides the terminal when it shows, or shows the last one, or finds one. */ /** ctrl+j: hides the terminal when it shows, or shows the last one, or finds one. */
@@ -201,7 +212,7 @@ export function usePanes(deps: {
rest.delete(gone.threadId); rest.delete(gone.threadId);
return rest; return rest;
}); });
if (side && gone.threadId === threadId) tabGone(editors.length > 0); if (side && gone.threadId === threadId) tabGone(editors.length + previews.length > 0);
} }
if (note) say(note); if (note) say(note);
}; };
@@ -222,9 +233,20 @@ export function usePanes(deps: {
}; };
const editorClosed = (id: string, note?: string) => { const editorClosed = (id: string, note?: string) => {
setEditors((previous) => previous.filter((editor) => editor.program.id !== id)); setEditors((previous) => previous.filter((editor) => editor.program.id !== id));
tabGone(editors.length > 1 || (side && terminal !== null)); tabGone(editors.length > 1 || previews.length > 0 || (side && terminal !== null));
if (note) say(note); if (note) say(note);
}; };
/** A file read-only in a tab of its own in the column, with the keys. */
const openPreview = (path: string, cwd: string) => {
const id = `preview:${cwd}:${path}`;
setPreviews((previous) => (previous.some((preview) => preview.id === id) ? previous : [...previous, { id, path, cwd }]));
enter("column", id);
};
/** A preview closes back to Files, which it was opened from. */
const closePreview = (id: string) => {
setPreviews((previous) => previous.filter((preview) => preview.id !== id));
if (columnTab === id) setTab(FILES);
};
/** The message in $EDITOR, in the composer's place. */ /** The message in $EDITOR, in the composer's place. */
const openMessage = (next: EditorProgram) => { const openMessage = (next: EditorProgram) => {
setMessage(next); setMessage(next);
@@ -243,10 +265,12 @@ export function usePanes(deps: {
const terminalTab = tabs.find((candidate) => candidate.terminalId === id || terminalTabId(candidate.terminalId) === id); const terminalTab = tabs.find((candidate) => candidate.terminalId === id || terminalTabId(candidate.terminalId) === id);
if (terminalTab) return deps.closeTerminal(terminalTab); if (terminalTab) return deps.closeTerminal(terminalTab);
const editor = editors.find((candidate) => candidate.program.id === id); const editor = editors.find((candidate) => candidate.program.id === id);
if (editor) quitEditor(editor, basename(editor.path), "column"); if (editor) return quitEditor(editor, basename(editor.path), "column");
if (previews.some((preview) => preview.id === id)) closePreview(id);
}; };
const closeFocused = () => { const closeFocused = () => {
if (focusedPane === "drawer" && terminal) return closeTab(terminal.terminalId); if (focusedPane === "drawer" && terminal) return closeTab(terminal.terminalId);
if (focusedPane === "column" && columnTab === FILES) return say("Files stays; d hides the column.", true);
if (focusedPane === "column") return closeTab(columnTab); if (focusedPane === "column") return closeTab(columnTab);
if (focusedPane === "message" && message) return quitEditor(message, "the message", "message"); if (focusedPane === "message" && message) return quitEditor(message, "the message", "message");
say(deps.detailsFocused ? "Details stays; d hides the column." : "No pane has the keys; ctrl+\\ tab moves them to one.", true); say(deps.detailsFocused ? "Details stays; d hides the column." : "No pane has the keys; ctrl+\\ tab moves them to one.", true);
@@ -270,7 +294,7 @@ export function usePanes(deps: {
if (terminal) return side ? enter("column") : enter("drawer"); if (terminal) return side ? enter("column") : enter("drawer");
toggleTerminal(); toggleTerminal();
}; };
const focusColumn = () => (open.column ? enter("column") : say("Nothing runs in the column; o on a changed file opens one.", true)); const focusColumn = () => enter("column");
/** 1…9: a tab of the focused strip, the column's or else the drawer's. */ /** 1…9: a tab of the focused strip, the column's or else the drawer's. */
const pickTab = (index: number) => { const pickTab = (index: number) => {
if (focusedPane !== "column" && !deps.detailsFocused) return selectTab(index); if (focusedPane !== "column" && !deps.detailsFocused) return selectTab(index);
@@ -315,7 +339,7 @@ export function usePanes(deps: {
{ keys: ["esc"], run: () => {}, hint: "cancel" }, { keys: ["esc"], run: () => {}, hint: "cancel" },
); );
/** Where the keys are, by name. */ /** Where the keys are, by name. */
const focusedName = focusedPane === "message" ? "message" : focusedPane === "drawer" ? terminal?.label : focusedPane === "column" ? (activeColumnTab.kind === "editor" ? basename(activeColumnTab.label) : activeColumnTab.label) : undefined; const focusedName = focusedPane === "message" ? "message" : focusedPane === "drawer" ? terminal?.label : focusedPane === "column" ? (activeColumnTab.kind === "editor" || activeColumnTab.kind === "preview" ? basename(activeColumnTab.label) : activeColumnTab.label) : undefined;
/** The hint bar while a pane has the keys. */ /** The hint bar while a pane has the keys. */
const focusedKeys: Binding[] = focusedName const focusedKeys: Binding[] = focusedName
? [ ? [
@@ -337,10 +361,13 @@ export function usePanes(deps: {
/** Terminals this run showed that still run, while the terminal is hidden. */ /** Terminals this run showed that still run, while the terminal is hidden. */
running: terminal ? [] : tabs.filter((candidate) => seen.has(key(candidate))), running: terminal ? [] : tabs.filter((candidate) => seen.has(key(candidate))),
editors, editors,
previews,
modified, modified,
message, message,
columnTabs, columnTabs,
columnTab, columnTab,
/** What the column's shown tab is. */
columnKind: activeColumnTab.kind,
showColumnTab, showColumnTab,
focusedPane, focusedPane,
/** Whether a terminal has the keys, in the drawer or the column. */ /** Whether a terminal has the keys, in the drawer or the column. */
@@ -358,6 +385,9 @@ export function usePanes(deps: {
openEditor, openEditor,
editorOpened, editorOpened,
editorClosed, editorClosed,
openPreview,
/** Shows Files and gives it the keys. */
showFiles: () => enter("column", FILES),
openMessage, openMessage,
messageClosed: () => setMessage(null), messageClosed: () => setMessage(null),
keys: { prefix: prefixKey, afterPrefix: prefixKeys, focused: focusedKeys, commands }, keys: { prefix: prefixKey, afterPrefix: prefixKeys, focused: focusedKeys, commands },
+321
View File
@@ -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<ReturnType<typeof renderApp>> | null = null;
const open = async (...args: Parameters<typeof renderApp>) => (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<ReturnType<typeof renderApp>>;
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<string, readonly unknown[]> = {
"": [
{ 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<string, unknown> = {}, more: Parameters<typeof fakeSession>[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<void>((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");
});
});
+5 -3
View File
@@ -32,7 +32,7 @@ export interface Call {
/** /**
* A session that serves fixed state and records every other call. Watchers get one live * 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 * 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( export function fakeSession(
state: { state: {
@@ -41,7 +41,7 @@ export function fakeSession(
readonly status?: ConnectionStatus; readonly status?: ConnectionStatus;
/** Git status for every folder; loading by default. */ /** Git status for every folder; loading by default. */
readonly vcs?: unknown; readonly vcs?: unknown;
readonly results?: Record<string, unknown>; readonly results?: Record<string, unknown | ((...args: never[]) => unknown)>;
/** The thread's terminals on the server, and what attaching to one streams. */ /** The thread's terminals on the server, and what attaching to one streams. */
readonly terminals?: readonly unknown[]; readonly terminals?: readonly unknown[];
readonly terminalEvents?: readonly unknown[]; readonly terminalEvents?: readonly unknown[];
@@ -86,7 +86,9 @@ export function fakeSession(
calls.push({ method: name, args }); calls.push({ method: name, args });
if (name.startsWith("watch") || name.startsWith("on")) return () => {}; if (name.startsWith("watch") || name.startsWith("on")) return () => {};
const failure = state.failures?.[name]; 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; }) as unknown as T3Session;
+2 -2
View File
@@ -70,10 +70,10 @@ describe("links and paths in replies", () => {
const app = await open({ width: 200, session: fakeSession({ snapshot, projection: withReply("I changed `src/a.ts:3` and left src/missing.ts alone.", false) }) }); const app = await open({ width: 200, session: fakeSession({ snapshot, projection: withReply("I changed `src/a.ts:3` and left src/missing.ts alone.", false) }) });
const missing = app.find("missing.ts"); const missing = app.find("missing.ts");
await app.click(missing.x, missing.y); await app.click(missing.x, missing.y);
expect(app.frame()).not.toContain("Details "); expect(app.frame()).not.toContain("missing.ts ✕");
const path = app.find("a.ts:3"); const path = app.find("a.ts:3");
await app.click(path.x, path.y); await app.click(path.x, path.y);
expect(app.frame()).toContain("Details src/a.ts ✕"); expect(app.frame()).toContain("Details Files src/a.ts ✕");
expect(app.hints()).toStartWith("keys: a.ts"); expect(app.hints()).toStartWith("keys: a.ts");
}); });
+19 -19
View File
@@ -300,18 +300,18 @@ describe("terminal drawer", () => {
}); });
test("Pane: move terminal to the side puts each terminal in the right column's one strip of tabs, and stays", async () => { test("Pane: move terminal to the side puts each terminal in the right column's one strip of tabs, and stays", async () => {
const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, session: withTerminals() }); const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 54 }, session: withTerminals() });
await app.press("k", { ctrl: true }); await app.press("k", { ctrl: true });
await app.type("move terminal to the side"); await app.type("move terminal to the side");
await app.press("return"); await app.press("return");
expect((await loadLayout()).terminalPlacement).toBe("side"); expect((await loadLayout()).terminalPlacement).toBe("side");
await app.press("j", { ctrl: true }); await app.press("j", { ctrl: true });
expect(app.frame()).toContain("Details Terminal 1 ✕ Terminal 2 + new"); expect(app.frame()).toContain("Details Files Terminal 1 ✕ Terminal 2 + new");
expect(app.frame().match(/Terminal 2/g)).toHaveLength(1); expect(app.frame().match(/Terminal 2/g)).toHaveLength(1);
expect(app.find("Details Terminal 1").x).toBeGreaterThan(200 - 46 - 1); expect(app.find("Details Files Terminal 1").x).toBeGreaterThan(200 - 54 - 1);
expect(app.frame()).toContain("user@host"); expect(app.frame()).toContain("user@host");
expect(app.hints()).toBe(keysOn("Terminal 1")); expect(app.hints()).toBe(keysOn("Terminal 1"));
// The prefix's 1…9 count the column's tabs; Details gives the keys back. // The prefix's 1…9 count the column's tabs (Details, Files, then the rest); Details gives the keys back.
await prefix(app, "1"); await prefix(app, "1");
expect(app.frame()).not.toContain("user@host"); expect(app.frame()).not.toContain("user@host");
expect(app.frame()).toContain("/workspace/project"); expect(app.frame()).toContain("/workspace/project");
@@ -319,7 +319,7 @@ describe("terminal drawer", () => {
await prefix(app, "l"); await prefix(app, "l");
expect(app.frame()).toContain("user@host"); expect(app.frame()).toContain("user@host");
expect(app.hints()).toBe(keysOn("Terminal 1")); expect(app.hints()).toBe(keysOn("Terminal 1"));
await prefix(app, "3"); await prefix(app, "4");
expect(attached(app).at(-1)).toBe("term-2"); expect(attached(app).at(-1)).toBe("term-2");
expect(app.hints()).toBe(keysOn("Terminal 2")); expect(app.hints()).toBe(keysOn("Terminal 2"));
await app.press("j", { ctrl: true }); await app.press("j", { ctrl: true });
@@ -453,17 +453,17 @@ describe("editing a changed file", () => {
const app = await open({ width: 200, session: fakeSession({ vcs, snapshot }) }); const app = await open({ width: 200, session: fakeSession({ vcs, snapshot }) });
await app.press("l"); await app.press("l");
await app.press("o"); await app.press("o");
expect(app.frame()).toContain("Details README.md ✕"); expect(app.frame()).toContain("Details Files README.md ✕");
expect(app.find("Details README.md").x).toBeGreaterThan(200 - 38 - 1); expect(app.find("Details Files README.md").x).toBeGreaterThan(200 - 38 - 1);
expect(app.hints()).toBe(keysOn("README.md")); expect(app.hints()).toBe(keysOn("README.md"));
// Back to Details and to the editor again, with it still running. // Back to Details and to the editor again, with it still running.
await prefix(app, "1"); await prefix(app, "1");
expect(app.frame()).toContain("Changes"); expect(app.frame()).toContain("Changes");
const tab = app.find("Details README.md"); const tab = app.find("Details Files README.md");
await app.click(tab.x + "Details ".length, tab.y); await app.click(tab.x + "Details Files ".length, tab.y);
expect(app.hints()).toBe(keysOn("README.md")); expect(app.hints()).toBe(keysOn("README.md"));
await waitFor(() => !app.frame().includes("Details README.md")); await waitFor(() => !app.frame().includes("Details Files README.md"));
expect(app.frame()).not.toContain("Details README.md"); expect(app.frame()).not.toContain("Details Files README.md");
expect(app.frame()).toContain("Changes"); expect(app.frame()).toContain("Changes");
}); });
@@ -473,27 +473,27 @@ describe("editing a changed file", () => {
const app = await open({ width: 200, session: fakeSession({ vcs: twoFiles, snapshot }) }); const app = await open({ width: 200, session: fakeSession({ vcs: twoFiles, snapshot }) });
await editBoth(app); await editBoth(app);
// The column's default width cuts them; wider, they fit. // The column's default width cuts them; wider, they fit.
expect(app.frame()).toContain("Details README.md …nalPane.tsx ✕"); expect(app.frame()).toContain("Details Files …DME.md …ne.tsx ✕");
await app.mockMouse.drag(200 - 39, 10, 200 - 60, 10); await app.mockMouse.drag(200 - 39, 10, 200 - 68, 10);
await app.settle(100); await app.settle(100);
expect(app.frame()).toContain("Details README.md src/ui/deep/TerminalPane.tsx ✕"); expect(app.frame()).toContain("Details Files README.md src/ui/deep/TerminalPane.tsx ✕");
expect(app.frame()).toContain("src/ui/deep/TerminalPane.tsx"); expect(app.frame()).toContain("src/ui/deep/TerminalPane.tsx");
expect(app.hints()).toBe(keysOn("TerminalPane.tsx")); expect(app.hints()).toBe(keysOn("TerminalPane.tsx"));
await prefix(app, "2"); await prefix(app, "3");
expect(app.hints()).toBe(keysOn("README.md")); expect(app.hints()).toBe(keysOn("README.md"));
// An editor that can't be asked to quit isn't closed under you. // An editor that can't be asked to quit isn't closed under you.
await prefix(app, "x"); await prefix(app, "x");
expect(app.hints()).toStartWith("Quit README.md from inside it"); expect(app.hints()).toStartWith("Quit README.md from inside it");
expect(app.frame()).toContain("Details README.md ✕"); expect(app.frame()).toContain("Details Files README.md ✕");
}); });
test("Neovim takes further files in the instance already running, through its socket, and the prefix's x asks it to quit", async () => { test("Neovim takes further files in the instance already running, through its socket, and the prefix's x asks it to quit", async () => {
const { root, snapshot } = workspace(); const { root, snapshot } = workspace();
const log = fakeNvim(); const log = fakeNvim();
const app = await open({ width: 200, session: fakeSession({ vcs: twoFiles, snapshot }) }); const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, session: fakeSession({ vcs: twoFiles, snapshot }) });
await editBoth(app); await editBoth(app);
await waitFor(() => log().some((line) => line.includes("--remote-expr"))); await waitFor(() => log().some((line) => line.includes("--remote-expr")));
expect(app.frame()).toContain("Details src/…/TerminalPane.tsx ✕"); expect(app.frame()).toContain("Details Files src/…/TerminalPane.tsx ✕");
expect(app.frame()).not.toContain("README.md ✕"); expect(app.frame()).not.toContain("README.md ✕");
expect(app.hints()).toBe(keysOn("TerminalPane.tsx")); expect(app.hints()).toBe(keysOn("TerminalPane.tsx"));
const [listen, remote] = log(); const [listen, remote] = log();
@@ -517,7 +517,7 @@ describe("editing a changed file", () => {
expect(app.frame().split("\n")[0]).toContain("Editor: README.md ● · d"); expect(app.frame().split("\n")[0]).toContain("Editor: README.md ● · d");
const note = app.find("Editor: README.md"); const note = app.find("Editor: README.md");
await app.click(note.x, note.y); await app.click(note.x, note.y);
expect(app.frame()).toContain("Details README.md ✕"); expect(app.frame()).toContain("Details Files README.md ✕");
}); });
test("on a narrow window the column, editor and all, takes the conversation's place", async () => { test("on a narrow window the column, editor and all, takes the conversation's place", async () => {
+78
View File
@@ -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> = {}): ProjectEntry => ({ path, kind: "file", ...extra }) as ProjectEntry;
const folder = (path: string, extra: Partial<ProjectEntry> = {}): ProjectEntry => ({ path, kind: "directory", ...extra }) as ProjectEntry;
const tree = (input: Partial<FileTreeInput>): 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<string, readonly ProjectEntry[]>([
["", [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");
});