diff --git a/README.md b/README.md index cdb8baa..34de0ba 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,12 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code - **Find in thread:** `f` or `Find in thread` in the palette or thread menu searches the whole conversation, counts matches, highlights matching text and loads earlier history to reveal the selected match. Matching Markdown is shown as highlighted plain text while finding. - **Archived threads:** `A` or `Show archived threads` in the palette opens the archive. Open a thread normally; `Unarchive thread` in the palette restores it. `Show active threads` returns to the live list. - **Ordering:** `J` / `K` or `Move pinned thread down` / `Move pinned thread up` in the palette reorder pinned threads. Active threads stay ordered by return time, as in T3 Code's Working shelf. -- **Mouse:** click a thread to open it, a collapsed section to unfold it, a details row to run it, the message box to type, or a palette row. +- **Mouse:** + - **Select and copy:** drag across any text to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally). A key press clears the highlight. Your terminal's own selection still works with shift held. + - **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one for send now / edit / remove), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top. + - **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a diff, a click on a file selects it and a second click shows its whole file. In the PR view, the URL opens in the browser. + - **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions). + - **Panes:** clicking the conversation takes the keys out of the message box or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right border to resize it; right-click the border to reset it. - Threads open scrolled to the bottom. - **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off. diff --git a/src/model/hints.ts b/src/model/hints.ts new file mode 100644 index 0000000..b42e473 --- /dev/null +++ b/src/model/hints.ts @@ -0,0 +1,31 @@ +/** A key a hint names, as the keyboard handler receives it. */ +export interface HintKey { + readonly name: string; + readonly sequence: string; + readonly shift: boolean; + readonly ctrl: boolean; +} + +const NAMED: Record = { esc: "escape", enter: "return", tab: "tab" }; + +/** + * The key at the start of a hint like "y approve" or "ctrl+k commands", so a click on the hint + * can press it. Hints that name a choice of keys ("j/k move", "1-9 pick") or a chord that + * sends a message ("alt+enter steer") aren't clickable. + */ +export function hintKey(hint: string, mode: string): HintKey | null { + const token = hint.trim().split(/\s+/)[0] ?? ""; + if (hint.includes(" or ") || /^\d-\d$/.test(token)) return null; + if (token.length > 1 && token.includes("/")) return null; + const ctrl = token.startsWith("ctrl+"); + const key = ctrl ? token.slice(5) : token; + if (key.includes("+") || key.includes("↑") || key.includes("↓")) return null; + // In the composer, enter is the composer's own: it sends, and a click shouldn't. + if (key === "enter" && (mode === "input" || ctrl)) return null; + const named = NAMED[key]; + if (named) return { name: named, sequence: named === "return" ? "\r" : named === "tab" ? "\t" : "\x1b", shift: false, ctrl }; + if ([...key].length !== 1) return null; + const lower = key.toLowerCase(); + const shift = lower !== key; + return { name: lower, sequence: ctrl ? String.fromCharCode(lower.charCodeAt(0) & 0x1f) : key, shift, ctrl }; +} diff --git a/src/model/timeline.ts b/src/model/timeline.ts index c889a24..53860ba 100644 --- a/src/model/timeline.ts +++ b/src/model/timeline.ts @@ -1,5 +1,5 @@ import { turnTargets, type TurnTarget } from "./turns.ts"; -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import type { OrchestrationV2ThreadProjection, RunAttemptId, RunId } from "@t3tools/contracts"; import { deriveRunlessWorkStartedAt, deriveThreadActivityRun, @@ -42,6 +42,7 @@ interface TimelineCache { readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] }; readonly stable: StableMessagesTimelineRowsState; readonly expandAll: boolean; + readonly expanded: ReadonlySet; } /** Answers yes for every id: "expand everything" without knowing the group ids up front. */ @@ -50,15 +51,17 @@ class EverySet extends Set { return true; } } -const EVERYTHING = new EverySet(); -const NOTHING = new Set(); +const EVERYTHING: ReadonlySet = new EverySet(); +const NOTHING: ReadonlySet = new Set(); export function buildTimeline( projection: OrchestrationV2ThreadProjection, - options: { readonly expandAll: boolean; readonly historyComplete: boolean }, + /** `expanded` holds the run, attempt and work group ids opened one at a time (by a click). */ + options: { readonly expandAll: boolean; readonly expanded?: ReadonlySet; readonly historyComplete: boolean }, previous: Timeline | null, ): Timeline { - const cache = previous?.cache.expandAll === options.expandAll ? previous.cache : null; + const opened = options.expanded ?? NOTHING; + const cache = previous?.cache.expandAll === options.expandAll && previous.cache.expanded === opened ? previous.cache : null; const entries = deriveTimelineEntriesFromVisibleTurnItemsWithState( { visibleTurnItems: projection.visibleTurnItems, @@ -75,15 +78,16 @@ export function buildTimeline( const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null; const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt; const pending = derivePendingThreadRequests(projection); - const expanded = options.expandAll ? EVERYTHING : NOTHING; + const expanded = options.expandAll ? EVERYTHING : opened; const rows = deriveMessagesTimelineRowsWithState( { timelineEntries: entries.entries, pendingApprovalRequestIds: new Set(pending.approvals.map((approval) => approval.requestId)), latestRun, runningRunId: runtime?.activeRunId ?? null, - expandedRunIds: expanded, - expandedAttemptIds: expanded, + // The ids are branded strings; one set of plain ones holds all three kinds. + expandedRunIds: expanded as ReadonlySet, + expandedAttemptIds: expanded as ReadonlySet, expandedWorkGroupIds: expanded, isWorking, runlessWorkActive: runlessStartedAt !== null, @@ -100,6 +104,6 @@ export function buildTimeline( turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete), isWorking, workStartedAt, - cache: { entries, rows, stable, expandAll: options.expandAll }, + cache: { entries, rows, stable, expandAll: options.expandAll, expanded: opened }, }; } diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 6331ba6..482681c 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -1,4 +1,4 @@ -import type { KeyEvent, ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"; +import type { KeyEvent, MouseEvent, ScrollBoxRenderable, Selection, TextareaRenderable } from "@opentui/core"; import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"; import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { @@ -47,7 +47,11 @@ import { copyText, desktopNotify, ring } from "./terminalOut.ts"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.tsx"; import { useTurns } from "./useTurns.ts"; -import { ThreadView } from "./ThreadView.tsx"; +import { ThreadView, type ConversationMouse, type ConversationTarget } from "./ThreadView.tsx"; +import { Button, ResizeHandle } from "./Button.tsx"; +import { HintBar } from "./HintBar.tsx"; +import type { HintKey } from "../model/hints.ts"; +import { useEvent } from "./useEvent.ts"; import { useQueue } from "./useQueue.ts"; import { useSecretRequest } from "./useSecretRequest.ts"; import { canStopSubagent } from "../model/subagents.ts"; @@ -111,6 +115,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const [filter, setFilter] = useState(""); const [showFolded, setShowFolded] = useState(false); const [expandAll, setExpandAll] = useState(false); + /** Folds opened one at a time by a click, for the open thread. */ + const [expandedIds, setExpandedIds] = useState>(() => new Set()); + /** The thread list's width once its border is dragged; null follows the window. */ + const [listWidthPref, setListWidthPref] = useState(null); + const [resizing, setResizing] = useState(false); /** null follows the terminal width; d sets it for the rest of the session. */ const [detailsPref, setDetailsPref] = useState(null); const [detailsSelected, setDetailsSelected] = useState(null); @@ -235,10 +244,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const timeline = useMemo(() => { if (!thread?.projection || !watchedId) return null; const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null; - const next = buildTimeline(thread.projection, { expandAll: expandAll || mode === "find", historyComplete: !thread.history.hasMore }, previous); + const next = buildTimeline(thread.projection, { expandAll: expandAll || mode === "find", expanded: expandedIds, historyComplete: !thread.history.hasMore }, previous); previousTimeline.current = { id: watchedId, timeline: next }; return next; - }, [thread?.projection, thread?.history.hasMore, watchedId, expandAll, mode === "find"]); + }, [thread?.projection, thread?.history.hasMore, watchedId, expandAll, expandedIds, mode === "find"]); + useEffect(() => setExpandedIds(new Set()), [watchedId]); const current = watchedId === threadId ? timeline : null; const find = useThreadFind(session, watchedId, thread, current, mode === "find"); const openFind = () => { setDiff(null); setSettingsIndex(null); setMode("find"); }; @@ -345,6 +355,19 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C setFlash({ text, bad }); setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000); }; + // Taking the mouse costs the terminal's own drag-to-select, so a drag selects here and copies on release. + const copySelection = useEvent((selection: Selection) => { + const text = selection.getSelectedText(); + if (!text.trim()) return; + copyText(renderer, text); + say(`Copied ${text.length === 1 ? "1 character" : `${text.length} characters`}`); + }); + useEffect(() => { + renderer.on("selection", copySelection); + return () => { + renderer.off("selection", copySelection); + }; + }, [renderer, copySelection]); const run = (label: string, action: () => Promise) => { action().then( () => say(label), @@ -1189,7 +1212,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return false; }; - useKeyboard((key) => { + const handleKey = (key: KeyEvent) => { + // A key ends a mouse selection; it was copied when the drag ended. + if (renderer.hasSelection) renderer.clearSelection(); if (mode === "find") { if (key.ctrl && key.name === "c") return quit(); if (key.ctrl && key.name === "k") return openPalette(), key.preventDefault(); @@ -1375,7 +1400,58 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C if (threadId || draft) setMode("input"); return key.preventDefault(); } - }); + }; + useKeyboard(handleKey); + + /** A click on a key hint presses that key, through the same handler as the keyboard. */ + const pressKey = (hint: HintKey) => + handleKey({ ...hint, meta: false, option: false, number: false, raw: hint.sequence, eventType: "press", source: "raw", preventDefault() {}, stopPropagation() {} } as unknown as KeyEvent); + + // The mouse in the conversation: stable callbacks, since its rows are memoized. + const conversationMouse: ConversationMouse = { + respond: useEvent((decision: ProviderApprovalDecision) => respond(decision)), + selectTurn: useEvent((messageId: string) => turns.select(messageId)), + toggleFold: useEvent((id: string) => + setExpandedIds((previous) => { + const next = new Set(previous); + if (!next.delete(id)) next.add(id); + return next; + }), + ), + loadEarlier: useEvent(() => loadEarlier()), + menu: useEvent((target: ConversationTarget) => openConversationMenu(target)), + }; + const copy = (label: string, text: string) => { + copyText(renderer, text); + say(`Copied ${label}`); + }; + /** The right-click menu on a message or command, as a picker like the thread menu. */ + const openConversationMenu = (target: ConversationTarget) => { + const items: PickerItem[] = + target.kind === "command" + ? [ + { id: "copy-command", title: "Copy command", run: () => copy("the command", target.command) }, + ...(target.output ? [{ id: "copy-output", title: "Copy output", run: () => copy("the output", target.output) }] : []), + ] + : [ + { id: "copy-message", title: "Copy message", run: () => copy("the message", target.text) }, + ...(target.role === "user" ? turns.menuFor(target.messageId) : []), + ]; + if (target.kind === "message" && target.role === "user") turns.select(target.messageId); + openPicker({ placeholder: target.kind === "command" ? "Command" : target.role === "user" ? "Your message" : "Message", groups: [{ label: truncateLabel(target.kind === "command" ? target.command : target.text, 60), items }] }); + }; + /** The right-click menu in the pull request view: its palette commands, as a picker. */ + const openPullRequestMenu = () => + openPicker({ + placeholder: "Pull request", + groups: [{ label: "Pull request", items: pullRequests.commands.filter((candidate) => candidate.id.startsWith("pr-") || candidate.id.startsWith("watch-") || candidate.id.startsWith("unlink-")).map((candidate) => ({ id: candidate.id, title: candidate.title, ...(candidate.shortcut ? { hint: candidate.shortcut } : {}), run: candidate.run })) }], + }); + /** 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; + setDetailsSelected(null); + setMode("nav"); + }; const status = shell.status.type === "error" @@ -1385,7 +1461,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C : shell.status.type === "reconnecting" ? "reconnecting…" : (shell.serverUrl ?? ""); - const listWidth = attached ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3))); + const listWidth = attached ? 0 : clampListWidth(listWidthPref ?? Math.min(46, Math.max(28, Math.floor(width * 0.3))), width); const detailsColumn = showDetails && width - listWidth - DETAILS_WIDTH >= MIN_CONVERSATION_WIDTH; const detailsInPlace = showDetails && !detailsColumn; const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2; @@ -1440,7 +1516,19 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C ); return ( - + setListWidthPref(clampListWidth(event.x, width)), + onMouseUp: () => setResizing(false), + onMouseDragEnd: () => setResizing(false), + } + : {})} + > tui3 @@ -1448,7 +1536,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C {` ${status}`} {usageInfo.note ? {` ${usageInfo.note}`} : null} - ctrl+k commands +