Run terminals and $EDITOR in a pane beside the conversation

ctrl+j opens the thread's T3 terminal in an embedded terminal that takes
the details column's place (or the conversation's on narrow terminals);
ctrl+g writes the message there and o on a changed file edits it. While
the pane has focus every key but ctrl+\ goes to its program. Full-screen
attach stays in the T picker and the palette.
This commit is contained in:
Callum Alpass committed 2026-11-03 02:53:53 +11:00
1 parent c0b7615590
commit 4ef243875f
10 files changed
+500 -61

No files matched your search

+3 -1
View File
@@ -48,7 +48,9 @@ The keys you'll use most:
| `c` | new thread | | `c` | new thread |
| `m` | model, reasoning and access mode | | `m` | model, reasoning and access mode |
| `.` | thread actions: pin, snooze, rename, archive… | | `.` | 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+c` | quit | | `ctrl+c` | quit |
In the message box, `/`, `$`, `@` and `#` suggest commands, skills, files and threads, and pull requests. Most things also work with the mouse. In the message box, `/`, `$`, `@` and `#` suggest commands, skills, files and threads, and pull requests. Most things also work with the mouse.
+11 -6
View File
@@ -27,7 +27,8 @@ Any mode:
| Key | Action | | Key | Action |
| --- | --- | | --- | --- |
| `ctrl+k` | command palette: every action below, plus thread search | | `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 | | `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) | | `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 | | `ctrl+c` | quit |
@@ -41,7 +42,7 @@ Navigation:
| `a` | attach a file to the next message (see [Attachments](#attachments)) | | `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 | | `.` | 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 | | `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 | | `b` | branches and worktrees: switch, create, pull or remove |
| `E` | open the workspace (or diff file) in the server's editor | | `E` | open the workspace (or diff file) in the server's editor |
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | | `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) | | `d` | show or hide thread details (kept for the next run) |
| `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, `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) | | `u` | go to the parent thread (from a fork or subagent) |
| `:` | command palette | | `:` | command palette |
| `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows | | `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows |
@@ -73,7 +74,7 @@ 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. `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.
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. 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.
@@ -150,9 +151,13 @@ Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other
## Terminals ## 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 ## Workspace
+113 -32
View File
@@ -3,7 +3,9 @@ import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts"; import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
@@ -31,7 +33,8 @@ 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";
import { useThreadMenu } from "./useThreadMenu.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 { Palette } from "./Palette.tsx";
import { ApprovalPanel } from "./ApprovalPanel.tsx"; import { ApprovalPanel } from "./ApprovalPanel.tsx";
import { LiveStatus } from "./LiveStatus.tsx"; import { LiveStatus } from "./LiveStatus.tsx";
@@ -68,9 +71,10 @@ import { useUsageSummary } from "./useUsage.ts";
/** /**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve. * "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. * "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. * 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. */ /** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120; const SUBSCRIBE_DELAY_MS = 120;
@@ -134,6 +138,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
/** The edge being dragged. */ /** The edge being dragged. */
const [resizing, setResizing] = useState<"list" | "details" | null>(null); const [resizing, setResizing] = useState<"list" | "details" | null>(null);
const [diff, setDiff] = useState<DiffState | null>(null); const [diff, setDiff] = useState<DiffState | null>(null);
/** The program in the right-hand pane: one of T3's terminals, or $EDITOR. */
const [pane, setPane] = useState<PaneProgram | null>(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 [config, setConfig] = useState(props.config);
const [settingsIndex, setSettingsIndex] = useState<number | null>(null); const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null); const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null);
@@ -459,6 +467,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
say, say,
progress: (text) => setFlash({ text }), progress: (text) => setFlash({ text }),
openThread, openThread,
editFile: (path, cwd) => editFile(path, cwd),
focus: (focused) => setMode(focused ? "details" : "nav"), focus: (focused) => setMode(focused ? "details" : "nav"),
}); });
@@ -513,17 +522,58 @@ 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. */ /** The composer's text in $EDITOR, in the pane; what's saved comes back when it exits. */
const openEditor = async () => { const openEditor = () => {
const composer = composerRef.current; const composer = composerRef.current;
if (!composer) return; if (!composer) return;
const edited = await editInEditor(renderer, composer.plainText); const key = composerKey;
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true); const file = scratchFile(composer.plainText);
composer.setText(edited); showPane({
composer.gotoBufferEnd(); kind: "local",
setMode("input"); 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: () => {} });
}; };
const settingsRows = settingRows(config); const settingsRows = settingRows(config);
@@ -545,6 +595,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
setMode("nav"); 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);
composer.setText(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 * 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. * attachments and its mentions, unless something new was typed there meanwhile.
@@ -724,12 +784,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const quitKey: Binding = { keys: ["ctrl+c"], run: quit }; const quitKey: Binding = { keys: ["ctrl+c"], run: quit };
const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette }; const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette };
const terminalKey: Binding = { keys: ["ctrl+j"], run: workspace.openTerminal }; 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 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 nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) };
const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], 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. // 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 lineInput = mode === "filter" || mode === "input" || mode === "find" || mode === "palette" || mode === "picker" || mode === "confirm";
const globalKeys = keys( const globalKeys = keys(
paneKey,
quitKey, quitKey,
paletteKey, paletteKey,
terminalKey, terminalKey,
@@ -795,15 +857,19 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
cancelDraftKey, cancelDraftKey,
); );
// A diff and a draft name their own few keys; everything else names the lot. // A diff and a draft name their own few keys; everything else names the lot.
const navHints = diff const navHints = keys(
? [scrollDiffDown, closeDiff, detailsKey] paneKey,
: draft diff
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey) ? [scrollDiffDown, closeDiff, detailsKey]
: navKeys; : draft
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey)
: navKeys,
);
// Commands only the palette runs. // Commands only the palette runs.
const paletteOnly = keys( const paletteOnly = keys(
editorKey, editorKey,
pane?.kind === "server" && { keys: [], run: () => closePane(), command: { id: "pane-close", title: "Close the terminal pane", keywords: ["detach", "hide"] } },
queue.keys.input, queue.keys.input,
queue.keys.palette, 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"] } })), (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 +880,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
pullRequests.commands.map((command): Binding => ({ ...fromCommand(command), keys: [], ...(command.shortcut ? { label: command.shortcut } : {}) })), 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"] } }, { 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. // The composer. Enter and newlines are the textarea's own; their hints only explain.
const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter"; const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
@@ -888,6 +954,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
return { layers: [confirmKeys], hints: confirmKeys }; return { layers: [confirmKeys], hints: confirmKeys };
} }
} }
if (mode === "pane" && paneKey) return { layers: [[paneKey]], hints: [paneKey] };
// 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, [quitKey]], hints: secret.bindings }; if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings };
switch (mode) { switch (mode) {
@@ -921,7 +988,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
return key.preventDefault(); 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); secret.type(key);
key.preventDefault(); key.preventDefault();
} }
@@ -985,7 +1052,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. */ /** 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) => { 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(); panel.leave();
}; };
@@ -999,8 +1066,11 @@ 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. // 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 detailsRoom = width - listWidth - 1 - MIN_CONVERSATION_WIDTH;
const detailsWidth = Math.min(detailsWidthPref ?? DETAILS_WIDTH, Math.max(DETAILS_WIDTH, detailsRoom)); const detailsWidth = Math.min(detailsWidthPref ?? DETAILS_WIDTH, Math.max(DETAILS_WIDTH, detailsRoom));
const detailsColumn = panel.show && detailsWidth <= detailsRoom; // The pane takes the details column's place, or the conversation's when there's no room beside it.
const detailsInPlace = panel.show && !detailsColumn; const paneColumn = pane !== null && detailsWidth <= detailsRoom;
const detailsColumn = !pane && panel.show && detailsWidth <= detailsRoom;
const detailsInPlace = !pane && panel.show && !detailsColumn;
const rightColumn = paneColumn || detailsColumn;
// The block's height: a row of padding on top, the text, then the model line inside it. // 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. // Padding row, text, a blank row, then the model line.
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 3; const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 3;
@@ -1044,6 +1114,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
inPlace={inPlace} inPlace={inPlace}
selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null} selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null}
onActivate={panel.activateById} onActivate={panel.activateById}
onEdit={panel.edit}
/> />
); );
@@ -1118,8 +1189,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
saveLayoutNow({ listWidth: null }); saveLayoutNow({ listWidth: null });
}} />} }} />}
<box flexDirection="column" flexGrow={1} minHeight={0}> <box flexDirection="column" flexGrow={1} minHeight={0}>
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation}> <box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation} onSizeChange={function (this: { height: number }) { setContentHeight(this.height); }}>
{settingsIndex !== null ? ( {pane && !paneColumn ? null : settingsIndex !== null ? (
<SettingsView <SettingsView
rows={settingsRows} rows={settingsRows}
server={serverSettingLines(serverConfig?.config ?? null)} server={serverSettingLines(serverConfig?.config ?? null)}
@@ -1171,7 +1242,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null} {workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null} {find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} actions={secret.actions} /> : null} {mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} actions={secret.actions} /> : null}
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? detailsWidth + 1 : 0) - 3} actions={queue.actions} /> : null} {queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (rightColumn ? detailsWidth + 1 : 0) - 3} actions={queue.actions} /> : null}
{mode !== "confirm" && questions.request && questions.draft ? <QuestionPanel {mode !== "confirm" && questions.request && questions.draft ? <QuestionPanel
request={questions.request} request={questions.request}
index={questions.draft.index} index={questions.draft.index}
@@ -1192,7 +1263,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
onCancel={closeOverlay} onCancel={closeOverlay}
/> />
) : null} ) : null}
{menu ? <ComposerMenu items={menu.items} selected={composerMenu.selected} empty={menu.empty} width={width - listWidth - (detailsColumn ? detailsWidth + 1 : 0) - 2} onPick={composerMenu.pick} /> : null} {menu ? <ComposerMenu items={menu.items} selected={composerMenu.selected} empty={menu.empty} width={width - listWidth - (rightColumn ? detailsWidth + 1 : 0) - 2} onPick={composerMenu.pick} /> : null}
{attach.pending.length > 0 ? ( {attach.pending.length > 0 ? (
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0} paddingLeft={2} paddingRight={2}> <box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
<text fg={colors.muted}>Attached:</text> <text fg={colors.muted}>Attached:</text>
@@ -1275,14 +1346,24 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
</box> </box>
) : null} ) : null}
</box> </box>
{detailsColumn ? ( {rightColumn ? (
<> <ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => {
<ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => { setDetailsWidthPref(null);
setDetailsWidthPref(null); saveLayoutNow({ detailsWidth: null });
saveLayoutNow({ detailsWidth: null }); }} />
}} /> ) : null}
{detailsPanel(false)} {detailsColumn ? detailsPanel(false) : null}
</> {/* One place in the tree in both layouts, so a narrower window doesn't restart its program. */}
{pane ? (
<TerminalPane
key={pane.id}
program={pane}
session={session}
focused={mode === "pane"}
onFocus={() => setMode("pane")}
onClose={closePane}
place={paneColumn ? { width: detailsWidth } : { left: showList ? listWidth + 1 : 0, height: contentHeight }}
/>
) : null} ) : null}
</box> </box>
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}> <box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
+15 -6
View File
@@ -1,7 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { MAX_DETAIL_FILES, type ChangedFile, type DetailsAction, type DetailsFold, type LineageLine, type ThreadDetails } from "../model/details.ts"; 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 { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
@@ -25,6 +25,8 @@ export function DetailsPanel(props: {
readonly selected: string | null; readonly selected: string | null;
readonly unfolded: ReadonlySet<DetailsFold>; readonly unfolded: ReadonlySet<DetailsFold>;
readonly onActivate: (id: string) => void; 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. */ /** Shown when there are no details, which defaults to no thread being selected. */
readonly empty?: string; readonly empty?: string;
}) { }) {
@@ -48,7 +50,7 @@ export function DetailsPanel(props: {
{!details ? ( {!details ? (
<text fg={colors.faint}>{props.empty ?? "No thread selected."}</text> <text fg={colors.faint}>{props.empty ?? "No thread selected."}</text>
) : ( ) : (
<Sections details={details} inner={inner} loading={props.loading} unfolded={props.unfolded} selected={props.selected} onActivate={props.onActivate} /> <Sections details={details} inner={inner} loading={props.loading} unfolded={props.unfolded} selected={props.selected} onActivate={props.onActivate} onEdit={props.onEdit} />
)} )}
</scrollbox> </scrollbox>
</box> </box>
@@ -60,7 +62,7 @@ interface LineProps {
readonly onActivate: (id: string) => void; 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<DetailsFold> } & LineProps) { function Sections({ details, inner, loading, unfolded, selected, onActivate, onEdit }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet<DetailsFold>; readonly onEdit: (path: string) => void } & LineProps) {
const { branch, changes, git, tasks } = details; const { branch, changes, git, tasks } = details;
const files = changes?.files ?? []; const files = changes?.files ?? [];
const line = { selected, onActivate }; const line = { selected, onActivate };
@@ -102,9 +104,16 @@ function Sections({ details, inner, loading, unfolded, selected, onActivate }: {
{changes ? ( {changes ? (
<Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}> <Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}>
{files.slice(0, MAX_DETAIL_FILES).map((file) => ( {files.slice(0, MAX_DETAIL_FILES).map((file) => (
<Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}> <box key={file.path} flexDirection="column">
<FileLine file={file} inner={inner} /> <Selectable id={`diff:${file.path}`} {...line} inner={inner}>
</Selectable> <FileLine file={file} inner={inner} />
</Selectable>
{selected === `diff:${file.path}` && !file.path.endsWith("/") ? (
<box flexDirection="row" marginLeft={1}>
<Button label="▸ Edit" shortcut="o" plain onPress={() => onEdit(file.path)} />
</box>
) : null}
</box>
))} ))}
{files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null} {files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null}
{files.length === 0 ? <text fg={colors.faint}>Working tree clean</text> : null} {files.length === 0 ? <text fg={colors.faint}>Working tree clean</text> : null}
+186
View File
@@ -0,0 +1,186 @@
import { EmbeddedTerminalRenderable, type EmbeddedTerminalDataSource } from "@opentui/core";
import { extend } from "@opentui/react";
import { useEffect, useRef } from "react";
import type { T3Session } from "../client/session.ts";
import { BAR } from "./edges.ts";
import type { TerminalTarget } from "./terminalAttach.ts";
import { truncate } from "./text.ts";
import { colors } from "./theme.ts";
import { useEvent } from "./useEvent.ts";
declare module "@opentui/react" {
interface OpenTUIComponents {
embeddedTerminal: typeof EmbeddedTerminalRenderable;
}
}
extend({ embeddedTerminal: EmbeddedTerminalRenderable });
/** What runs in the pane: one of T3's terminals, or a program run here, like $EDITOR. */
export type PaneProgram =
| { readonly kind: "server"; readonly id: string; readonly title: string; readonly target: TerminalTarget }
| { readonly kind: "local"; readonly id: string; readonly title: string; readonly command: readonly string[]; readonly cwd?: string | undefined; readonly onExit: (code: number) => void };
/** How the pane talks to its program once it knows its size. */
interface Link {
readonly send: (data: Uint8Array, source: EmbeddedTerminalDataSource) => void;
readonly resize: (cols: number, rows: number) => void;
readonly stop: () => void;
}
/**
* A terminal in the right-hand column: keys go to its program while it has focus, its size
* follows the column, and it closes when the program exits. Key it by the program's id.
*/
export function TerminalPane(props: {
readonly program: PaneProgram;
readonly session: T3Session;
readonly focused: boolean;
/** A column this wide beside the conversation, or the conversation's place: from `left`, `height` tall. */
readonly place: { readonly width: number } | { readonly left: number; readonly height: number };
readonly onFocus: () => void;
readonly onClose: (message?: string) => void;
}) {
const { program, focused, place } = props;
const terminal = useRef<EmbeddedTerminalRenderable | null>(null);
const link = useRef<Link | null>(null);
const onFocus = useEvent(props.onFocus);
const onClose = useEvent(props.onClose);
useEffect(() => () => link.current?.stop(), []);
useEffect(() => {
const term = terminal.current;
if (!term) return;
if (focused) term.focus();
else term.blur();
}, [focused]);
// A click the program takes as a mouse event still focuses the terminal; that is the pane's focus too.
useEffect(() => {
const term = terminal.current;
term?.on("focused", onFocus);
return () => void term?.off("focused", onFocus);
}, [onFocus]);
const start = (term: EmbeddedTerminalRenderable, cols: number, rows: number) => {
paint(term);
link.current = program.kind === "server" ? attachServer(props.session, program.target, term, cols, rows, onClose) : spawnLocal(program, term, cols, rows, onClose);
};
return (
<box
{...("width" in place ? { width: place.width, flexShrink: 0 } : { position: "absolute", left: place.left, right: 0, top: 0, height: place.height })}
minHeight={0}
flexDirection="column"
overflow="hidden"
backgroundColor={colors.panel}
border={["left"]}
customBorderChars={BAR}
borderColor={focused ? colors.accent : colors.panel}
onMouseDown={onFocus}
>
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1}>
<text fg={focused ? colors.text : colors.muted} wrapMode="none">{truncate(program.title, Math.max(8, ("width" in place ? place.width : 80) - 17))}</text>
<box flexGrow={1} />
<text fg={colors.faint} wrapMode="none" flexShrink={0}>{focused ? "ctrl+\\ leave" : "ctrl+\\ focus"}</text>
</box>
<embeddedTerminal
ref={terminal}
flexGrow={1}
minHeight={0}
width="100%"
onTerminalResize={function (this: EmbeddedTerminalRenderable, cols: number, rows: number) {
if (link.current) link.current.resize(cols, rows);
else start(this, cols, rows);
}}
onData={(data, source) => link.current?.send(data, source)}
/>
</box>
);
}
/** The program's default colours are the pane's. */
function paint(term: EmbeddedTerminalRenderable): void {
term.write(`\x1b]10;${colors.text}\x1b\\\x1b]11;${colors.panel}\x1b\\`);
}
/**
* One of T3's terminals: its scrollback, then live output; typed keys go to it. Only keys:
* the emulator's own answers to queries replayed from history must not reach the shell.
*/
function attachServer(session: T3Session, target: TerminalTarget, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
const { threadId, terminalId } = target;
const decoder = new TextDecoder();
let stopped = false;
let detach = () => {};
const end = (message?: string) => {
if (stopped) return;
stopped = true;
detach();
close(message);
};
detach = session.attachTerminal(
{ threadId, terminalId, cwd: target.cwd, worktreePath: target.worktreePath, cols, rows },
(event) => {
if (stopped) return;
switch (event.type) {
case "snapshot":
case "restarted":
term.write("\x1bc");
paint(term);
term.write(event.snapshot.history);
return;
case "output":
term.write(event.data);
return;
case "cleared":
term.write("\x1b[H\x1b[2J");
return;
case "error":
term.write(`\r\n\x1b[31m[${event.message}]\x1b[0m\r\n`);
return;
case "exited":
return end(`${target.label} exited`);
case "closed":
return end("Terminal closed");
}
},
(error) => end(error ? `Terminal: ${error}` : undefined),
);
// A fake or failing session can end the stream before it returns.
if (stopped) detach();
return {
send: (data, source) => {
if (source === "input" && !stopped) session.writeTerminal(threadId, terminalId, decoder.decode(data, { stream: true })).catch(() => {});
},
resize: (next, height) => void session.resizeTerminal(threadId, terminalId, next, height).catch(() => {}),
stop: () => {
stopped = true;
detach();
},
};
}
/** A program run here on its own pty, answering its terminal queries through the emulator. */
function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
let stopped = false;
const child = Bun.spawn([...program.command], {
...(program.cwd ? { cwd: program.cwd } : {}),
terminal: { cols, rows, data: (_pty, data) => term.write(data) },
});
void child.exited.then((code) => {
if (stopped) return;
stopped = true;
program.onExit(code);
close();
});
return {
send: (data) => void child.terminal?.write(data),
resize: (next, height) => child.terminal?.resize(next, height),
stop: () => {
if (stopped) return;
stopped = true;
child.kill();
},
};
}
+19 -8
View File
@@ -4,23 +4,34 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
/** $VISUAL or $EDITOR (falling back to vi) on `file`, through the shell so EDITOR="code --wait" works. */
export function editorCommand(file: string): string[] {
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
return [process.env.SHELL || "sh", "-c", `${editor} "$1"`, "sh", file];
}
/** A scratch copy of `text` to edit: `read` returns what was saved, `remove` cleans up. */
export function scratchFile(text: string): { readonly path: string; readonly read: () => string; readonly remove: () => void } {
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
const path = join(dir, "prompt.md");
writeFileSync(path, text);
return { path, read: () => readFileSync(path, "utf8").replace(/\n$/, ""), remove: () => rmSync(dir, { recursive: true, force: true }) };
}
/** /**
* Hands the terminal to $VISUAL or $EDITOR on a copy of `text` and returns what was saved, * Hands the terminal to $VISUAL or $EDITOR on a copy of `text` and returns what was saved,
* or null if the editor failed. The renderer is suspended meanwhile. * or null if the editor failed. The renderer is suspended meanwhile.
*/ */
export async function editInEditor(renderer: CliRenderer, text: string): Promise<string | null> { export async function editInEditor(renderer: CliRenderer, text: string): Promise<string | null> {
const editor = process.env.VISUAL || process.env.EDITOR || "vi"; const file = scratchFile(text);
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
const file = join(dir, "prompt.md");
writeFileSync(file, text);
await renderer.suspend(); await renderer.suspend();
try { try {
// Through the shell, so EDITOR="code --wait" works. const [command, ...args] = editorCommand(file.path);
const result = spawnSync(process.env.SHELL || "sh", ["-c", `${editor} "$1"`, "sh", file], { stdio: "inherit" }); const result = spawnSync(command!, args, { stdio: "inherit" });
if (result.status !== 0) return null; if (result.status !== 0) return null;
return readFileSync(file, "utf8").replace(/\n$/, ""); return file.read();
} finally { } finally {
rmSync(dir, { recursive: true, force: true }); file.remove();
await renderer.resume(); await renderer.resume();
renderer.requestRender(); renderer.requestRender();
} }
+9 -1
View File
@@ -42,6 +42,8 @@ export function useDetails(deps: {
/** A step of a running git action, shown until the next. */ /** A step of a running git action, shown until the next. */
readonly progress: (text: string) => void; readonly progress: (text: string) => void;
readonly openThread: (id: ThreadId) => void; readonly openThread: (id: ThreadId) => void;
/** A changed file in $EDITOR, in the terminal pane. */
readonly editFile: (path: string, cwd: string | null) => void;
/** The panel takes the keys, or gives them back. */ /** The panel takes the keys, or gives them back. */
readonly focus: (focused: boolean) => void; readonly focus: (focused: boolean) => void;
}) { }) {
@@ -193,6 +195,11 @@ export function useDetails(deps: {
deps.focus(false); deps.focus(false);
}; };
const selectedAction = () => actions.find((candidate) => candidate.id === selected); const selectedAction = () => actions.find((candidate) => candidate.id === selected);
const selectedFile = (() => {
const action = selectedAction();
return action?.kind === "diff" && action.path && !action.path.endsWith("/") ? action.path : null;
})();
const edit = (path: string) => deps.editFile(path, cwd);
const focusKey: Binding = { keys: ["l", "→"], run: focus, hint: "details", ...(thread ? { command: { id: "focus-details", title: "Focus thread details" } } : {}) }; const focusKey: Binding = { keys: ["l", "→"], run: focus, hint: "details", ...(thread ? { command: { id: "focus-details", title: "Focus thread details" } } : {}) };
const toggleKey: Binding = { keys: ["d"], run: () => setPref(!show), command: { id: "details", title: show ? "Hide thread details" : "Show thread details", keywords: ["panel", "info"] } }; const toggleKey: Binding = { keys: ["d"], run: () => setPref(!show), command: { id: "details", title: show ? "Hide thread details" : "Show thread details", keywords: ["panel", "info"] } };
@@ -232,11 +239,12 @@ export function useDetails(deps: {
}, },
hint: "toggle automation", hint: "toggle automation",
}, },
selectedFile && { keys: ["o"], run: () => edit(selectedFile), hint: "edit file" },
{ keys: ["esc"], run: () => (deps.diff ? setDiff(null) : leave()), hint: "back" }, { keys: ["esc"], run: () => (deps.diff ? setDiff(null) : leave()), hint: "back" },
{ keys: ["h", "←"], run: leave }, { keys: ["h", "←"], run: leave },
); );
return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, unfolded, activateById, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } }; return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, unfolded, activateById, edit, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } };
} }
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
+24 -6
View File
@@ -10,7 +10,7 @@ import type { PaletteCommand, Picker, PickerItem } from "../model/palette.ts";
import { newTerminalInput, preferredEditor, resolveBranchSelectionTarget, worktreeSetupNote } from "../model/workspace.ts"; import { newTerminalInput, preferredEditor, resolveBranchSelectionTarget, worktreeSetupNote } from "../model/workspace.ts";
import type { Confirmation } from "./ConfirmBar.tsx"; import type { Confirmation } from "./ConfirmBar.tsx";
import { splitPatch, type DiffState } from "./DiffView.tsx"; import { splitPatch, type DiffState } from "./DiffView.tsx";
import { attachTerminal } from "./terminalAttach.ts"; import { attachTerminal, type TerminalTarget } from "./terminalAttach.ts";
type Command = PaletteCommand & { readonly run: () => void }; type Command = PaletteCommand & { readonly run: () => void };
@@ -25,6 +25,8 @@ export function useWorkspace(input: {
readonly draft: boolean; readonly draft: boolean;
readonly diff: DiffState | null; readonly diff: DiffState | null;
readonly openPicker: (picker: Picker) => void; readonly openPicker: (picker: Picker) => void;
/** Shows a terminal in the pane beside the conversation. */
readonly openPane: (target: TerminalTarget) => void;
readonly confirm: (confirmation: Confirmation) => void; readonly confirm: (confirmation: Confirmation) => void;
readonly run: (label: string, action: () => Promise<unknown>) => void; readonly run: (label: string, action: () => Promise<unknown>) => void;
readonly say: (message: string, bad?: boolean) => void; readonly say: (message: string, bad?: boolean) => void;
@@ -76,23 +78,35 @@ export function useWorkspace(input: {
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id); const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
const cwd = thread?.worktreePath ?? project?.workspaceRoot; const cwd = thread?.worktreePath ?? project?.workspaceRoot;
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal); const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => { /** In the pane, or with the whole screen. */
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">, fullScreen = false) => {
if (!thread) return; if (!thread) return;
const target = { const target = {
threadId: thread.id, threadId: thread.id,
...terminal, ...terminal,
label: resolveTerminalSessionLabel(terminal.terminalId, terminal), label: resolveTerminalSessionLabel(terminal.terminalId, terminal),
}; };
if (!fullScreen) return input.openPane(target);
void attachTerminal(renderer, session, target, (message) => { void attachTerminal(renderer, session, target, (message) => {
if (message) say(message); if (message) say(message);
}); });
}; };
const newTerminal = () => { const newTerminal = (fullScreen = false) => {
if (!thread || !project) return say("Open a thread with a project folder first.", true); if (!thread || !project) return say("Open a thread with a project folder first.", true);
const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live"); const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live");
run("Terminal opened", async () => { run("Terminal opened", async () => {
await session.openTerminal(request); await session.openTerminal(request);
enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" }); enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" }, fullScreen);
});
};
/** The old way in: the terminal takes the screen until ctrl+j. */
const attachFullScreen = () => {
if (!thread || input.draft) return say("Open a thread first.", true);
if (threadTerminals.length === 0) return newTerminal(true);
if (threadTerminals.length === 1) return enterTerminal(threadTerminals[0]!, true);
openPicker({
placeholder: "Attach full screen",
groups: [{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:full:${terminal.terminalId}`, title: label(terminal), run: () => enterTerminal(terminal, true) })) }],
}); });
}; };
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => { const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
@@ -114,7 +128,10 @@ export function useWorkspace(input: {
}; };
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them. // Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
const terminalActionItems = (): PickerItem[] => { const terminalActionItems = (): PickerItem[] => {
const items: PickerItem[] = [{ id: "terminal:new", title: "New terminal", run: newTerminal }]; const items: PickerItem[] = [
{ id: "terminal:new", title: "New terminal", run: () => newTerminal() },
{ id: "terminal:full-screen", title: "Attach full screen", hint: "ctrl+j returns", run: attachFullScreen },
];
for (const action of ["close", "clear"] as const) { for (const action of ["close", "clear"] as const) {
const targets = terminalItems(action); const targets = terminalItems(action);
if (targets.length === 0) continue; if (targets.length === 0) continue;
@@ -269,7 +286,8 @@ export function useWorkspace(input: {
const commands: Command[] = thread && !input.draft ? [ const commands: Command[] = thread && !input.draft ? [
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal }, { id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
{ id: "terminal-picker", title: "Terminals…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker }, { id: "terminal-picker", title: "Terminals…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker },
{ id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: newTerminal }, { id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: () => newTerminal() },
{ id: "terminal-full-screen", title: "Attach terminal full screen", keywords: ["shell", "console", "attach"], run: attachFullScreen },
...terminalItems("close"), ...terminalItems("clear"), ...terminalItems("close"), ...terminalItems("clear"),
{ id: "branches", title: "Branches and worktrees…", shortcut: "b", keywords: ["git", "switch", "ref", "create", "remove", "pull"], run: branchPicker }, { id: "branches", title: "Branches and worktrees…", shortcut: "b", keywords: ["git", "switch", "ref", "create", "remove", "pull"], run: branchPicker },
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor }, { id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
+9 -1
View File
@@ -41,6 +41,9 @@ export function fakeSession(
/** 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>;
/** The thread's terminals on the server, and what attaching to one streams. */
readonly terminals?: readonly unknown[];
readonly terminalEvents?: readonly unknown[];
readonly failures?: Record<string, string>; readonly failures?: Record<string, string>;
} = {}, } = {},
) { ) {
@@ -58,7 +61,12 @@ export function fakeSession(
watchServerConfig: live({ status: "loading", config: null }), watchServerConfig: live({ status: "loading", config: null }),
watchServers: live({ status: "live", items: [] }), watchServers: live({ status: "live", items: [] }),
watchAutomations: live({ status: "live", items: [] }), watchAutomations: live({ status: "live", items: [] }),
watchTerminals: live({ status: "live", items: [] }), watchTerminals: live({ status: "live", items: state.terminals ?? [] }),
attachTerminal: (input: unknown, onEvent: (event: unknown) => void) => {
calls.push({ method: "attachTerminal", args: [input] });
for (const event of state.terminalEvents ?? []) onEvent(event);
return () => calls.push({ method: "detachTerminal", args: [] });
},
watchVcs: (_cwd: string, listener: (value: unknown) => void) => live(state.vcs ?? { status: "loading", local: null, remote: null })(listener), watchVcs: (_cwd: string, listener: (value: unknown) => void) => live(state.vcs ?? { status: "loading", local: null, remote: null })(listener),
}; };
const session = new Proxy(known, { const session = new Proxy(known, {
+111
View File
@@ -0,0 +1,111 @@
import { afterEach, describe, expect, test } from "bun:test";
import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx";
let app: Awaited<ReturnType<typeof renderApp>> | null = null;
const open = async (...args: Parameters<typeof renderApp>) => (app = await renderApp(...args));
afterEach(() => {
app?.destroy();
app = null;
});
const terminal = { threadId: v2ThreadId, terminalId: "term-1", cwd: "/workspace/project", worktreePath: null, status: "running", pid: 42, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "", updatedAt: "2026-06-20T00:00:00.000Z" };
const snapshot = { type: "snapshot", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z", snapshot: { history: "earlier output\r\nuser@host:~$ " } };
const withTerminal = (events: readonly unknown[] = [snapshot]) => fakeSession({ terminals: [terminal], terminalEvents: events });
describe("terminal pane", () => {
test("ctrl+j opens the thread's terminal in the pane, with its scrollback, and takes every key", async () => {
const app = await open({ session: withTerminal() });
await app.press("j", { ctrl: true });
expect(app.frame()).toContain("Terminal · Terminal 1");
expect(app.frame()).toContain("user@host:~$");
expect(app.calls("attachTerminal")).toHaveLength(1);
expect(app.hints()).toBe("ctrl+\\ leave pane");
await app.press("q");
await app.press("escape");
expect(app.calls("writeTerminal").map((call) => call.args[2])).toEqual(["q", "\x1b"]);
// q went to the shell rather than quitting.
expect(app.frame()).toContain("user@host:~$");
});
test("ctrl+\\ leaves the pane and comes back to it; a click focuses it too", async () => {
const app = await open({ session: withTerminal() });
await app.press("j", { ctrl: true });
await app.press("\\", { ctrl: true });
expect(app.hints()).toStartWith("ctrl+\\ pane · j/k threads");
await app.press("j");
expect(app.calls("writeTerminal")).toHaveLength(0);
await app.press("\\", { ctrl: true });
expect(app.hints()).toBe("ctrl+\\ leave pane");
await app.press("\\", { ctrl: true });
const shell = app.find("user@host");
await app.click(shell.x, shell.y);
expect(app.hints()).toBe("ctrl+\\ leave pane");
});
test("it takes the details column's place, and the conversation's when the window is narrow", async () => {
const wide = await open({ width: 200, session: withTerminal() });
await wide.press("j", { ctrl: true });
const title = wide.find("Terminal · Terminal 1");
expect(title.x).toBeGreaterThan(200 - 38 - 1);
expect(wide.frame()).not.toContain("/workspace/project ·");
wide.destroy();
const narrow = await open({ width: 100, session: withTerminal() });
await narrow.press("j", { ctrl: true });
expect(narrow.find("Terminal · Terminal 1").x).toBeLessThan(50);
});
test("the pane closes when the terminal does", async () => {
const app = await open({ session: withTerminal([snapshot, { type: "closed", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z" }]) });
await app.press("j", { ctrl: true });
expect(app.frame()).not.toContain("Terminal · Terminal 1");
expect(app.hints()).toBe("Terminal closed");
});
test("the T picker can still attach full screen", async () => {
const app = await open({ session: withTerminal() });
await app.press("T");
expect(app.frame()).toContain("Attach full screen");
});
test("ctrl+g writes the message in $EDITOR in the pane, and what's saved comes back", async () => {
const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR };
delete process.env.VISUAL;
// Run as `$EDITOR "$1"`: this one waits a moment, overwrites the file and exits.
process.env.EDITOR = "sleep 0.5; printf 'from the editor' >";
try {
const app = await open();
await app.press("i");
await app.type("draft");
await app.press("g", { ctrl: true });
expect(app.frame()).toContain("Message · save and quit");
expect(app.hints()).toBe("ctrl+\\ leave pane");
for (let tries = 0; tries < 40 && app.frame().includes("Message · save and quit"); tries++) await app.settle(50);
expect(app.frame()).not.toContain("Message · save and quit");
expect(app.frame()).toContain("from the editor");
expect(app.hints()).toStartWith("enter send");
} finally {
if (previous.visual !== undefined) process.env.VISUAL = previous.visual;
if (previous.editor === undefined) delete process.env.EDITOR;
else process.env.EDITOR = previous.editor;
}
});
});
describe("editing a changed file", () => {
const vcs = {
status: "live",
local: { isRepo: true, hasPrimaryRemote: true, isDefaultRef: true, refName: "main", hasWorkingTreeChanges: true, workingTree: { files: [{ path: "README.md", insertions: 2, deletions: 1 }], insertions: 2, deletions: 1 } },
remote: { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null },
};
test("o on a file in Changes, or its ▸ Edit, opens it in the pane when it's on this machine", async () => {
const app = await open({ width: 200, session: fakeSession({ vcs }) });
await app.press("l");
expect(app.hints()).toContain("o edit file");
expect(app.frame()).toContain("▸ Edit o");
await app.press("o");
// The fixture's workspace isn't on this machine.
expect(app.hints()).toBe("README.md isn't on this machine.");
});
});