diff --git a/src/ui/App.tsx b/src/ui/App.tsx index c5c3851..e1cda9a 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -36,7 +36,8 @@ import { useModelPicker } from "./useModelPicker.ts"; import { useQuestion } from "./useQuestion.ts"; import { useThreadMenu } from "./useThreadMenu.ts"; import { editorCommand, scratchFile } from "./editor.ts"; -import { TerminalPane, type PaneProgram } from "./TerminalPane.tsx"; +import { TerminalPane } from "./TerminalPane.tsx"; +import { usePanes, type Placement } from "./usePanes.ts"; import { Palette } from "./Palette.tsx"; import { ApprovalPanel } from "./ApprovalPanel.tsx"; import { LiveStatus } from "./LiveStatus.tsx"; @@ -56,7 +57,7 @@ import { BAR, NO_BORDER } from "./edges.ts"; import { ThreadList } from "./ThreadList.tsx"; import { useTurns } from "./useTurns.ts"; import { ThreadView, type ConversationMouse, type ConversationTarget } from "./ThreadView.tsx"; -import { Button, ResizeHandle } from "./Button.tsx"; +import { Button, ResizeHandle, Tab, Tabs } from "./Button.tsx"; import { HintBar } from "./HintBar.tsx"; import { bindingFor, commandsFor, fromCommand, hinted, hintsFor, keys, type Binding } from "../model/keymap.ts"; import { firstLine, truncate } from "./text.ts"; @@ -93,6 +94,11 @@ 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 fewest rows the terminal drawer keeps, and leaves the conversation; with less room it takes the conversation's place. */ +const MIN_DRAWER_ROWS = 6; +const MIN_CONVERSATION_ROWS = 10; +/** The drawer's default share of the conversation's height, and the message editor's of the window's. */ +const DRAWER_SHARE = 0.4; /** The conversation this wide or wider shows diffs side by side. */ const SPLIT_DIFF_WIDTH = 140; @@ -133,8 +139,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui const [detailsWidthPref, setDetailsWidthPref] = useState(props.layout?.detailsWidth ?? null); const [listHidden, setListHidden] = useState(props.layout?.listHidden ?? false); const [detailsPref, setDetailsPrefState] = useState(props.layout?.details ?? null); - const layoutNow = useRef({ listWidth: listWidthPref, detailsWidth: detailsWidthPref, listHidden, details: detailsPref }); - layoutNow.current = { listWidth: listWidthPref, detailsWidth: detailsWidthPref, listHidden, details: detailsPref }; + const [drawerHeightPref, setDrawerHeightPref] = useState(props.layout?.drawerHeight ?? null); + const [placement, setPlacement] = useState(props.layout?.terminalPlacement ?? "bottom"); + const layoutNow = useRef({ listWidth: listWidthPref, detailsWidth: detailsWidthPref, listHidden, details: detailsPref, drawerHeight: drawerHeightPref, terminalPlacement: placement }); + layoutNow.current = { listWidth: listWidthPref, detailsWidth: detailsWidthPref, listHidden, details: detailsPref, drawerHeight: drawerHeightPref, terminalPlacement: placement }; /** Kept for the next run; a failed save only costs that. */ const saveLayoutNow = (change: Partial = {}) => void saveLayout({ ...layoutNow.current, ...change }).catch(() => {}); const setDetailsPref = (show: boolean) => { @@ -147,12 +155,13 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }; const showList = !attached && !listHidden; /** The edge being dragged. */ - const [resizing, setResizing] = useState<"list" | "details" | null>(null); + const [resizing, setResizing] = useState<"list" | "details" | "drawer" | null>(null); + /** Where a drag of the drawer's edge started, and the drawer's height then. */ + const drawerDrag = useRef({ y: 0, height: 0 }); 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. */ + /** The conversation's height, for the column when it takes that place; and with the drawer under it, for the drawer. */ const [contentHeight, setContentHeight] = useState(0); + const [areaHeight, setAreaHeight] = useState(0); const [config, setConfig] = useState(props.config); const [settingsIndex, setSettingsIndex] = useState(null); const [serverConfig, setServerConfig] = useState(null); @@ -534,17 +543,6 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }, }); - /** 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, @@ -555,19 +553,38 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui draft: draft !== null, diff, openPicker, - openPane: (target) => showPane({ kind: "server", id: `server:${target.threadId}:${target.terminalId}`, title: `Terminal · ${target.label}`, target }), + openPane: (target) => panes.openTerminal(target), confirm, run, say, }); + const panes = usePanes({ + threadId: draft ? undefined : threadId, + terminals: workspace.tabs, + placement, + column: panel.show, + columnPref: detailsPref, + setColumnPref: setDetailsPrefState, + focused: mode === "pane", + focus: (focused) => setMode((current) => (focused ? "pane" : current === "pane" ? "nav" : current)), + say, + }); + const movePlacement = () => { + const next = placement === "bottom" ? "side" : "bottom"; + setPlacement(next); + saveLayoutNow({ terminalPlacement: next }); + }; + useEffect(() => { + if (mode === "details") panes.setColumnTab("details"); + }, [mode]); - /** The composer's text in $EDITOR, in the pane; what's saved comes back when it exits. */ + /** The composer's text in $EDITOR, in the composer's place; what's saved comes back when it exits. */ const openEditor = () => { const composer = composerRef.current; if (!composer) return; const key = composerKey; const file = scratchFile(composerText(composer)); - showPane({ + panes.openMessage({ kind: "local", id: `message:${file.path}`, title: "Message · save and quit to bring it back", @@ -581,14 +598,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }, }); }; - /** A workspace file in $EDITOR, in the pane, when the workspace is on this machine. */ + /** A workspace file in $EDITOR, in the column's Editor tab, 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: () => {} }); + panes.openEditor({ 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. */ + /** A click on a link opens it in the browser; on a path to a workspace file, in the column's editor. A drag doesn't. */ const openAt = (x: number, y: number) => { if (renderer.getSelection()?.getSelectedText()) return; const url = renderer.getLinkAt(x, y); @@ -808,8 +825,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui // Keys that work wherever there's no line input to type into. 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 terminalKey: Binding = { keys: ["ctrl+j"], run: () => panes.toggleTerminal(workspace.openTerminal) }; + const paneKey = panes.keys.pane; 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) }; @@ -821,6 +838,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui paletteKey, terminalKey, editorKey, + panes.keys.tabs, { keys: lineInput ? ["pagedown"] : ["pagedown", "ctrl+d"], run: () => scrollPage(1) }, { keys: lineInput ? ["pageup"] : ["pageup", "ctrl+u"], run: () => scrollPage(-1) }, !attached && nextThreadKey, @@ -872,6 +890,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui hinted(paletteKey, "commands"), { keys: ["q"], run: quit, hint: "quit", command: { id: "quit", title: "Quit t3tui", keywords: ["exit"] } }, panel.keys.toggle, + panes.keys.column.map((binding) => ({ ...binding, run: () => { + if (mode === "details") panel.leave(); + binding.run?.(); + } })), { keys: ["e"], run: () => setExpandAll((value) => !value), command: { id: "expand", title: expandAll ? "Collapse work" : "Expand all work", keywords: ["fold", "tool calls"] } }, thread?.history.hasMore && { keys: ["o"], run: loadEarlier, command: { id: "earlier", title: "Load earlier turns", keywords: ["history", "older"] } }, !attached && { keys: ["z"], run: () => setShowFolded((value) => !value), command: { id: "settled", title: showFolded ? "Hide settled threads" : "Show settled threads", keywords: ["snoozed", "archive"] } }, @@ -894,7 +916,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui // 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"] } }, + panes.terminal && { keys: [], run: panes.hideTerminal, command: { id: "pane-close", title: "Hide the terminal", keywords: ["detach", "drawer", "close"] } }, + threadId && !draft && { keys: [], run: movePlacement, command: { id: "terminal-placement", title: placement === "bottom" ? "Move terminal to the side" : "Move terminal below", keywords: ["drawer", "column", "right", "bottom", "layout"] } }, { 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, @@ -981,7 +1004,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui return { layers: [confirmKeys], hints: confirmKeys }; } } - if (mode === "pane" && paneKey) return { layers: [[paneKey]], hints: [paneKey] }; + // In the drawer, ctrl+j hides it again, as it leaves a terminal attached full screen. + if (mode === "pane" && paneKey) return { layers: [keys(panes.keys.focused, panes.focusedPane === "terminal" && terminalKey)], 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) { @@ -1094,11 +1118,20 @@ 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)); - // 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; + // The right-hand column, with its tabs, goes beside the conversation, or in its place when there's no room. + // It stays in the tree while it holds a program, hidden or not, so the program keeps running. + const columnInPlace = detailsWidth > detailsRoom; + const columnMounted = panel.show || panes.editor !== null || (placement === "side" && panes.terminal !== null); + // In the conversation's place, Details gives way to a diff, settings and the like, as the conversation does. + const detailsGivesWay = settingsIndex !== null || (mode === "pull-request" && pullRequests.view !== null) || diff !== null || draft !== null || mode === "find" || !threadId; + const columnVisible = panel.show && !(columnInPlace && panes.columnTab === "details" && detailsGivesWay); + const rightColumn = columnVisible && !columnInPlace; + // The drawer leaves the conversation some rows, or takes its place when it can't. + const drawer = placement === "bottom" ? panes.terminal : null; + const drawerRoom = areaHeight - MIN_CONVERSATION_ROWS; + const drawerInPlace = drawer !== null && drawerRoom < MIN_DRAWER_ROWS; + const drawerHeight = Math.max(MIN_DRAWER_ROWS, Math.min(drawerRoom, drawerHeightPref ?? Math.round(areaHeight * DRAWER_SHARE))); + const conversationHidden = (columnVisible && columnInPlace) || drawerInPlace; 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. @@ -1133,6 +1166,23 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui return { name, rest: [...options, mode].filter(Boolean).join(" · ") }; })(); const composerBarColor = mode === "input" ? colors.accent : colors.border; + // The thread's terminal, in the drawer or the column, with a tab for each of its terminals. + const terminalTarget = panes.terminal; + const terminalPane = terminalTarget ? ( + ({ id: tab.terminalId, label: tab.label }))} active={terminalTarget.terminalId} onPick={(id) => panes.selectTab(panes.tabs.findIndex((tab) => tab.terminalId === id))}> + + + } + onFocus={() => panes.enter("terminal")} + onClose={(note) => panes.terminalEnded(terminalTarget, note)} + /> + ) : null; const detailsPanel = (inPlace: boolean) => ( - resizing === "list" ? setListWidthPref(clampListWidth(event.x, width)) : setDetailsWidthPref(Math.max(MIN_DETAILS_WIDTH, Math.min(width - event.x - 1, detailsRoom))), + resizing === "list" + ? setListWidthPref(clampListWidth(event.x, width)) + : resizing === "details" + ? setDetailsWidthPref(Math.max(MIN_DETAILS_WIDTH, Math.min(width - event.x - 1, detailsRoom))) + : setDrawerHeightPref(Math.max(MIN_DRAWER_ROWS, Math.min(drawerRoom, drawerDrag.current.height + drawerDrag.current.y - event.y))), onMouseUp: () => { setResizing(null); saveLayoutNow(); @@ -1219,8 +1273,9 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui saveLayoutNow({ listWidth: null }); }} />} - - {pane && !paneColumn ? null : settingsIndex !== null ? ( + + + {conversationHidden ? null : settingsIndex !== null ? ( ) : draft ? ( - ) : threadId && detailsInPlace && mode !== "find" ? ( - - {detailsPanel(true)} - ) : threadId ? ( )} + {drawer ? ( + <> + {drawerInPlace ? null : ( + { + drawerDrag.current = { y: event.y, height: drawerHeight }; + setResizing("drawer"); + }} + onReset={() => { + setDrawerHeightPref(null); + saveLayoutNow({ drawerHeight: null }); + }} + /> + )} + + {terminalPane} + + + ) : null} + {workspace.note ? {workspace.note} : null} {find.open ? setMode("nav")} /> : null} {mode !== "confirm" && secret.request ? : null} @@ -1304,8 +1377,21 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui ) : null} {working && threadId && !draft && !pendingApproval ? : null} + {panes.message ? ( + + {panes.message.title}} + onFocus={() => panes.enter("message")} + onClose={panes.messageClosed} + /> + + ) : null} {threadId || draft ? ( - + {pendingApproval && !draft ? ( @@ -1393,18 +1479,42 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui 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 }} - /> + {/* One place in the tree beside the conversation or in its place, so a narrower window doesn't restart its programs. */} + {columnMounted ? ( + + {panes.columnTabs.length > 1 ? ( + + panes.setColumnTab(id as typeof panes.columnTab)} /> + {"{ }"} + + ) : null} + {panes.columnTab === "details" ? detailsPanel(columnInPlace) : null} + {panes.editor ? ( + + {truncate(panes.editor.title, Math.max(8, (columnInPlace ? width - listWidth : detailsWidth) - 17))}} + onFocus={() => panes.enter("editor")} + onClose={panes.editorClosed} + /> + + ) : null} + {placement === "side" && panes.terminal ? ( + + {terminalPane} + + ) : null} + ) : null} diff --git a/src/ui/DetailsPanel.tsx b/src/ui/DetailsPanel.tsx index d5d9d4d..9762ee9 100644 --- a/src/ui/DetailsPanel.tsx +++ b/src/ui/DetailsPanel.tsx @@ -37,10 +37,10 @@ export function DetailsPanel(props: { return ( void }; /** How the pane talks to its program once it knows its size. */ @@ -30,19 +29,20 @@ interface Link { } /** - * 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. + * A terminal filling its box: the drawer, a tab of the right-hand column or the composer's + * place. Keys go to its program while it has focus, its size follows the box, 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 }; + /** The row above the terminal: its title, or the drawer's tabs. */ + readonly header: ReactNode; readonly onFocus: () => void; readonly onClose: (message?: string) => void; }) { - const { program, focused, place } = props; + const { program, focused } = props; const terminal = useRef(null); const link = useRef(null); const onFocus = useEvent(props.onFocus); @@ -69,7 +69,7 @@ export function TerminalPane(props: { return ( - {truncate(program.title, Math.max(8, ("width" in place ? place.width : 80) - 17))} - + {props.header} {focused ? "ctrl+\\ leave" : "ctrl+\\ focus"} ; + +const COLUMN_TAB_LABELS: Record = { details: "Details", editor: "Editor", terminal: "Terminal" }; + +/** + * The panes around the conversation: each thread's terminals (in the drawer below it, or the + * right-hand column's Terminal tab), a file in $EDITOR in the column's Editor tab, and the + * message in $EDITOR in the composer's place. Which one has the keys, and the keys between them. + */ +export function usePanes(deps: { + readonly threadId: ThreadId | undefined; + /** The open thread's terminals on the server. */ + readonly terminals: readonly TerminalTarget[]; + readonly placement: Placement; + /** Whether the right-hand column shows; its setting, and changing it for this run only. */ + readonly column: boolean; + readonly columnPref: boolean | null; + readonly setColumnPref: (show: boolean | null) => void; + /** Whether a pane has the keys, and giving them to one or back to the conversation. */ + readonly focused: boolean; + readonly focus: (focused: boolean) => void; + readonly say: (text: string, bad?: boolean) => void; +}) { + const { threadId, placement, column, focused, say } = deps; + /** Per thread: the terminal its drawer shows, and whether the drawer is open. */ + const [drawers, setDrawers] = useState>(new Map()); + /** Terminals that closed or exited here, until the server's list catches up. */ + const [ended, setEnded] = useState>(new Set()); + const [editor, setEditor] = useState(null); + const [message, setMessage] = useState(null); + const [tab, setTab] = useState("details"); + const [target, setTarget] = useState("terminal"); + /** The column's setting before a tab opened it, to go back to once that tab closes. */ + const restore = useRef<{ readonly pref: boolean | null } | null>(null); + + const endedKey = (terminal: TerminalTarget) => `${terminal.threadId}:${terminal.terminalId}`; + const drawer = threadId ? drawers.get(threadId) : undefined; + const listed = deps.terminals.filter((terminal) => !ended.has(endedKey(terminal))); + // A terminal just opened shows before the server lists it. + const tabs = drawer && !ended.has(endedKey(drawer.target)) && !listed.some((terminal) => terminal.terminalId === drawer.target.terminalId) ? [...listed, drawer.target] : listed; + const terminal = drawer?.open ? drawer.target : null; + const side = placement === "side"; + + const columnTabs: ColumnTab[] = ["details", ...(editor ? ["editor" as const] : []), ...(side && terminal ? ["terminal" as const] : [])]; + const columnTab = columnTabs.includes(tab) ? tab : "details"; + const shown: Record = { + terminal: terminal !== null && (!side || (column && columnTab === "terminal")), + editor: column && columnTab === "editor", + message: message !== null, + }; + const focusedPane = focused && shown[target] ? target : null; + // A pane that went away, or out of sight, gives the keys back. + useEffect(() => { + if (focused && !shown[target]) deps.focus(false); + }); + + const enter = (pane: PaneFocus) => { + setTarget(pane); + deps.focus(true); + }; + const showTab = (next: ColumnTab) => { + setTab(next); + if (column) return; + restore.current ??= { pref: deps.columnPref }; + deps.setColumnPref(true); + }; + /** The column goes back to how it was once nothing but Details is left in it. */ + const tabGone = (othersLeft: boolean) => { + if (othersLeft || !restore.current) return; + deps.setColumnPref(restore.current.pref); + restore.current = null; + }; + const setDrawer = (id: ThreadId, value: { readonly target: TerminalTarget; readonly open: boolean }) => setDrawers((previous) => new Map(previous).set(id, value)); + + /** Shows a terminal, as a tab of the drawer or of the column, and gives it the keys. */ + const openTerminal = (next: TerminalTarget) => { + setEnded((previous) => { + const rest = new Set(previous); + rest.delete(endedKey(next)); + return rest; + }); + setDrawer(next.threadId, { target: next, open: true }); + if (side) showTab("terminal"); + enter("terminal"); + }; + const hideTerminal = () => { + if (!threadId || !drawer) return; + setDrawer(threadId, { ...drawer, open: false }); + if (side) tabGone(editor !== null); + }; + /** ctrl+j: hides the terminal when it shows, or shows the last one, or `open` finds one. */ + const toggleTerminal = (open: () => void) => { + if (shown.terminal) return hideTerminal(); + if (drawer && tabs.some((candidate) => candidate.terminalId === drawer.target.terminalId)) return openTerminal(drawer.target); + open(); + }; + const selectTab = (index: number) => { + const next = tabs[index]; + if (next) setDrawer(next.threadId, { target: next, open: true }); + }; + /** A terminal closed or exited: its tab goes, the next one shows, and the last takes the drawer with it. */ + const terminalEnded = (gone: TerminalTarget, note?: string) => { + setEnded((previous) => new Set(previous).add(endedKey(gone))); + const next = tabs.find((candidate) => candidate.terminalId !== gone.terminalId); + if (next) setDrawer(gone.threadId, { target: next, open: drawers.get(gone.threadId)?.open ?? true }); + else { + setDrawers((previous) => { + const rest = new Map(previous); + rest.delete(gone.threadId); + return rest; + }); + if (side && gone.threadId === threadId) tabGone(editor !== null); + } + if (note) say(note); + }; + + /** A file in $EDITOR, in the column's Editor tab. An editor may hold unsaved work, so it isn't replaced. */ + const openEditor = (program: LocalProgram) => { + if (editor && editor.id !== program.id) return say("The editor is still open; ctrl+\\ there and quit it first.", true); + setEditor(program); + showTab("editor"); + enter("editor"); + }; + const editorClosed = (note?: string) => { + setEditor(null); + tabGone(side && terminal !== null); + if (note) say(note); + }; + /** The message in $EDITOR, in the composer's place. */ + const openMessage = (program: LocalProgram) => { + if (message) return enter("message"); + setMessage(program); + enter("message"); + }; + + // ctrl+\ goes back to the pane that last had the keys, or the first that shows. + const next = ([target, "message", "editor", "terminal"] as const).find((pane) => shown[pane]); + const paneKey: Binding | null = next + ? { keys: ["ctrl+\\"], run: () => (focused ? deps.focus(false) : enter(next)), hint: focused ? "leave pane" : "pane", command: { id: "pane-focus", title: focused ? "Leave the pane" : "Focus the pane", keywords: ["terminal", "editor"] } } + : null; + /** alt+1…9 pick the terminal tab, while the terminal shows. */ + const tabKeys: Binding[] = shown.terminal ? tabs.slice(0, 9).map((_, index) => ({ keys: [`alt+${index + 1}`], run: () => selectTab(index) })) : []; + const cycle = (step: 1 | -1) => setTab(columnTabs[(columnTabs.indexOf(columnTab) + step + columnTabs.length) % columnTabs.length]!); + /** { and } step through the column's tabs; [ and ] step through turns. */ + const columnKeys: Binding[] = + column && columnTabs.length > 1 + ? [ + { keys: ["}"], run: () => cycle(1), command: { id: "column-next", title: "Next tab in the right column", keywords: ["details", "editor", "terminal"] } }, + { keys: ["{"], run: () => cycle(-1), command: { id: "column-previous", title: "Previous tab in the right column", keywords: ["details", "editor", "terminal"] } }, + ] + : []; + /** While a pane has the keys, all it keeps are these. */ + const focusedKeys = keys(paneKey, focusedPane === "terminal" && tabKeys); + + return { + terminal, + tabs, + editor, + message, + columnTabs: columnTabs.map((id) => ({ id, label: COLUMN_TAB_LABELS[id] })), + columnTab, + setColumnTab: setTab, + focusedPane, + enter, + openTerminal, + hideTerminal, + toggleTerminal, + selectTab, + terminalEnded, + openEditor, + editorClosed, + openMessage, + messageClosed: () => setMessage(null), + keys: { pane: paneKey, tabs: tabKeys, column: columnKeys, focused: focusedKeys }, + }; +} diff --git a/src/ui/useWorkspace.ts b/src/ui/useWorkspace.ts index 1f1458d..a2212ea 100644 --- a/src/ui/useWorkspace.ts +++ b/src/ui/useWorkspace.ts @@ -1,5 +1,5 @@ import type { CliRenderer, KeyEvent } from "@opentui/core"; -import type { OrchestrationProjectShell, OrchestrationV2ThreadShell, ServerConfig, ServerLifecycleStreamEvent, TerminalSummary, WorktreeSetupSnapshot } from "@t3tools/contracts"; +import type { OrchestrationProjectShell, OrchestrationV2ThreadShell, ServerConfig, ServerLifecycleStreamEvent, TerminalSummary, ThreadId, WorktreeSetupSnapshot } from "@t3tools/contracts"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { deriveLocalBranchNameFromRemoteRef, sanitizeNewRefName } from "@t3tools/shared/git"; import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; @@ -25,7 +25,7 @@ export function useWorkspace(input: { readonly draft: boolean; readonly diff: DiffState | null; readonly openPicker: (picker: Picker) => void; - /** Shows a terminal in the pane beside the conversation. */ + /** Shows a terminal in the drawer, or the right-hand column's Terminal tab. */ readonly openPane: (target: TerminalTarget) => void; readonly confirm: (confirmation: Confirmation) => void; readonly run: (label: string, action: () => Promise) => void; @@ -78,14 +78,19 @@ export function useWorkspace(input: { const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id); const cwd = thread?.worktreePath ?? project?.workspaceRoot; const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal); - /** In the pane, or with the whole screen. */ + const targetOf = (threadId: ThreadId, terminal: Pick): TerminalTarget => ({ + threadId, + terminalId: terminal.terminalId, + cwd: terminal.cwd, + worktreePath: terminal.worktreePath, + label: resolveTerminalSessionLabel(terminal.terminalId, terminal), + }); + /** The drawer's tabs: the thread's terminals that haven't exited. */ + const tabs = thread ? threadTerminals.filter((terminal) => terminal.status !== "exited").map((terminal) => targetOf(thread.id, terminal)) : []; + /** In the drawer, or with the whole screen. */ const enterTerminal = (terminal: Pick, fullScreen = false) => { if (!thread) return; - const target = { - threadId: thread.id, - ...terminal, - label: resolveTerminalSessionLabel(terminal.terminalId, terminal), - }; + const target = targetOf(thread.id, terminal); if (!fullScreen) return input.openPane(target); void attachTerminal(renderer, session, target, (message) => { if (message) say(message); @@ -164,9 +169,10 @@ export function useWorkspace(input: { }; const openTerminal = () => { if (!thread || input.draft) return say("Open a thread first.", true); - if (threadTerminals.length === 0) return newTerminal(); - if (threadTerminals.length === 1) return enterTerminal(threadTerminals[0]!); - terminalPicker(); + // The drawer's tabs reach the others. + const first = tabs[0]; + if (!first) return newTerminal(); + input.openPane(first); }; const branchPicker = () => { @@ -318,6 +324,8 @@ export function useWorkspace(input: { commands, key, openTerminal, + newTerminal: () => newTerminal(), + tabs, note, setupFailed: setup?.phase === "failed" || setupError !== null, }; diff --git a/test/app/pane.test.tsx b/test/app/pane.test.tsx index cb96133..f188646 100644 --- a/test/app/pane.test.tsx +++ b/test/app/pane.test.tsx @@ -1,6 +1,11 @@ import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; -import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx"; +import { loadLayout } from "../../src/layout.ts"; +import { withReply } from "./fixtures.ts"; +import { fakeSession, renderApp, v2ShellSnapshot, v2ThreadId } from "./harness.tsx"; let app: Awaited> | null = null; const open = async (...args: Parameters) => (app = await renderApp(...args)); @@ -11,16 +16,21 @@ afterEach(() => { 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 }); +const withTerminal = (events: readonly unknown[] = [snapshot]) => fakeSession({ terminals: [terminal], terminalEvents: events, projection: withReply("The reply above the drawer.", false) }); -describe("terminal pane", () => { - test("ctrl+j opens the thread's terminal in the pane, with its scrollback, and takes every key", async () => { +describe("terminal drawer", () => { + test("ctrl+j opens the thread's terminal in a drawer below the conversation, with its scrollback, and it 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("Terminal 1 +"); expect(app.frame()).toContain("user@host:~$"); expect(app.calls("attachTerminal")).toHaveLength(1); expect(app.hints()).toBe("ctrl+\\ leave pane"); + // Between the conversation and the composer, the conversation's full width. + const tab = app.find("Terminal 1 +"); + expect(tab.y).toBeGreaterThan(app.find("The reply above").y); + expect(tab.y).toBeLessThan(app.find("Press i to type").y); + expect(tab.x).toBeLessThan(app.find("Press i to type").x); await app.press("q"); await app.press("escape"); expect(app.calls("writeTerminal").map((call) => call.args[2])).toEqual(["q", "\x1b"]); @@ -28,7 +38,7 @@ describe("terminal pane", () => { expect(app.frame()).toContain("user@host:~$"); }); - test("ctrl+\\ leaves the pane and comes back to it; a click focuses it too", async () => { + test("ctrl+\\ leaves the drawer 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 }); @@ -43,32 +53,108 @@ describe("terminal pane", () => { 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("ctrl+j hides the drawer again, from it or from the conversation, and brings back the same terminal", async () => { + const app = await open({ session: withTerminal() }); + await app.press("j", { ctrl: true }); + await app.press("j", { ctrl: true }); + expect(app.frame()).not.toContain("user@host"); + expect(app.hints()).toStartWith("j/k threads"); + await app.press("j", { ctrl: true }); + expect(app.frame()).toContain("user@host"); + await app.press("\\", { ctrl: true }); + await app.press("j", { ctrl: true }); + expect(app.frame()).not.toContain("user@host"); + expect(app.calls("writeTerminal")).toHaveLength(0); }); - 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" }]) }); + test("each terminal is a tab: a click, alt+1…9, or the T picker switches; + opens another", async () => { + const second = { ...terminal, terminalId: "term-2" }; + const app = await open({ session: fakeSession({ terminals: [terminal, second], terminalEvents: [snapshot] }) }); await app.press("j", { ctrl: true }); - expect(app.frame()).not.toContain("Terminal · Terminal 1"); + expect(app.frame()).toContain("Terminal 1 Terminal 2 +"); + const attached = () => app.calls("attachTerminal").map((call) => (call.args[0] as { terminalId: string }).terminalId); + expect(attached()).toEqual(["term-1"]); + await app.press("2", { meta: true }); + expect(attached()).toEqual(["term-1", "term-2"]); + // From the conversation too, while the drawer shows. + await app.press("\\", { ctrl: true }); + await app.press("1", { meta: true }); + expect(attached()).toEqual(["term-1", "term-2", "term-1"]); + const tab = app.find("Terminal 2"); + await app.click(tab.x, tab.y); + expect(attached()).toEqual(["term-1", "term-2", "term-1", "term-2"]); + await app.press("T"); + await app.press("return"); + expect(attached().at(-1)).toBe("term-1"); + const plus = app.find("Terminal 2 +"); + await app.click(plus.x + "Terminal 2 ".length, plus.y); + expect(app.calls("openTerminal")).toHaveLength(1); + expect(app.frame()).toContain("Terminal 1 Terminal 2 Terminal 3 +"); + expect(attached().at(-1)).toBe("term-3"); + }); + + test("a terminal that closes takes its tab away, and the last one the drawer", async () => { + const closed = { type: "closed", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z" }; + const app = await open({ session: withTerminal([snapshot, closed]) }); + await app.press("j", { ctrl: true }); + expect(app.frame()).not.toContain("Terminal 1 +"); expect(app.hints()).toBe("Terminal closed"); }); + test("dragging the drawer's edge resizes it and keeps the height; right-click resets it", async () => { + const app = await open({ session: withTerminal() }); + await app.press("j", { ctrl: true }); + await app.press("\\", { ctrl: true }); + const tabs = () => app.find("Terminal 1 +").y; + const before = tabs(); + const edge = app.find("━"); + await app.mockMouse.drag(edge.x + 5, edge.y, edge.x + 5, edge.y - 4); + await app.settle(100); + expect(tabs()).toBe(before - 4); + expect((await loadLayout()).drawerHeight).toBeGreaterThan(0); + await app.click(edge.x + 5, edge.y - 4, 2); + expect(tabs()).toBe(before); + expect((await loadLayout()).drawerHeight).toBeNull(); + }); + + test("on a short window the drawer takes the conversation's place", async () => { + const app = await open({ height: 22, session: withTerminal() }); + expect(app.frame()).toContain("The reply above"); + await app.press("j", { ctrl: true }); + expect(app.frame()).toContain("user@host:~$"); + expect(app.frame()).not.toContain("The reply above"); + expect(app.frame()).toContain("Press i to type"); + }); + + test("Move terminal to the side puts terminals in the right column's Terminal tab, and stays", async () => { + const app = await open({ width: 200, session: withTerminal() }); + await app.press("k", { ctrl: true }); + await app.type("move terminal to the side"); + await app.press("return"); + expect((await loadLayout()).terminalPlacement).toBe("side"); + await app.press("j", { ctrl: true }); + expect(app.frame()).toContain("Details Terminal"); + const tab = app.find("Terminal 1 +"); + expect(tab.x).toBeGreaterThan(200 - 38 - 1); + expect(app.hints()).toBe("ctrl+\\ leave pane"); + // { and } step through the column's tabs from the conversation. + await app.press("\\", { ctrl: true }); + await app.press("{"); + expect(app.frame()).not.toContain("user@host"); + expect(app.frame()).toContain("/workspace/project"); + await app.press("}"); + expect(app.frame()).toContain("user@host"); + await app.press("j", { ctrl: true }); + expect(app.frame()).not.toContain("Details Terminal"); + }); + 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 () => { + test("ctrl+g writes the message in $EDITOR in the composer's place, 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. @@ -77,21 +163,28 @@ describe("terminal pane", () => { const app = await open(); await app.press("i"); await app.type("draft"); + const composer = app.find("draft"); await app.press("g", { ctrl: true }); expect(app.frame()).toContain("Message · save and quit"); + expect(app.frame()).not.toContain("draft"); + expect(app.find("Message · save and quit").x).toBeLessThan(composer.x); 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; + restoreEditor(previous); } }); }); +const restoreEditor = (previous: { visual: string | undefined; editor: string | undefined }) => { + 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", @@ -108,4 +201,33 @@ describe("editing a changed file", () => { // The fixture's workspace isn't on this machine. expect(app.hints()).toBe("README.md isn't on this machine."); }); + + test("a file on this machine opens in the column's Editor tab, which closes when the editor does", async () => { + const root = mkdtempSync(join(tmpdir(), "t3tui-edit-")); + writeFileSync(join(root, "README.md"), "hello\n"); + const project = { ...v2ShellSnapshot.projects[0]!, workspaceRoot: root }; + const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR }; + delete process.env.VISUAL; + process.env.EDITOR = "sleep 0.6; true"; + try { + const app = await open({ width: 200, session: fakeSession({ vcs, snapshot: { ...v2ShellSnapshot, projects: [project] } }) }); + await app.press("l"); + await app.press("o"); + expect(app.frame()).toContain("Details Editor"); + expect(app.frame()).toContain("Editing README.md"); + expect(app.find("Details Editor").x).toBeGreaterThan(200 - 38 - 1); + expect(app.hints()).toBe("ctrl+\\ leave pane"); + // Back to Details and to the editor again, with it still running. + await app.press("\\", { ctrl: true }); + await app.press("}"); + expect(app.frame()).not.toContain("Editing README.md"); + await app.click(app.find("Editor").x, app.find("Editor").y); + expect(app.frame()).toContain("Editing README.md"); + for (let tries = 0; tries < 40 && app.frame().includes("Details Editor"); tries++) await app.settle(50); + expect(app.frame()).not.toContain("Details Editor"); + expect(app.frame()).toContain("Changes"); + } finally { + restoreEditor(previous); + } + }); });