diff --git a/README.md b/README.md index 1d09ea1..e7a113a 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,10 @@ The keys you'll use most: | `c` | new thread | | `m` | model, reasoning and access mode | | `.` | thread actions: pin, snooze, rename, archive… | -| `ctrl+j` | attach to the thread's terminal on the server | +| `ctrl+j` | the thread's terminal on the server, in a pane beside the conversation | +| `ctrl+\` | move the keys between the pane and the conversation | +| `ctrl+g` | write the message in `$EDITOR`, in the pane | +| `ctrl+v` | in the message box: attach the clipboard's image (or paste its text) | | `ctrl+c` | quit | In the message box, `/`, `$`, `@` and `#` suggest commands, skills, files and threads, and pull requests. Most things also work with the mouse. diff --git a/docs/reference.md b/docs/reference.md index dff5025..7585b05 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -27,7 +27,8 @@ Any mode: | Key | Action | | --- | --- | | `ctrl+k` | command palette: every action below, plus thread search | -| `ctrl+j` | attach to the thread's terminal (see [Terminals](#terminals)) | +| `ctrl+j` | open the thread's terminal in the pane (see [Terminals](#terminals)) | +| `ctrl+\` | with the pane open: move the keys between it and the conversation | | `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread | | `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation (`ctrl+u`/`ctrl+d` only in navigation; while typing they edit the text) | | `ctrl+c` | quit | @@ -41,7 +42,7 @@ Navigation: | `a` | attach a file to the next message (see [Attachments](#attachments)) | | `.` | thread actions (see [Thread actions](#thread-actions)); a right-click on a thread opens them too | | `m` | model, options (reasoning, fast mode…) and access mode | -| `T` | terminals: attach, new, close or clear | +| `T` | terminals: open in the pane, attach full screen, new, close or clear | | `b` | branches and worktrees: switch, create, pull or remove | | `E` | open the workspace (or diff file) in the server's editor | | `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | @@ -60,7 +61,7 @@ Navigation: | `d` | show or hide thread details (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 | -| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `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 the pane, `t` turns an automation on or off, `esc` comes back | | `u` | go to the parent thread (from a fork or subagent) | | `:` | command palette | | `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows | @@ -73,7 +74,11 @@ Navigation: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run; the `followUpBehavior` setting swaps the two. With an approval pending, a typed message declines it with your feedback. -`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. +`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`) in the terminal pane; save and quit to bring it back. + +`ctrl+v` attaches the clipboard's image, or pastes its text when there is no image. Pasting or dropping the path of an image file (quoted, as a `file://` URL, or with `\ ` before spaces) attaches the file rather than typing the path. See [Attachments](#attachments). + +Attachments and `@` files show in the box as chips, `[image 1]` or `@src/ui/App.tsx`, in the accent colour: the cursor steps over one in a single move and `backspace` deletes it whole. Deleting an attachment's chip removes the attachment. The text sent is what it was without chips: an attachment's chip is left out, and an `@` file goes as its markdown link. With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off and releases messages held in the queue. @@ -93,11 +98,11 @@ Typing a trigger opens a list of suggestions above the box: The layout follows T3 Code's web app, and much of it uses the web app's own code. - **Sidebar:** the same sections as the app (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. -- **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`. 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. - **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. -- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `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. - **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. - **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). `New automation` and `Edit automation: …` in the palette open the automation's fields in `$EDITOR` (title, schedule, project, workspace, model, mode, prompt); save and quit to save. `Delete automation: …` asks first. Webhook signatures and filters are left as they are; change those in the app. @@ -111,9 +116,9 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code ## Mouse -- **Select and copy:** drag across any text to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally). 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 the terminal pane, 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 the pane 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. -- **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 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 the editor pane. 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. - **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 or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, or the details column's left edge, to resize it; right-click the edge to reset it. @@ -136,7 +141,9 @@ Submenus open as their own list, and typing finds their items from the top (`thr ## Attachments -`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `Paste image from clipboard` in the palette takes a clipboard image instead (`wl-paste`, `xclip`, or `pngpaste` on macOS). Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone. +`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `ctrl+v` in the message box, or `Paste image from clipboard` in the palette, takes the clipboard's image instead (PNG, JPEG, WebP or GIF), as does a paste that comes through empty, which is how many terminals pass on a copied image. The clipboard is read through OpenTUI, then `wl-paste` or `xclip` (or `pngpaste` or `osascript` on macOS) when that finds nothing it can read. Over SSH the clipboard is on the other machine, so use `a` there. Pasting an image file's path attaches the file. Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone. + +Sent images show in their message, up to 12 rows tall, through kitty or sixel graphics where the terminal has them and as coloured blocks elsewhere; the file's name is under each. Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other files up to the server's limit (50 MB at most), and 100 attachments per message. @@ -150,9 +157,13 @@ Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other ## Terminals -`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. t3tui hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back, and the terminal keeps running. Its size is shared, so attaching resizes it for anyone else watching. +`ctrl+j` opens the thread's terminal on the T3 server, the same one the app's terminal drawer shows, in the pane on the right. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. The pane takes the details column's place and width (drag its edge to resize it); on a terminal too narrow for both, it takes the conversation's place. -`T` opens the terminal picker even with only one terminal. Choose `New terminal`, `Close terminal…` or `Clear terminal…`; typing `close` or `clear` finds each terminal's action directly. Closing ends the shell and deletes its history; clearing clears its scrollback. These are in the command palette too. +While the pane has focus, every key goes to its program, `esc` included, apart from `ctrl+\`, which gives the keys back to the conversation. `ctrl+\` again, or a click on the pane, returns them; the pane's left edge shows the accent while it has them. The pane follows its size, and so does the terminal on the server: its size is shared, so it resizes for anyone else watching. When the shell exits, the pane closes; `Close the terminal pane` in the palette detaches without stopping it. + +The same pane runs `$VISUAL` or `$EDITOR` (falling back to `vi`) on this machine: `ctrl+g` writes the message there, and `o` on a file under Changes in the details panel (or its `▸ Edit`) opens that file, when the workspace is on this machine. An open editor isn't replaced by anything else; quit it first. + +`T` opens the terminal picker even with only one terminal. Choose `New terminal`, `Attach full screen` (the whole screen goes to the terminal until `ctrl+j` or `ctrl+]`), `Close terminal…` or `Clear terminal…`; typing `close` or `clear` finds each terminal's action directly. Closing ends the shell and deletes its history; clearing clears its scrollback. These are in the command palette too. ## Workspace @@ -183,7 +194,7 @@ Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a clic | `diffIgnoreWhitespace` | `true`, `false` | `true` | | `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` | | `inAppNotificationsEnabled` | `true`, `false` | `true` | -| `theme` | `auto` (match the terminal), `dark`, `light`; applies from the next start | `auto` | +| `theme` | `auto` (dark or light, from the terminal's background), `dark`, `light`, or `terminal` (built from the terminal's own background, text and 16 ANSI colours); applies from the next start. Terminals that don't report their colours get `dark`. | `auto` | They have the same names as the app's settings. The app keeps its settings in the browser, so t3tui keeps its own, and turns the two alert settings on by default where the app leaves them off. diff --git a/src/bin.ts b/src/bin.ts index 9286504..60faeda 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -173,9 +173,14 @@ async function runUi(attachNeedle?: string) { setInterval(() => { if (Date.now() - lastInput > 5_000) Bun.gc(true); }, 30_000).unref(); - const { applyTheme } = await import("./ui/theme.ts"); - // Terminals that don't say what their background is get the dark palette. - applyTheme(config.theme === "auto" ? ((await renderer.waitForThemeMode(300)) ?? "dark") : config.theme); + const { applyTheme, terminalPalette, themeModeOf } = await import("./ui/theme.ts"); + if (config.theme === "dark" || config.theme === "light") applyTheme(config.theme); + else { + // The terminal's colours through OSC 4, 10 and 11; terminals that don't answer get the dark palette. + const detected = await renderer.getPalette({ timeout: 300, size: 16 }).catch(() => null); + const mode = themeModeOf(detected) ?? renderer.themeMode ?? "dark"; + applyTheme(config.theme === "terminal" ? (terminalPalette(detected) ?? mode) : mode); + } createRoot(renderer).render(createElement(App, { session, config, layout, ...(attachThreadId ? { attachThreadId } : {}) })); } diff --git a/src/client/session.ts b/src/client/session.ts index e238614..68578b1 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -200,6 +200,7 @@ export class T3Session { private readonly shellListeners = new Set>(); private readonly threads = new Map(); private readonly feeds = new Map(); + private readonly attachmentImages = new Map>(); async start(): Promise { const scope = Effect.runSync(Scope.make()); @@ -477,6 +478,23 @@ export class T3Session { return { type: upload.type === "file" ? "file" : "image", id: minted.attachmentId, name: upload.name, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes } as ChatAttachment; } + /** A sent image's bytes, fetched once per session through a signed inline URL, as the web shows it. */ + attachmentImage(attachment: Pick): Promise { + const cached = this.attachmentImages.get(attachment.id); + if (cached) return cached; + const loading = (async () => { + const { rpc, target } = this.requireConnection(); + const resource = { _tag: "attachment", attachmentId: attachment.id, fileName: attachment.name, mimeType: attachment.mimeType, disposition: "inline" } as const; + const minted = await Effect.runPromise(rpc[WS_METHODS.assetsCreateUrl]({ resource })); + const response = await fetch(new URL(minted.relativeUrl, target.httpBaseUrl)); + if (!response.ok) throw new Error(`Image request failed (${response.status})`); + return new Uint8Array(await response.arrayBuffer()); + })(); + this.attachmentImages.set(attachment.id, loading); + loading.catch(() => this.attachmentImages.delete(attachment.id)); + return loading; + } + /** Deletes an unsent upload, as removing it in the web composer does. */ deleteAttachment(attachmentId: string): Promise { return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.attachmentsDelete]({ attachmentId })); diff --git a/src/config.ts b/src/config.ts index c46007b..97cd38c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -18,8 +18,8 @@ export interface T3tuiConfig { readonly notificationMode: "off" | "notifications" | "sound" | "notifications-and-sound"; /** As the web's in-app toasts: a line at the bottom for threads you aren't looking at. */ readonly inAppNotificationsEnabled: boolean; - /** auto follows the terminal's background colour. */ - readonly theme: "auto" | "dark" | "light"; + /** auto picks dark or light from the terminal's background; terminal builds the palette from its colours. */ + readonly theme: "auto" | "dark" | "light" | "terminal"; } export const DEFAULT_CONFIG: T3tuiConfig = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true, theme: "auto" }; @@ -32,7 +32,7 @@ export const CONFIG_CHOICES: { readonly [K in keyof T3tuiConfig]: readonly T3tui diffIgnoreWhitespace: [true, false], notificationMode: ["off", "sound", "notifications", "notifications-and-sound"], inAppNotificationsEnabled: [true, false], - theme: ["auto", "dark", "light"], + theme: ["auto", "dark", "light", "terminal"], }; export const configPath = () => join(configDir(), "config.json"); diff --git a/src/model/attachments.ts b/src/model/attachments.ts index 8ff9205..9c839e7 100644 --- a/src/model/attachments.ts +++ b/src/model/attachments.ts @@ -32,16 +32,80 @@ export function expandAttachmentPath(input: string, cwd: string | null): string return isAbsolute(expanded) ? expanded : resolve(cwd ?? process.cwd(), expanded); } +/** Image types asked of the clipboard, in order of preference; all of them can be sent. */ +export const CLIPBOARD_IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const; + +/** A platform tool that reads a clipboard image, for when OpenTUI's clipboard service can't. */ +export interface ClipboardImageTool { + /** Lists the clipboard's types, one per line; absent for a tool that reads one fixed type. */ + readonly types?: readonly string[]; + readonly read: (mimeType: string) => readonly string[]; + /** The type a fixed-type tool reads. */ + readonly mimeType?: string; + /** Turns what the tool printed into the image's bytes, when it doesn't print them raw. */ + readonly decode?: (stdout: Uint8Array) => Uint8Array | null; +} + /** The clipboard readers, in order: the platform's usual image grabber first. */ -export function clipboardImageCommands(platform: string): readonly (readonly string[])[] { +export function clipboardImageCommands(platform: string): readonly ClipboardImageTool[] { return platform === "darwin" - ? [["pngpaste", "-"]] + ? [ + { read: () => ["pngpaste", "-"], mimeType: "image/png" }, + { read: () => ["osascript", "-e", "the clipboard as «class PNGf»"], mimeType: "image/png", decode: decodeAppleScriptData }, + ] : [ - ["wl-paste", "--type", "image/png"], - ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"], + { types: ["wl-paste", "--list-types"], read: (type) => ["wl-paste", "--type", type] }, + { types: ["xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"], read: (type) => ["xclip", "-selection", "clipboard", "-t", type, "-o"] }, ]; } +/** The image type to ask for among the clipboard's: a preferred one, else any image. */ +export function pickClipboardImageType(types: readonly string[]): string | null { + const offered = types.map((type) => type.trim().toLowerCase()); + return CLIPBOARD_IMAGE_TYPES.find((type) => offered.includes(type)) ?? offered.find((type) => type.startsWith("image/")) ?? null; +} + +/** AppleScript prints clipboard data as `«data PNGf89504E47…»`; this is the bytes. */ +export function decodeAppleScriptData(stdout: Uint8Array): Uint8Array | null { + const hex = /«data \w{4}([0-9A-Fa-f]+)»/.exec(new TextDecoder().decode(stdout))?.[1]; + return hex ? Uint8Array.from(hex.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16)) : null; +} + +/** The file name for a pasted image of this type. */ +export function pastedImageName(mimeType: string): string { + const extension = Object.entries(IMAGE_MIME_BY_EXTENSION).find(([, type]) => type === mimeType)?.[0] ?? "png"; + return `pasted-image.${extension === "jpeg" ? "jpg" : extension}`; +} + +/** + * The image file a paste names, as terminals paste a dropped file: quoted, as a file:// + * URL, or with its spaces escaped. Null unless it is one path with an image's extension; + * whether the file exists is the caller's to check. + */ +export function pastedImagePath(text: string, cwd: string | null): string | null { + const raw = text.trim().replace(/^(['"])(.*)\1$/s, "$2"); + if (!raw || raw.includes("\n")) return null; + let path: string; + if (raw.startsWith("file://")) { + try { + const url = new URL(raw); + if (url.hostname && url.hostname !== "localhost") return null; + path = decodeURIComponent(url.pathname); + } catch { + return null; + } + } else { + path = raw.replace(/\\(.)/g, "$1"); + } + if (!path.startsWith("/") && !path.startsWith("~") && !path.startsWith(".")) return null; + return imageMimeTypeForName(path) ? expandAttachmentPath(path, cwd) : null; +} + +/** Over SSH the clipboard is on the other machine, out of reach of the tools here. */ +export function isRemoteTerminal(env: Record): boolean { + return Boolean(env.SSH_CONNECTION || env.SSH_TTY); +} + export type AttachmentCheck = | { readonly ok: true; readonly upload: AttachmentCreateUploadUrlInput; readonly mimeType: string } | { readonly ok: false; readonly error: string }; diff --git a/src/model/composerMenu.ts b/src/model/composerMenu.ts index 6c1f331..10d792b 100644 --- a/src/model/composerMenu.ts +++ b/src/model/composerMenu.ts @@ -23,6 +23,8 @@ export interface ComposerItem { readonly label: string; readonly description: string; readonly replacement: string | null; + /** What the composer shows in place of the replacement, as one chip; the replacement is still what's sent. */ + readonly chip?: string; /** A mention's record (a thread, or a pull request), sent with the message. */ readonly record?: ComposerContextRecord; readonly action?: "model"; @@ -138,14 +140,19 @@ export function pathItems(entries: readonly ProjectEntry[]): ComposerItem[] { label: `${entry.path.slice(slash + 1)}${entry.kind === "directory" ? "/" : ""}`, description: slash > 0 ? entry.path.slice(0, slash) : "", replacement: `${serializeComposerFileLink(entry.path)} `, + chip: `@${entry.path}${entry.kind === "directory" ? "/" : ""}`, }; }); } /** The text with the trigger replaced; a trailing space swallows one already there, as the web does. */ export function applyComposerItem(text: string, trigger: ComposerTrigger, replacement: string): { text: string; cursor: number } { - const end = replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd; - return replaceTextRange(text, trigger.rangeStart, end, replacement); + return replaceTextRange(text, trigger.rangeStart, composerItemEnd(text, trigger, replacement), replacement); +} + +/** Where the text a choice replaces ends: the trigger's range, and a space the replacement brings its own of. */ +export function composerItemEnd(text: string, trigger: ComposerTrigger, replacement: string): number { + return replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd; } /** The records for the mentions (threads, pull requests) still in the text, as the message's context. */ diff --git a/src/model/links.ts b/src/model/links.ts new file mode 100644 index 0000000..c6edf5b --- /dev/null +++ b/src/model/links.ts @@ -0,0 +1,25 @@ +/** Characters a file path on screen is made of, with an optional `:line` or `:line:col` after it. */ +const PATH_CHARS = /[\w.~/@+-]/; + +/** + * The file path the text has at `index`, as an agent writes them: `src/ui/App.tsx`, + * `./bin.ts:12`, `~/notes.md`. Null for words, URLs and anything else without a folder + * or an extension. + */ +export function pathAt(text: string, index: number): string | null { + if (!PATH_CHARS.test(text[index] ?? "")) return null; + let start = index; + let end = index + 1; + while (start > 0 && PATH_CHARS.test(text[start - 1]!)) start--; + while (end < text.length && (PATH_CHARS.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++; + if (text[start - 1] === ":" || text.slice(end, end + 3) === "://") return null; + const token = text.slice(start, end).replace(/[.,]+$/, ""); + const path = token.replace(/(:\d+){1,2}$/, ""); + if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/")) return null; + return path.includes("/") || /\.[A-Za-z]\w*$/.test(path) ? path : null; +} + +/** A link's target is a web page unless it is a bare path. */ +export function isWebUrl(url: string): boolean { + return /^[a-z][a-z\d+.-]*:/i.test(url) && !url.toLowerCase().startsWith("file:"); +} diff --git a/src/model/settings.ts b/src/model/settings.ts index fae78b3..c5c4092 100644 --- a/src/model/settings.ts +++ b/src/model/settings.ts @@ -21,7 +21,7 @@ const LABELS: { readonly [K in keyof T3tuiConfig]: { readonly label: string; rea values: { off: "off", sound: "bell", notifications: "desktop notifications", "notifications-and-sound": "bell and desktop notifications" }, }, inAppNotificationsEnabled: { label: "In-app alerts", help: "a line at the bottom for other threads", values: { true: "on", false: "off" } }, - theme: { label: "Colours", help: "from the next start", values: { auto: "match the terminal", dark: "dark", light: "light" } }, + theme: { label: "Colours", help: "from the next start", values: { auto: "dark or light, as the terminal is", dark: "dark", light: "light", terminal: "the terminal's own colours" } }, }; /** t3tui's own settings, in display order, each cycled with enter. */ diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 67d4fde..c5c3851 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -1,14 +1,18 @@ -import type { KeyEvent, MouseEvent, ScrollBoxRenderable, Selection, TextareaRenderable } from "@opentui/core"; +import { decodePasteBytes, type KeyEvent, type MouseEvent, type PasteEvent, type ScrollBoxRenderable, type Selection, type TextareaRenderable } from "@opentui/core"; import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"; import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { existsSync, statSync } from "node:fs"; import { homedir } from "node:os"; +import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts"; import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts"; import { createAlerts, type Alert } from "../model/alerts.ts"; +import { pastedImagePath } from "../model/attachments.ts"; +import { isWebUrl, pathAt } from "../model/links.ts"; import { modelSummary } from "../model/models.ts"; import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts"; import { saveLayout, type Layout } from "../layout.ts"; @@ -31,7 +35,8 @@ import { useDraft } from "./useDraft.ts"; import { useModelPicker } from "./useModelPicker.ts"; import { useQuestion } from "./useQuestion.ts"; import { useThreadMenu } from "./useThreadMenu.ts"; -import { editInEditor } from "./editor.ts"; +import { editorCommand, scratchFile } from "./editor.ts"; +import { TerminalPane, type PaneProgram } from "./TerminalPane.tsx"; import { Palette } from "./Palette.tsx"; import { ApprovalPanel } from "./ApprovalPanel.tsx"; import { LiveStatus } from "./LiveStatus.tsx"; @@ -42,8 +47,11 @@ import { PullRequestView } from "./PullRequestView.tsx"; import { SettingsView } from "./SettingsView.tsx"; import { useWorkspace } from "./useWorkspace.ts"; import { usePullRequests } from "./usePullRequests.ts"; -import { copyText, desktopNotify, ring } from "./terminalOut.ts"; -import { colors, statusColor } from "./theme.ts"; +import { rendererClipboard, type Clipboard } from "./clipboard.ts"; +import { composerText, useComposerChips } from "./useComposerChips.ts"; +import { openInBrowser, screenTextAt } from "./links.ts"; +import { desktopNotify, ring } from "./terminalOut.ts"; +import { colors, statusColor, useMarkdownStyle } from "./theme.ts"; import { BAR, NO_BORDER } from "./edges.ts"; import { ThreadList } from "./ThreadList.tsx"; import { useTurns } from "./useTurns.ts"; @@ -68,9 +76,10 @@ import { useUsageSummary } from "./useUsage.ts"; /** * "input": typing goes to the composer. "nav": single keys move, scroll, approve. * "details": j/k move through the details panel. "settings": j/k move through settings. + * "pane": every key but ctrl+\ goes to the program in the terminal pane. * The rest are overlays with their own input. */ -type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request"; +type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request" | "pane"; /** Holding j/k skims past threads; only subscribe to one you stop on. */ const SUBSCRIBE_DELAY_MS = 120; @@ -84,6 +93,8 @@ const DETAILS_WIDTH = 38; const MIN_DETAILS_WIDTH = 28; /** Below this, the details panel takes the conversation's place instead of a column beside it. */ const MIN_CONVERSATION_WIDTH = 70; +/** The conversation this wide or wider shows diffs side by side. */ +const SPLIT_DIFF_WIDTH = 140; const COMPOSER_KEYS = { enter: [ @@ -99,10 +110,12 @@ const COMPOSER_KEYS = { /** The composer's key while a new thread is being drafted. */ const DRAFT_KEY = "draft"; -export function App(props: { readonly session: T3Session; readonly config: T3tuiConfig; readonly layout?: Layout; readonly attachThreadId?: ThreadId }) { +export function App(props: { readonly session: T3Session; readonly config: T3tuiConfig; readonly layout?: Layout; readonly attachThreadId?: ThreadId; readonly clipboard?: Clipboard }) { const { session, attachThreadId } = props; const attached = attachThreadId !== undefined; const renderer = useRenderer(); + const [clipboard] = useState(() => props.clipboard ?? rendererClipboard(renderer)); + const markdownStyle = useMarkdownStyle(); const { width, height } = useTerminalDimensions(); const [shell, setShell] = useState(session.getShell()); // Any thread, listed or not: subagents open here too. @@ -111,6 +124,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const [filter, setFilter] = useState(""); const [showFolded, setShowFolded] = useState(false); const [expandAll, setExpandAll] = useState(false); + /** Side-by-side diffs, once toggled for the session; null follows the conversation's width. */ + const [splitDiffPref, setSplitDiffPref] = useState(null); /** Folds opened one at a time by a click, for the open thread. */ const [expandedIds, setExpandedIds] = useState>(() => new Set()); /** The thread list's and details column's widths once their edges are dragged; null follows the window. */ @@ -134,6 +149,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui /** The edge being dragged. */ const [resizing, setResizing] = useState<"list" | "details" | null>(null); const [diff, setDiff] = useState(null); + /** The program in the right-hand pane: one of T3's terminals, or $EDITOR. */ + const [pane, setPane] = useState(null); + /** The conversation area's height, for the pane when it takes that place. */ + const [contentHeight, setContentHeight] = useState(0); const [config, setConfig] = useState(props.config); const [settingsIndex, setSettingsIndex] = useState(null); const [serverConfig, setServerConfig] = useState(null); @@ -341,8 +360,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const copySelection = useEvent((selection: Selection) => { const text = selection.getSelectedText(); if (!text.trim()) return; - copyText(renderer, text); - say(`Copied ${text.length === 1 ? "1 character" : `${text.length} characters`}`); + void clipboard.copy(text).then((copied) => (copied ? say("Copied") : say("Could not reach the clipboard.", true))); }); useEffect(() => { renderer.on("selection", copySelection); @@ -411,12 +429,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const attachCwd = draft ? (shell.snapshot?.projects.find((candidate) => candidate.id === draft.projectId)?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null); const attach = useAttachments({ session, + clipboard, composerKey, cwd: attachCwd, maxFileBytes: serverConfig?.config ? (serverConfig.config.environment.capabilities.fileAttachments?.maxUploadBytes ?? null) : undefined, confirm, say, }); + const chips = useComposerChips({ composerRef, composerKey, pending: attach.pending, remove: attach.remove }); const usage = useUsageSummary(session, settingsIndex !== null && live); const usageInfo = useMemo(() => usageLimits(serverConfig?.config ?? null, now), [serverConfig, now]); const spendResetCredit = (credit: (typeof usageInfo.credits)[number]) => @@ -459,6 +479,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui say, progress: (text) => setFlash({ text }), openThread, + editFile: (path, cwd) => editFile(path, cwd), focus: (focused) => setMode(focused ? "details" : "nav"), }); @@ -488,7 +509,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const runtimeMode = models.runtimeMode; const threadMenu = useThreadMenu({ session, - renderer, + clipboard, snapshot: shell.snapshot, config: providerConfig, timestampFormat: config.timestampFormat, @@ -513,17 +534,70 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }, }); - const workspace = useWorkspace({ session, renderer, live, thread: threadShell, project, serverConfig: serverConfig?.config ?? null, draft: draft !== null, diff, openPicker, confirm, run, say }); + /** Puts a program in the pane and gives it the keys. An editor there may hold unsaved work, so it isn't replaced. */ + const showPane = (program: PaneProgram) => { + if (pane?.kind === "local" && pane.id !== program.id) return say("The editor in the pane is still open; ctrl+\\ there and quit it first.", true); + setPane(program); + setMode("pane"); + }; + const closePane = (message?: string) => { + setPane(null); + setMode((current) => (current === "pane" ? "nav" : current)); + if (message) say(message); + }; + const workspace = useWorkspace({ + session, + renderer, + live, + thread: threadShell, + project, + serverConfig: serverConfig?.config ?? null, + draft: draft !== null, + diff, + openPicker, + openPane: (target) => showPane({ kind: "server", id: `server:${target.threadId}:${target.terminalId}`, title: `Terminal · ${target.label}`, target }), + confirm, + run, + say, + }); - /** The composer's text in $EDITOR. */ - const openEditor = async () => { + /** The composer's text in $EDITOR, in the pane; what's saved comes back when it exits. */ + const openEditor = () => { const composer = composerRef.current; if (!composer) return; - const edited = await editInEditor(renderer, composer.plainText); - if (edited === null) return say("The editor exited with an error; the message is unchanged.", true); - composer.setText(edited); - composer.gotoBufferEnd(); - setMode("input"); + const key = composerKey; + const file = scratchFile(composerText(composer)); + showPane({ + kind: "local", + id: `message:${file.path}`, + title: "Message · save and quit to bring it back", + command: editorCommand(file.path), + onExit: (code) => { + const edited = code === 0 ? file.read() : null; + file.remove(); + if (edited === null) return say("The editor exited with an error; the message is unchanged.", true); + putMessage(key, edited); + setMode((current) => (current === "pane" ? "input" : current)); + }, + }); + }; + /** A workspace file in $EDITOR, in the pane, when the workspace is on this machine. */ + const editFile = (path: string, cwd: string | null) => { + const file = cwd ? resolvePathLinkTarget(path, cwd) : path; + if (!existsSync(file)) return say(`${path} isn't on this machine.`, true); + showPane({ kind: "local", id: `edit:${file}`, title: `Editing ${path}`, command: editorCommand(file), cwd: cwd ?? undefined, onExit: () => {} }); + }; + + /** A click on a link opens it in the browser; on a path to a workspace file, in the editor pane. A drag doesn't. */ + const openAt = (x: number, y: number) => { + if (renderer.getSelection()?.getSelectedText()) return; + const url = renderer.getLinkAt(x, y); + if (url && isWebUrl(url)) return openInBrowser(url, (reason) => say(`Could not open the browser (${reason}): ${url}`, true)); + const shown = url ? null : screenTextAt(renderer, x, y); + const raw = url ? (url.startsWith("file:") ? decodeURIComponent(parseFileUrlHref(url)?.path ?? "") : url) : shown && pathAt(shown.text, shown.index); + if (!raw || !attachCwd) return; + const { path } = splitFilePathPosition(resolvePathLinkTarget(raw, attachCwd)); + if (existsSync(path) && statSync(path).isFile()) editFile(path, attachCwd); }; const settingsRows = settingRows(config); @@ -545,6 +619,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui setMode("nav"); }; + /** Replaces a composer's text, the open one's or a stored draft's. */ + const putMessage = (key: string, text: string) => { + const composer = composerRef.current; + if (key !== activeComposerKey.current || !composer) return void drafts.current.set(key, text); + chips.replaceText(composer, text); + composer.gotoBufferEnd(); + setComposerLines(composerLineCount(composer)); + setComposerEmpty(text.trim() === ""); + }; + /** * A message that didn't go comes back to its composer, as the web's does: its text, its * attachments and its mentions, unless something new was typed there meanwhile. @@ -552,8 +636,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const restoreMessage = (key: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[]) => { const composer = composerRef.current; if (key === activeComposerKey.current && composer) { - if (composer.plainText.trim()) return; - composer.setText(text); + if (composerText(composer).trim()) return; + chips.replaceText(composer, text); composer.gotoBufferEnd(); setComposerLines(composerLineCount(composer)); setComposerEmpty(text === ""); @@ -577,7 +661,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }; const clearComposer = () => { - composerRef.current?.setText(""); + if (composerRef.current) chips.replaceText(composerRef.current, ""); if (threadId) drafts.current.delete(threadId); composerMenu.forget(); setComposerLines(1); @@ -587,11 +671,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui /** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */ const submit = (alternate = false) => { const composer = composerRef.current; - const raw = composer?.plainText ?? ""; + const raw = composer ? composerText(composer) : ""; // A trailing backslash continues onto a new line, for terminals that can't send shift+enter. if (!alternate && config.sendShortcut === "enter" && composer && raw.endsWith("\\")) { - composer.setText(raw.slice(0, -1)); composer.gotoBufferEnd(); + composer.deleteCharBackward(); composer.newLine(); return; } @@ -646,10 +730,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const turns = useTurns({ session, threadId, projection, timeline: current, config: providerConfig, cwd: panel.cwd, ignoreWhitespace: config.diffIgnoreWhitespace, enabled: draft === null, diff, setDiff, scrollRef, confirm, say, showConversation: () => { setMode("nav"); setDetailsPrefState((value) => (width < MIN_CONVERSATION_WIDTH + DETAILS_WIDTH ? false : value)); }, restorePrompt: (id, text) => { - const previous = id === activeComposerKey.current ? composerRef.current?.plainText ?? "" : drafts.current.get(id) ?? ""; + const previous = id === activeComposerKey.current && composerRef.current ? composerText(composerRef.current) : drafts.current.get(id) ?? ""; const next = text ? previous ? `${previous}\n\n${text}` : text : previous; drafts.current.set(id, next); - if (id === activeComposerKey.current) { composerRef.current?.setText(next); setMode("input"); } + if (id === activeComposerKey.current && composerRef.current) { chips.replaceText(composerRef.current, next); setMode("input"); } }, }); @@ -657,6 +741,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const pullRequests = usePullRequests({ session, renderer, + clipboard, threadShell, project: draft ? draftProject : project, projects: shell.snapshot?.projects ?? [], @@ -724,12 +809,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const quitKey: Binding = { keys: ["ctrl+c"], run: quit }; const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette }; const terminalKey: Binding = { keys: ["ctrl+j"], run: workspace.openTerminal }; + const paneKey: Binding | null = pane && { keys: ["ctrl+\\"], run: () => setMode(mode === "pane" ? "nav" : "pane"), hint: mode === "pane" ? "leave pane" : "pane", command: { id: "pane-focus", title: mode === "pane" ? "Leave the terminal pane" : "Focus the terminal pane", keywords: ["terminal", "editor"] } }; const editorKey: Binding | null = hasComposer ? { keys: ["ctrl+g"], run: openEditor, command: { id: "editor", title: "Write the message in $EDITOR", keywords: ["vim", "editor", "compose"] } } : null; const nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) }; const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], run: () => move(-1) }; // Anywhere with a text field, ctrl+u and ctrl+d edit (delete to line start, delete forward); page up/down still scroll. const lineInput = mode === "filter" || mode === "input" || mode === "find" || mode === "palette" || mode === "picker" || mode === "confirm"; const globalKeys = keys( + paneKey, quitKey, paletteKey, terminalKey, @@ -795,15 +882,20 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui cancelDraftKey, ); // A diff and a draft name their own few keys; everything else names the lot. - const navHints = diff - ? [scrollDiffDown, closeDiff, detailsKey] - : draft - ? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey) - : navKeys; + const navHints = keys( + paneKey, + diff + ? [scrollDiffDown, closeDiff, detailsKey] + : draft + ? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey) + : navKeys, + ); // Commands only the palette runs. const paletteOnly = keys( editorKey, + pane?.kind === "server" && { keys: [], run: () => closePane(), command: { id: "pane-close", title: "Close the terminal pane", keywords: ["detach", "hide"] } }, + { keys: [], run: () => setSplitDiffPref(!splitDiff), command: { id: "split-diff", title: "Toggle split diff", keywords: ["side by side", "unified", "diff view"] } }, queue.keys.input, queue.keys.palette, (projection?.subagents ?? []).filter((agent) => threadId && canStopSubagent(agent)).map((agent): Binding => ({ keys: [], run: () => run("Stop requested", () => session.stopSubagent(agent)), command: { id: `stop-subagent:${agent.id}`, title: `Stop subagent: ${agent.title ?? "subagent"}`, keywords: ["interrupt", "cancel", "kill"] } })), @@ -814,7 +906,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui pullRequests.commands.map((command): Binding => ({ ...fromCommand(command), keys: [], ...(command.shortcut ? { label: command.shortcut } : {}) })), { keys: [], run: openSettings, command: { id: "settings", title: "Settings", keywords: ["preferences", "config", "options", "notifications", "alerts"] } }, ); - const commands = commandsFor([...navKeys, ...paletteOnly]); + const commands = commandsFor(keys(paneKey, navKeys, paletteOnly)); // The composer. Enter and newlines are the textarea's own; their hints only explain. const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter"; @@ -828,6 +920,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui queue.keys.input, { keys: [], label: config.sendShortcut === "enter" ? "shift+enter or \\" : "enter", hint: "newline" }, editorKey && hinted(editorKey, "editor"), + { keys: ["ctrl+v"], run: () => attach.paste((text) => composerRef.current?.insertText(text)) }, { keys: ["esc"], run: () => setMode("nav"), hint: "navigate" }, !attached && hinted(nextThreadKey, "thread"), ); @@ -888,6 +981,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui return { layers: [confirmKeys], hints: confirmKeys }; } } + if (mode === "pane" && paneKey) return { layers: [[paneKey]], hints: [paneKey] }; // The secret field takes every key while it's focused. if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings }; switch (mode) { @@ -921,7 +1015,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui return key.preventDefault(); } } - if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm") { + if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm" && mode !== "pane") { secret.type(key); key.preventDefault(); } @@ -948,9 +1042,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui loadEarlier: useEvent(() => loadEarlier()), menu: useEvent((target: ConversationTarget) => openConversationMenu(target)), openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)), + click: useEvent((x: number, y: number) => openAt(x, y)), }; const copy = (label: string, text: string) => { - copyText(renderer, text); + void clipboard.copy(text); say(`Copied ${label}`); }; /** Long output stays on the server until it's asked for. */ @@ -985,7 +1080,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }); /** A click in the conversation, a diff or the PR view takes the keys there, out of the composer or details. */ const focusConversation = (event: MouseEvent) => { - if (event.button !== 0 || (mode !== "input" && mode !== "details")) return; + if (event.button !== 0 || (mode !== "input" && mode !== "details" && mode !== "pane")) return; panel.leave(); }; @@ -999,8 +1094,13 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui // Room for the details column and its edge beside the conversation; a dragged width gives way to the conversation first. const detailsRoom = width - listWidth - 1 - MIN_CONVERSATION_WIDTH; const detailsWidth = Math.min(detailsWidthPref ?? DETAILS_WIDTH, Math.max(DETAILS_WIDTH, detailsRoom)); - const detailsColumn = panel.show && detailsWidth <= detailsRoom; - const detailsInPlace = panel.show && !detailsColumn; + // The pane takes the details column's place, or the conversation's when there's no room beside it. + const paneColumn = pane !== null && detailsWidth <= detailsRoom; + const detailsColumn = !pane && panel.show && detailsWidth <= detailsRoom; + const detailsInPlace = !pane && panel.show && !detailsColumn; + const rightColumn = paneColumn || detailsColumn; + const conversationWidth = width - (showList ? listWidth + 1 : 0) - (rightColumn ? detailsWidth + 1 : 0); + const splitDiff = splitDiffPref ?? conversationWidth >= SPLIT_DIFF_WIDTH; // The block's height: a row of padding on top, the text, then the model line inside it. // Padding row, text, a blank row, then the model line. const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 3; @@ -1044,6 +1144,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui inPlace={inPlace} selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null} onActivate={panel.activateById} + onEdit={panel.edit} /> ); @@ -1118,8 +1219,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui saveLayoutNow({ listWidth: null }); }} />} - - {settingsIndex !== null ? ( + + {pane && !paneColumn ? null : settingsIndex !== null ? ( pullRequests.commands.find((candidate) => candidate.id === "pr-open")?.run()} onMenu={openPullRequestMenu} onClose={pullRequests.close} /> ) : diff ? ( - + ) : draft ? ( ) : threadId && detailsInPlace && mode !== "find" ? ( @@ -1171,7 +1272,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui {workspace.note ? {workspace.note} : null} {find.open ? setMode("nav")} /> : null} {mode !== "confirm" && secret.request ? : null} - {queue.queued.length > 0 ? : null} + {queue.queued.length > 0 ? : null} {mode !== "confirm" && questions.request && questions.draft ? ) : null} - {menu ? : null} + {menu ? : null} {attach.pending.length > 0 ? ( Attached: @@ -1236,12 +1337,23 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui focusedBackgroundColor={colors.element} wrapMode="word" keyBindings={[...COMPOSER_KEYS[config.sendShortcut]]} + syntaxStyle={markdownStyle} onSubmit={() => submit()} + onPaste={(event: PasteEvent) => { + const text = decodePasteBytes(event.bytes); + // An empty paste is how terminals pass on a copied image they can't send as text. + const path = text.trim() ? pastedImagePath(text, attachCwd) : null; + if (text.trim() && !(path && existsSync(path))) return; + event.preventDefault(); + if (path) attach.attachPath(path); + else attach.paste(); + }} onCursorChange={composerMenu.sync} onContentChange={() => { composerMenu.sync(); + chips.sync(); const composer = composerRef.current; - const text = composer?.plainText ?? ""; + const text = composer ? composerText(composer) : ""; if (text) drafts.current.set(composerKey, text); else drafts.current.delete(composerKey); // Wrapped lines count too, so a long paragraph grows the box. @@ -1275,14 +1387,24 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui ) : null} - {detailsColumn ? ( - <> - setResizing("details")} onReset={() => { - setDetailsWidthPref(null); - saveLayoutNow({ detailsWidth: null }); - }} /> - {detailsPanel(false)} - + {rightColumn ? ( + setResizing("details")} onReset={() => { + setDetailsWidthPref(null); + saveLayoutNow({ detailsWidth: null }); + }} /> + ) : null} + {detailsColumn ? detailsPanel(false) : null} + {/* One place in the tree in both layouts, so a narrower window doesn't restart its program. */} + {pane ? ( + setMode("pane")} + onClose={closePane} + place={paneColumn ? { width: detailsWidth } : { left: showList ? listWidth + 1 : 0, height: contentHeight }} + /> ) : null} diff --git a/src/ui/DetailsPanel.tsx b/src/ui/DetailsPanel.tsx index befabe5..d5d9d4d 100644 --- a/src/ui/DetailsPanel.tsx +++ b/src/ui/DetailsPanel.tsx @@ -1,9 +1,9 @@ import type { ReactNode } from "react"; import { MAX_DETAIL_FILES, type ChangedFile, type DetailsAction, type DetailsFold, type LineageLine, type ThreadDetails } from "../model/details.ts"; -import { ClickRow } from "./Button.tsx"; +import { Button, ClickRow } from "./Button.tsx"; import { truncate } from "./text.ts"; -import { colors, statusColor } from "./theme.ts"; +import { colors, scrollbarOptions, statusColor } from "./theme.ts"; /** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */ const IN_PLACE_MAX_WIDTH = 64; @@ -25,6 +25,8 @@ export function DetailsPanel(props: { readonly selected: string | null; readonly unfolded: ReadonlySet; readonly onActivate: (id: string) => void; + /** Opens a changed file in $EDITOR, from its ▸ Edit. */ + readonly onEdit: (path: string) => void; /** Shown when there are no details, which defaults to no thread being selected. */ readonly empty?: string; }) { @@ -44,11 +46,11 @@ export function DetailsPanel(props: { overflow="hidden" backgroundColor={colors.panel} > - + {!details ? ( {props.empty ?? "No thread selected."} ) : ( - + )} @@ -60,7 +62,7 @@ interface LineProps { readonly onActivate: (id: string) => void; } -function Sections({ details, inner, loading, unfolded, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet } & LineProps) { +function Sections({ details, inner, loading, unfolded, selected, onActivate, onEdit }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet; readonly onEdit: (path: string) => void } & LineProps) { const { branch, changes, git, tasks } = details; const files = changes?.files ?? []; const line = { selected, onActivate }; @@ -102,9 +104,16 @@ function Sections({ details, inner, loading, unfolded, selected, onActivate }: { {changes ? (
}> {files.slice(0, MAX_DETAIL_FILES).map((file) => ( - - - + + + + + {selected === `diff:${file.path}` && !file.path.endsWith("/") ? ( + +