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

+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 { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
@@ -31,7 +33,8 @@ import { useDraft } from "./useDraft.ts";
import { useModelPicker } from "./useModelPicker.ts";
import { useQuestion } from "./useQuestion.ts";
import { useThreadMenu } from "./useThreadMenu.ts";
import { editInEditor } from "./editor.ts";
import { editorCommand, scratchFile } from "./editor.ts";
import { TerminalPane, type PaneProgram } from "./TerminalPane.tsx";
import { Palette } from "./Palette.tsx";
import { ApprovalPanel } from "./ApprovalPanel.tsx";
import { LiveStatus } from "./LiveStatus.tsx";
@@ -68,9 +71,10 @@ import { useUsageSummary } from "./useUsage.ts";
/**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
* "details": j/k move through the details panel. "settings": j/k move through settings.
* "pane": every key but ctrl+\ goes to the program in the terminal pane.
* The rest are overlays with their own input.
*/
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request";
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request" | "pane";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
@@ -134,6 +138,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
/** The edge being dragged. */
const [resizing, setResizing] = useState<"list" | "details" | null>(null);
const [diff, setDiff] = useState<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 [settingsIndex, setSettingsIndex] = useState<number | null>(null);
const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null);
@@ -459,6 +467,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
say,
progress: (text) => setFlash({ text }),
openThread,
editFile: (path, cwd) => editFile(path, cwd),
focus: (focused) => setMode(focused ? "details" : "nav"),
});
@@ -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. */
const openEditor = async () => {
/** The composer's text in $EDITOR, in the pane; what's saved comes back when it exits. */
const openEditor = () => {
const composer = composerRef.current;
if (!composer) return;
const edited = await editInEditor(renderer, composer.plainText);
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
composer.setText(edited);
composer.gotoBufferEnd();
setMode("input");
const key = composerKey;
const file = scratchFile(composer.plainText);
showPane({
kind: "local",
id: `message:${file.path}`,
title: "Message · save and quit to bring it back",
command: editorCommand(file.path),
onExit: (code) => {
const edited = code === 0 ? file.read() : null;
file.remove();
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
putMessage(key, edited);
setMode((current) => (current === "pane" ? "input" : current));
},
});
};
/** A workspace file in $EDITOR, in the pane, when the workspace is on this machine. */
const editFile = (path: string, cwd: string | null) => {
const file = cwd ? resolvePathLinkTarget(path, cwd) : path;
if (!existsSync(file)) return say(`${path} isn't on this machine.`, true);
showPane({ kind: "local", id: `edit:${file}`, title: `Editing ${path}`, command: editorCommand(file), cwd: cwd ?? undefined, onExit: () => {} });
};
const settingsRows = settingRows(config);
@@ -545,6 +595,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
setMode("nav");
};
/** Replaces a composer's text, the open one's or a stored draft's. */
const putMessage = (key: string, text: string) => {
const composer = composerRef.current;
if (key !== activeComposerKey.current || !composer) return void drafts.current.set(key, text);
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
* 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 paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette };
const terminalKey: Binding = { keys: ["ctrl+j"], run: workspace.openTerminal };
const paneKey: Binding | null = pane && { keys: ["ctrl+\\"], run: () => setMode(mode === "pane" ? "nav" : "pane"), hint: mode === "pane" ? "leave pane" : "pane", command: { id: "pane-focus", title: mode === "pane" ? "Leave the terminal pane" : "Focus the terminal pane", keywords: ["terminal", "editor"] } };
const editorKey: Binding | null = hasComposer ? { keys: ["ctrl+g"], run: openEditor, command: { id: "editor", title: "Write the message in $EDITOR", keywords: ["vim", "editor", "compose"] } } : null;
const nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) };
const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], run: () => move(-1) };
// Anywhere with a text field, ctrl+u and ctrl+d edit (delete to line start, delete forward); page up/down still scroll.
const lineInput = mode === "filter" || mode === "input" || mode === "find" || mode === "palette" || mode === "picker" || mode === "confirm";
const globalKeys = keys(
paneKey,
quitKey,
paletteKey,
terminalKey,
@@ -795,15 +857,19 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
cancelDraftKey,
);
// A diff and a draft name their own few keys; everything else names the lot.
const navHints = diff
? [scrollDiffDown, closeDiff, detailsKey]
: draft
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey)
: navKeys;
const navHints = keys(
paneKey,
diff
? [scrollDiffDown, closeDiff, detailsKey]
: draft
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey)
: navKeys,
);
// Commands only the palette runs.
const paletteOnly = keys(
editorKey,
pane?.kind === "server" && { keys: [], run: () => closePane(), command: { id: "pane-close", title: "Close the terminal pane", keywords: ["detach", "hide"] } },
queue.keys.input,
queue.keys.palette,
(projection?.subagents ?? []).filter((agent) => threadId && canStopSubagent(agent)).map((agent): Binding => ({ keys: [], run: () => run("Stop requested", () => session.stopSubagent(agent)), command: { id: `stop-subagent:${agent.id}`, title: `Stop subagent: ${agent.title ?? "subagent"}`, keywords: ["interrupt", "cancel", "kill"] } })),
@@ -814,7 +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 } : {}) })),
{ keys: [], run: openSettings, command: { id: "settings", title: "Settings", keywords: ["preferences", "config", "options", "notifications", "alerts"] } },
);
const commands = commandsFor([...navKeys, ...paletteOnly]);
const commands = commandsFor(keys(paneKey, navKeys, paletteOnly));
// The composer. Enter and newlines are the textarea's own; their hints only explain.
const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
@@ -888,6 +954,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
return { layers: [confirmKeys], hints: confirmKeys };
}
}
if (mode === "pane" && paneKey) return { layers: [[paneKey]], hints: [paneKey] };
// The secret field takes every key while it's focused.
if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings };
switch (mode) {
@@ -921,7 +988,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
return key.preventDefault();
}
}
if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm") {
if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm" && mode !== "pane") {
secret.type(key);
key.preventDefault();
}
@@ -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. */
const focusConversation = (event: MouseEvent) => {
if (event.button !== 0 || (mode !== "input" && mode !== "details")) return;
if (event.button !== 0 || (mode !== "input" && mode !== "details" && mode !== "pane")) return;
panel.leave();
};
@@ -999,8 +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.
const detailsRoom = width - listWidth - 1 - MIN_CONVERSATION_WIDTH;
const detailsWidth = Math.min(detailsWidthPref ?? DETAILS_WIDTH, Math.max(DETAILS_WIDTH, detailsRoom));
const detailsColumn = panel.show && detailsWidth <= detailsRoom;
const detailsInPlace = panel.show && !detailsColumn;
// The pane takes the details column's place, or the conversation's when there's no room beside it.
const paneColumn = pane !== null && detailsWidth <= detailsRoom;
const detailsColumn = !pane && panel.show && detailsWidth <= detailsRoom;
const detailsInPlace = !pane && panel.show && !detailsColumn;
const rightColumn = paneColumn || detailsColumn;
// The block's height: a row of padding on top, the text, then the model line inside it.
// Padding row, text, a blank row, then the model line.
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 3;
@@ -1044,6 +1114,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
inPlace={inPlace}
selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null}
onActivate={panel.activateById}
onEdit={panel.edit}
/>
);
@@ -1118,8 +1189,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
saveLayoutNow({ listWidth: null });
}} />}
<box flexDirection="column" flexGrow={1} minHeight={0}>
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation}>
{settingsIndex !== null ? (
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation} onSizeChange={function (this: { height: number }) { setContentHeight(this.height); }}>
{pane && !paneColumn ? null : settingsIndex !== null ? (
<SettingsView
rows={settingsRows}
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}
{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}
{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
request={questions.request}
index={questions.draft.index}
@@ -1192,7 +1263,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
onCancel={closeOverlay}
/>
) : 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 ? (
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
<text fg={colors.muted}>Attached:</text>
@@ -1275,14 +1346,24 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
</box>
) : null}
</box>
{detailsColumn ? (
<>
<ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => {
setDetailsWidthPref(null);
saveLayoutNow({ detailsWidth: null });
}} />
{detailsPanel(false)}
</>
{rightColumn ? (
<ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => {
setDetailsWidthPref(null);
saveLayoutNow({ detailsWidth: null });
}} />
) : null}
{detailsColumn ? detailsPanel(false) : null}
{/* One place in the tree in both layouts, so a narrower window doesn't restart its program. */}
{pane ? (
<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}
</box>
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
+15 -6
View File
@@ -1,7 +1,7 @@
import type { ReactNode } from "react";
import { MAX_DETAIL_FILES, type ChangedFile, type DetailsAction, type DetailsFold, type LineageLine, type ThreadDetails } from "../model/details.ts";
import { ClickRow } from "./Button.tsx";
import { Button, ClickRow } from "./Button.tsx";
import { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts";
@@ -25,6 +25,8 @@ export function DetailsPanel(props: {
readonly selected: string | null;
readonly unfolded: ReadonlySet<DetailsFold>;
readonly onActivate: (id: string) => void;
/** Opens a changed file in $EDITOR, from its ▸ Edit. */
readonly onEdit: (path: string) => void;
/** Shown when there are no details, which defaults to no thread being selected. */
readonly empty?: string;
}) {
@@ -48,7 +50,7 @@ export function DetailsPanel(props: {
{!details ? (
<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>
</box>
@@ -60,7 +62,7 @@ interface LineProps {
readonly onActivate: (id: string) => void;
}
function Sections({ details, inner, loading, unfolded, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet<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 files = changes?.files ?? [];
const line = { selected, onActivate };
@@ -102,9 +104,16 @@ function Sections({ details, inner, loading, unfolded, selected, onActivate }: {
{changes ? (
<Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}>
{files.slice(0, MAX_DETAIL_FILES).map((file) => (
<Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}>
<FileLine file={file} inner={inner} />
</Selectable>
<box key={file.path} flexDirection="column">
<Selectable id={`diff:${file.path}`} {...line} inner={inner}>
<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 === 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 { 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,
* or null if the editor failed. The renderer is suspended meanwhile.
*/
export async function editInEditor(renderer: CliRenderer, text: string): Promise<string | null> {
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
const file = join(dir, "prompt.md");
writeFileSync(file, text);
const file = scratchFile(text);
await renderer.suspend();
try {
// Through the shell, so EDITOR="code --wait" works.
const result = spawnSync(process.env.SHELL || "sh", ["-c", `${editor} "$1"`, "sh", file], { stdio: "inherit" });
const [command, ...args] = editorCommand(file.path);
const result = spawnSync(command!, args, { stdio: "inherit" });
if (result.status !== 0) return null;
return readFileSync(file, "utf8").replace(/\n$/, "");
return file.read();
} finally {
rmSync(dir, { recursive: true, force: true });
file.remove();
await renderer.resume();
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. */
readonly progress: (text: string) => 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. */
readonly focus: (focused: boolean) => void;
}) {
@@ -193,6 +195,11 @@ export function useDetails(deps: {
deps.focus(false);
};
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 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",
},
selectedFile && { keys: ["o"], run: () => edit(selectedFile), hint: "edit file" },
{ keys: ["esc"], run: () => (deps.diff ? setDiff(null) : leave()), hint: "back" },
{ 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));
+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 type { Confirmation } from "./ConfirmBar.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 };
@@ -25,6 +25,8 @@ 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. */
readonly openPane: (target: TerminalTarget) => void;
readonly confirm: (confirmation: Confirmation) => void;
readonly run: (label: string, action: () => Promise<unknown>) => 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 cwd = thread?.worktreePath ?? project?.workspaceRoot;
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;
const target = {
threadId: thread.id,
...terminal,
label: resolveTerminalSessionLabel(terminal.terminalId, terminal),
};
if (!fullScreen) return input.openPane(target);
void attachTerminal(renderer, session, target, (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);
const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live");
run("Terminal opened", async () => {
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") => {
@@ -114,7 +128,10 @@ export function useWorkspace(input: {
};
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
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) {
const targets = terminalItems(action);
if (targets.length === 0) continue;
@@ -269,7 +286,8 @@ export function useWorkspace(input: {
const commands: Command[] = thread && !input.draft ? [
{ 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-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"),
{ 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 },