Add mouse support across the TUI
Drag to select copies on release. Request cards, the queue, attachments, the PR view and the key hints get clickable buttons. Prompts, folds, commands and diff files respond to clicks; prompts, replies, commands and the PR view get right-click menus. Clicking a pane focuses it, the wheel scrolls the thread list and palette, rows highlight under the pointer, and the thread list's border drags to resize.
This commit is contained in:
1 parent
fbdfb5c3e0
commit
12e1e0ba7a
27 files changed
+639
-116
No files matched your search
@@ -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.
|
- **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.
|
- **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.
|
- **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.
|
- 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.
|
- **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.
|
||||||
|
|
||||||
|
|||||||
@@ -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<string, string> = { 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 };
|
||||||
|
}
|
||||||
+13
-9
@@ -1,5 +1,5 @@
|
|||||||
import { turnTargets, type TurnTarget } from "./turns.ts";
|
import { turnTargets, type TurnTarget } from "./turns.ts";
|
||||||
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
|
import type { OrchestrationV2ThreadProjection, RunAttemptId, RunId } from "@t3tools/contracts";
|
||||||
import {
|
import {
|
||||||
deriveRunlessWorkStartedAt,
|
deriveRunlessWorkStartedAt,
|
||||||
deriveThreadActivityRun,
|
deriveThreadActivityRun,
|
||||||
@@ -42,6 +42,7 @@ interface TimelineCache {
|
|||||||
readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] };
|
readonly rows: { readonly input: MessagesTimelineRowsInput; readonly rows: MessagesTimelineRow[] };
|
||||||
readonly stable: StableMessagesTimelineRowsState;
|
readonly stable: StableMessagesTimelineRowsState;
|
||||||
readonly expandAll: boolean;
|
readonly expandAll: boolean;
|
||||||
|
readonly expanded: ReadonlySet<string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Answers yes for every id: "expand everything" without knowing the group ids up front. */
|
/** Answers yes for every id: "expand everything" without knowing the group ids up front. */
|
||||||
@@ -50,15 +51,17 @@ class EverySet<T> extends Set<T> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const EVERYTHING = new EverySet<never>();
|
const EVERYTHING: ReadonlySet<string> = new EverySet<string>();
|
||||||
const NOTHING = new Set<never>();
|
const NOTHING: ReadonlySet<string> = new Set<string>();
|
||||||
|
|
||||||
export function buildTimeline(
|
export function buildTimeline(
|
||||||
projection: OrchestrationV2ThreadProjection,
|
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<string>; readonly historyComplete: boolean },
|
||||||
previous: Timeline | null,
|
previous: Timeline | null,
|
||||||
): Timeline {
|
): 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(
|
const entries = deriveTimelineEntriesFromVisibleTurnItemsWithState(
|
||||||
{
|
{
|
||||||
visibleTurnItems: projection.visibleTurnItems,
|
visibleTurnItems: projection.visibleTurnItems,
|
||||||
@@ -75,15 +78,16 @@ export function buildTimeline(
|
|||||||
const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null;
|
const isWorking = derivePhase(runtime) === "running" || runlessStartedAt !== null;
|
||||||
const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt;
|
const workStartedAt = deriveActiveWorkStartedAt(latestRun, runtime, null) ?? runlessStartedAt;
|
||||||
const pending = derivePendingThreadRequests(projection);
|
const pending = derivePendingThreadRequests(projection);
|
||||||
const expanded = options.expandAll ? EVERYTHING : NOTHING;
|
const expanded = options.expandAll ? EVERYTHING : opened;
|
||||||
const rows = deriveMessagesTimelineRowsWithState(
|
const rows = deriveMessagesTimelineRowsWithState(
|
||||||
{
|
{
|
||||||
timelineEntries: entries.entries,
|
timelineEntries: entries.entries,
|
||||||
pendingApprovalRequestIds: new Set(pending.approvals.map((approval) => approval.requestId)),
|
pendingApprovalRequestIds: new Set(pending.approvals.map((approval) => approval.requestId)),
|
||||||
latestRun,
|
latestRun,
|
||||||
runningRunId: runtime?.activeRunId ?? null,
|
runningRunId: runtime?.activeRunId ?? null,
|
||||||
expandedRunIds: expanded,
|
// The ids are branded strings; one set of plain ones holds all three kinds.
|
||||||
expandedAttemptIds: expanded,
|
expandedRunIds: expanded as ReadonlySet<RunId>,
|
||||||
|
expandedAttemptIds: expanded as ReadonlySet<RunAttemptId>,
|
||||||
expandedWorkGroupIds: expanded,
|
expandedWorkGroupIds: expanded,
|
||||||
isWorking,
|
isWorking,
|
||||||
runlessWorkActive: runlessStartedAt !== null,
|
runlessWorkActive: runlessStartedAt !== null,
|
||||||
@@ -100,6 +104,6 @@ export function buildTimeline(
|
|||||||
turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete),
|
turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete),
|
||||||
isWorking,
|
isWorking,
|
||||||
workStartedAt,
|
workStartedAt,
|
||||||
cache: { entries, rows, stable, expandAll: options.expandAll },
|
cache: { entries, rows, stable, expandAll: options.expandAll, expanded: opened },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+134
-18
@@ -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 { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react";
|
||||||
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
|
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
|
||||||
import {
|
import {
|
||||||
@@ -47,7 +47,11 @@ import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
|||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
import { ThreadList } from "./ThreadList.tsx";
|
import { ThreadList } from "./ThreadList.tsx";
|
||||||
import { useTurns } from "./useTurns.ts";
|
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 { useQueue } from "./useQueue.ts";
|
||||||
import { useSecretRequest } from "./useSecretRequest.ts";
|
import { useSecretRequest } from "./useSecretRequest.ts";
|
||||||
import { canStopSubagent } from "../model/subagents.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 [filter, setFilter] = useState("");
|
||||||
const [showFolded, setShowFolded] = useState(false);
|
const [showFolded, setShowFolded] = useState(false);
|
||||||
const [expandAll, setExpandAll] = useState(false);
|
const [expandAll, setExpandAll] = useState(false);
|
||||||
|
/** Folds opened one at a time by a click, for the open thread. */
|
||||||
|
const [expandedIds, setExpandedIds] = useState<ReadonlySet<string>>(() => new Set());
|
||||||
|
/** The thread list's width once its border is dragged; null follows the window. */
|
||||||
|
const [listWidthPref, setListWidthPref] = useState<number | null>(null);
|
||||||
|
const [resizing, setResizing] = useState(false);
|
||||||
/** null follows the terminal width; d sets it for the rest of the session. */
|
/** null follows the terminal width; d sets it for the rest of the session. */
|
||||||
const [detailsPref, setDetailsPref] = useState<boolean | null>(null);
|
const [detailsPref, setDetailsPref] = useState<boolean | null>(null);
|
||||||
const [detailsSelected, setDetailsSelected] = useState<string | null>(null);
|
const [detailsSelected, setDetailsSelected] = useState<string | null>(null);
|
||||||
@@ -235,10 +244,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const timeline = useMemo(() => {
|
const timeline = useMemo(() => {
|
||||||
if (!thread?.projection || !watchedId) return null;
|
if (!thread?.projection || !watchedId) return null;
|
||||||
const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : 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 };
|
previousTimeline.current = { id: watchedId, timeline: next };
|
||||||
return 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 current = watchedId === threadId ? timeline : null;
|
||||||
const find = useThreadFind(session, watchedId, thread, current, mode === "find");
|
const find = useThreadFind(session, watchedId, thread, current, mode === "find");
|
||||||
const openFind = () => { setDiff(null); setSettingsIndex(null); setMode("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 });
|
setFlash({ text, bad });
|
||||||
setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000);
|
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<unknown>) => {
|
const run = (label: string, action: () => Promise<unknown>) => {
|
||||||
action().then(
|
action().then(
|
||||||
() => say(label),
|
() => say(label),
|
||||||
@@ -1189,7 +1212,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
return false;
|
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 (mode === "find") {
|
||||||
if (key.ctrl && key.name === "c") return quit();
|
if (key.ctrl && key.name === "c") return quit();
|
||||||
if (key.ctrl && key.name === "k") return openPalette(), key.preventDefault();
|
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");
|
if (threadId || draft) setMode("input");
|
||||||
return key.preventDefault();
|
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 =
|
const status =
|
||||||
shell.status.type === "error"
|
shell.status.type === "error"
|
||||||
@@ -1385,7 +1461,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
: shell.status.type === "reconnecting"
|
: shell.status.type === "reconnecting"
|
||||||
? "reconnecting…"
|
? "reconnecting…"
|
||||||
: (shell.serverUrl ?? "");
|
: (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 detailsColumn = showDetails && width - listWidth - DETAILS_WIDTH >= MIN_CONVERSATION_WIDTH;
|
||||||
const detailsInPlace = showDetails && !detailsColumn;
|
const detailsInPlace = showDetails && !detailsColumn;
|
||||||
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2;
|
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2;
|
||||||
@@ -1440,7 +1516,19 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}>
|
<box
|
||||||
|
flexDirection="column"
|
||||||
|
width={width}
|
||||||
|
height={height}
|
||||||
|
backgroundColor={colors.bg}
|
||||||
|
{...(resizing
|
||||||
|
? {
|
||||||
|
onMouseDrag: (event: MouseEvent) => setListWidthPref(clampListWidth(event.x, width)),
|
||||||
|
onMouseUp: () => setResizing(false),
|
||||||
|
onMouseDragEnd: () => setResizing(false),
|
||||||
|
}
|
||||||
|
: {})}
|
||||||
|
>
|
||||||
<box flexDirection="row" paddingLeft={1} paddingRight={1} height={1} flexShrink={0}>
|
<box flexDirection="row" paddingLeft={1} paddingRight={1} height={1} flexShrink={0}>
|
||||||
<text fg={colors.accent}>
|
<text fg={colors.accent}>
|
||||||
<strong>tui3</strong>
|
<strong>tui3</strong>
|
||||||
@@ -1448,7 +1536,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text>
|
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text>
|
||||||
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
|
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
|
||||||
<box flexGrow={1} />
|
<box flexGrow={1} />
|
||||||
<text fg={colors.faint}>ctrl+k commands</text>
|
<Button label="commands" shortcut="ctrl+k" onPress={openPalette} />
|
||||||
</box>
|
</box>
|
||||||
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
|
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
|
||||||
{attached ? null : (
|
{attached ? null : (
|
||||||
@@ -1478,7 +1566,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
shelfStatus={library.error ?? (library.loading ? "Loading…" : library.archived ? "Archived threads · A to go back" : null)}
|
shelfStatus={library.error ?? (library.loading ? "Loading…" : library.archived ? "Archived threads · A to go back" : null)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{attached ? null : <ResizeHandle active={resizing} onStart={() => setResizing(true)} onReset={() => setListWidthPref(null)} />}
|
||||||
<box flexDirection="column" flexGrow={1} minHeight={0}>
|
<box flexDirection="column" flexGrow={1} minHeight={0}>
|
||||||
|
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation}>
|
||||||
{settingsIndex !== null ? (
|
{settingsIndex !== null ? (
|
||||||
<SettingsView
|
<SettingsView
|
||||||
rows={settingsRows}
|
rows={settingsRows}
|
||||||
@@ -1493,9 +1583,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : mode === "pull-request" && pullRequests.view ? (
|
) : mode === "pull-request" && pullRequests.view ? (
|
||||||
<PullRequestView view={pullRequests.view} scrollRef={scrollRef} />
|
<PullRequestView view={pullRequests.view} scrollRef={scrollRef} onOpenUrl={() => pullRequests.commands.find((candidate) => candidate.id === "pr-open")?.run()} onMenu={openPullRequestMenu} onClose={pullRequests.close} />
|
||||||
) : diff ? (
|
) : diff ? (
|
||||||
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} />
|
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} onFile={turns.diffContext.click} />
|
||||||
) : draft ? (
|
) : draft ? (
|
||||||
<DraftView lines={draftLines} />
|
<DraftView lines={draftLines} />
|
||||||
) : threadId && detailsInPlace && mode !== "find" ? (
|
) : threadId && detailsInPlace && mode !== "find" ? (
|
||||||
@@ -1522,17 +1612,26 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
scrollRef={scrollRef}
|
scrollRef={scrollRef}
|
||||||
parent={parent}
|
parent={parent}
|
||||||
onOpenThread={openThread}
|
onOpenThread={openThread}
|
||||||
|
mouse={conversationMouse}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<box flexGrow={1} paddingLeft={2} paddingTop={1}>
|
<box flexGrow={1} paddingLeft={2} paddingTop={1}>
|
||||||
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
|
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
|
</box>
|
||||||
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
|
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
|
||||||
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
|
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
|
||||||
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} /> : 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 ? DETAILS_WIDTH : 0) - 2} /> : null}
|
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 3} actions={queue.actions} /> : null}
|
||||||
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
|
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel
|
||||||
|
request={pendingInput}
|
||||||
|
index={questionDraft.index}
|
||||||
|
draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]}
|
||||||
|
onPick={pickOption}
|
||||||
|
onNext={() => advanceQuestion(questionDraft)}
|
||||||
|
onDismiss={threadId && pendingInput.dismissible ? () => run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)) : undefined}
|
||||||
|
/> : null}
|
||||||
{mode === "confirm" && confirmation ? (
|
{mode === "confirm" && confirmation ? (
|
||||||
<ConfirmBar
|
<ConfirmBar
|
||||||
confirmation={confirmation}
|
confirmation={confirmation}
|
||||||
@@ -1542,12 +1641,17 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
closeOverlay();
|
closeOverlay();
|
||||||
confirmation.run(confirmMessage);
|
confirmation.run(confirmMessage);
|
||||||
}}
|
}}
|
||||||
|
onCancel={closeOverlay}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{menu ? <ComposerMenu items={menu.items} selected={menuSelected} empty={menu.empty} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} onPick={(index) => chooseMenuItem(menu.items[index])} /> : null}
|
{menu ? <ComposerMenu items={menu.items} selected={menuSelected} empty={menu.empty} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} onPick={(index) => chooseMenuItem(menu.items[index])} /> : null}
|
||||||
{attach.line ? (
|
{attach.pending.length > 0 ? (
|
||||||
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
|
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
|
||||||
<text fg={colors.muted} wrapMode="none">{attach.line}</text>
|
<text fg={colors.muted}>Attached:</text>
|
||||||
|
{attach.pending.map((attachment) => (
|
||||||
|
<Button key={attachment.id} label={`${attachment.name} ✕`} onPress={() => attach.remove(attachment)} />
|
||||||
|
))}
|
||||||
|
<Button label="+ file" shortcut="a" onPress={attach.attachFile} />
|
||||||
</box>
|
</box>
|
||||||
) : null}
|
) : null}
|
||||||
{threadId || draft ? (
|
{threadId || draft ? (
|
||||||
@@ -1603,7 +1707,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
) : menuOpen ? (
|
) : menuOpen ? (
|
||||||
<text fg={colors.faint}>↑/↓ move · tab or enter choose · esc close</text>
|
<text fg={colors.faint}>↑/↓ move · tab or enter choose · esc close</text>
|
||||||
) : (
|
) : (
|
||||||
<text fg={colors.faint}>{hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined, secret: secret.focused ? "focused" : secret.request ? "pending" : null, queue: queue.focused ? "focused" : queue.editing ? "editing" : queue.queued.length > 0 ? "queued" : null })}</text>
|
<HintBar mode={mode} onPress={pressKey} text={hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined, secret: secret.focused ? "focused" : secret.request ? "pending" : null, queue: queue.focused ? "focused" : queue.editing ? "editing" : queue.queued.length > 0 ? "queued" : null })} />
|
||||||
)}
|
)}
|
||||||
</box>
|
</box>
|
||||||
{mode === "palette" ? (
|
{mode === "palette" ? (
|
||||||
@@ -1620,6 +1724,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
}}
|
}}
|
||||||
onSubmit={() => pick(Math.min(paletteIndex, entries.length - 1))}
|
onSubmit={() => pick(Math.min(paletteIndex, entries.length - 1))}
|
||||||
onPick={pick}
|
onPick={pick}
|
||||||
|
onMove={(step) => setPaletteIndex((index) => Math.max(0, Math.min(entries.length - 1, index + step)))}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{mode === "picker" && picker ? (
|
{mode === "picker" && picker ? (
|
||||||
@@ -1636,6 +1741,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
}}
|
}}
|
||||||
onSubmit={() => pickItem(Math.min(pickerIndex, pickerEntries.length - 1))}
|
onSubmit={() => pickItem(Math.min(pickerIndex, pickerEntries.length - 1))}
|
||||||
onPick={pickItem}
|
onPick={pickItem}
|
||||||
|
onMove={(step) => setPickerIndex((index) => Math.max(0, Math.min(pickerEntries.length - 1, index + step)))}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</box>
|
</box>
|
||||||
@@ -1704,6 +1810,16 @@ function composerLineCount(composer: TextareaRenderable): number {
|
|||||||
return Math.max(estimate, composer.virtualLineCount);
|
return Math.max(estimate, composer.virtualLineCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The thread list keeps room for itself and for the conversation. */
|
||||||
|
function clampListWidth(columns: number, width: number): number {
|
||||||
|
return Math.max(20, Math.min(columns, width - MIN_CONVERSATION_WIDTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
function truncateLabel(text: string, width: number): string {
|
||||||
|
const line = firstLine(text);
|
||||||
|
return line.length > width ? `${line.slice(0, width - 1)}…` : line;
|
||||||
|
}
|
||||||
|
|
||||||
function firstLine(text: string): string {
|
function firstLine(text: string): string {
|
||||||
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
|
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
|
||||||
return line.length > 100 ? `${line.slice(0, 99)}…` : line;
|
return line.length > 100 ? `${line.slice(0, 99)}…` : line;
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import type { MouseEvent } from "@opentui/core";
|
||||||
|
import type { BoxProps as OpenTuiBoxProps } from "@opentui/react";
|
||||||
|
import { useState, type ReactNode } from "react";
|
||||||
|
|
||||||
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
|
/** Hover state for a clickable box. Moving between a box and its own text sends out then over, so it settles on the right value. */
|
||||||
|
export function useHover() {
|
||||||
|
const [hover, setHover] = useState(false);
|
||||||
|
return [hover, { onMouseOver: () => setHover(true), onMouseOut: () => setHover(false) }] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True for a plain left click. */
|
||||||
|
export const isLeftClick = (event: MouseEvent) => event.button === 0;
|
||||||
|
export const isRightClick = (event: MouseEvent) => event.button === 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A clickable label with its key beside it: `Approve y`. It takes the click for itself, so the
|
||||||
|
* card or pane under it doesn't react too, and its text can't be drag-selected.
|
||||||
|
*/
|
||||||
|
export function Button(props: { readonly label: string; readonly shortcut?: string | undefined; readonly color?: string | undefined; readonly onPress: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
flexDirection="row"
|
||||||
|
flexShrink={0}
|
||||||
|
paddingLeft={1}
|
||||||
|
paddingRight={1}
|
||||||
|
backgroundColor={hover ? colors.selectedBg : colors.buttonBg}
|
||||||
|
{...hoverProps}
|
||||||
|
onMouseDown={(event: MouseEvent) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
if (isLeftClick(event)) props.onPress();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<text fg={props.color ?? colors.text} selectable={false}>{props.label}</text>
|
||||||
|
{props.shortcut ? <text fg={colors.faint} selectable={false}>{` ${props.shortcut}`}</text> : null}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Buttons in a row, wrapping on narrow screens. */
|
||||||
|
export function Buttons({ children }: { readonly children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0}>
|
||||||
|
{children}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BoxProps = Omit<OpenTuiBoxProps, "onMouseDown" | "onMouseOver" | "onMouseOut" | "backgroundColor" | "children">;
|
||||||
|
|
||||||
|
/** A list row that lights up under the pointer: a click picks it, a right-click opens its menu when it has one. */
|
||||||
|
export function ClickRow({ selected, selectedBg, onPress, onMenu, children, ...box }: BoxProps & { readonly selected?: boolean; readonly selectedBg?: string; readonly onPress: () => void; readonly onMenu?: (() => void) | undefined; readonly children: ReactNode }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
{...box}
|
||||||
|
backgroundColor={selected ? (selectedBg ?? colors.selectedBg) : hover ? colors.hoverBg : "transparent"}
|
||||||
|
{...hoverProps}
|
||||||
|
onMouseDown={(event: MouseEvent) => {
|
||||||
|
if (isRightClick(event) && onMenu) return onMenu();
|
||||||
|
if (isLeftClick(event)) onPress();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wheel direction as a step: -1 up, 1 down, 0 for anything else. */
|
||||||
|
export function wheelStep(event: MouseEvent): -1 | 0 | 1 {
|
||||||
|
return event.scroll?.direction === "up" ? -1 : event.scroll?.direction === "down" ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The border between two panes, pressed to start resizing the one on its left. OpenTUI sends a
|
||||||
|
* drag to whatever is under the pointer, so the app's root follows the drag (see App).
|
||||||
|
*/
|
||||||
|
export function ResizeHandle(props: { readonly active: boolean; readonly onStart: () => void; readonly onReset: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box
|
||||||
|
width={1}
|
||||||
|
flexShrink={0}
|
||||||
|
border={["right"]}
|
||||||
|
borderColor={hover || props.active ? colors.borderFocused : colors.border}
|
||||||
|
{...hoverProps}
|
||||||
|
onMouseDown={(event: MouseEvent) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
if (isRightClick(event)) props.onReset();
|
||||||
|
else if (isLeftClick(event)) props.onStart();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { ComposerItem } from "../model/composerMenu.ts";
|
import type { ComposerItem } from "../model/composerMenu.ts";
|
||||||
|
import { ClickRow } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
const MAX_ROWS = 8;
|
const MAX_ROWS = 8;
|
||||||
@@ -22,10 +23,10 @@ export function ComposerMenu(props: { readonly items: readonly ComposerItem[]; r
|
|||||||
const index = start + offset;
|
const index = start + offset;
|
||||||
const label = truncate(item.label, Math.floor(inner * 0.5));
|
const label = truncate(item.label, Math.floor(inner * 0.5));
|
||||||
return (
|
return (
|
||||||
<box key={item.id} flexDirection="row" paddingLeft={1} paddingRight={1} backgroundColor={index === selected ? colors.selectedBg : "transparent"} onMouseDown={() => props.onPick(index)}>
|
<ClickRow key={item.id} flexDirection="row" paddingLeft={1} paddingRight={1} selected={index === selected} onPress={() => props.onPick(index)}>
|
||||||
<text fg={index === selected ? colors.text : colors.accent}>{label}</text>
|
<text fg={index === selected ? colors.text : colors.accent}>{label}</text>
|
||||||
<text fg={colors.faint}>{` ${truncate(item.description, inner - label.length - 2)}`}</text>
|
<text fg={colors.faint}>{` ${truncate(item.description, inner - label.length - 2)}`}</text>
|
||||||
</box>
|
</ClickRow>
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Button, Buttons } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
/** An action that waits for you to say yes: git actions, stopping a server, running an automation. */
|
/** An action that waits for you to say yes: git actions, stopping a server, running an automation. */
|
||||||
@@ -11,7 +12,7 @@ export interface Confirmation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Shown above the composer while a confirmation is open. */
|
/** Shown above the composer while a confirmation is open. */
|
||||||
export function ConfirmBar(props: { readonly confirmation: Confirmation; readonly message: string; readonly onMessage: (value: string) => void; readonly onSubmit: () => void }) {
|
export function ConfirmBar(props: { readonly confirmation: Confirmation; readonly message: string; readonly onMessage: (value: string) => void; readonly onSubmit: () => void; readonly onCancel: () => void }) {
|
||||||
const { confirmation } = props;
|
const { confirmation } = props;
|
||||||
return (
|
return (
|
||||||
<box border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
|
<box border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
|
||||||
@@ -25,7 +26,10 @@ export function ConfirmBar(props: { readonly confirmation: Confirmation; readonl
|
|||||||
<input focused flexGrow={1} placeholder={confirmation.message.placeholder} value={props.message} onInput={props.onMessage} onSubmit={props.onSubmit} />
|
<input focused flexGrow={1} placeholder={confirmation.message.placeholder} value={props.message} onInput={props.onMessage} onSubmit={props.onSubmit} />
|
||||||
</box>
|
</box>
|
||||||
) : null}
|
) : null}
|
||||||
<text fg={colors.faint}>{`enter ${confirmation.confirmLabel} · esc cancel`}</text>
|
<Buttons>
|
||||||
|
<Button label={confirmation.confirmLabel} shortcut="enter" color={colors.warn} onPress={props.onSubmit} />
|
||||||
|
<Button label="cancel" shortcut="esc" onPress={props.onCancel} />
|
||||||
|
</Buttons>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts";
|
import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts";
|
||||||
|
import { ClickRow } from "./Button.tsx";
|
||||||
import { colors, statusColor } from "./theme.ts";
|
import { colors, statusColor } from "./theme.ts";
|
||||||
|
|
||||||
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */
|
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */
|
||||||
@@ -167,9 +168,9 @@ function Sections({ details, inner, loading, selected, onActivate }: { readonly
|
|||||||
function Selectable(props: LineProps & { readonly id: DetailsAction["id"]; readonly inner: number; readonly text?: string; readonly color?: string; readonly children?: ReactNode }) {
|
function Selectable(props: LineProps & { readonly id: DetailsAction["id"]; readonly inner: number; readonly text?: string; readonly color?: string; readonly children?: ReactNode }) {
|
||||||
const active = props.selected === props.id;
|
const active = props.selected === props.id;
|
||||||
return (
|
return (
|
||||||
<box backgroundColor={active ? colors.selectedBg : "transparent"} onMouseDown={() => props.onActivate(props.id)}>
|
<ClickRow selected={active} onPress={() => props.onActivate(props.id)}>
|
||||||
{props.children ?? <text fg={active ? colors.text : (props.color ?? colors.muted)}>{truncate(props.text ?? "", props.inner)}</text>}
|
{props.children ?? <text fg={active ? colors.text : (props.color ?? colors.muted)}>{truncate(props.text ?? "", props.inner)}</text>}
|
||||||
</box>
|
</ClickRow>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+15
-3
@@ -1,8 +1,9 @@
|
|||||||
import type { ReviewDiffFileContentsInput } from "@t3tools/contracts";
|
import type { ReviewDiffFileContentsInput } from "@t3tools/contracts";
|
||||||
import { splitPatch } from "../model/diffs.ts";
|
import { splitPatch } from "../model/diffs.ts";
|
||||||
import type { ScrollBoxRenderable } from "@opentui/core";
|
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||||
import type { RefObject } from "react";
|
import type { RefObject } from "react";
|
||||||
|
|
||||||
|
import { isLeftClick, useHover } from "./Button.tsx";
|
||||||
import { colors, getMarkdownStyle } from "./theme.ts";
|
import { colors, getMarkdownStyle } from "./theme.ts";
|
||||||
|
|
||||||
export interface DiffState {
|
export interface DiffState {
|
||||||
@@ -18,7 +19,7 @@ export interface DiffState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Working-tree or checkpoint changes through the same unified diff renderer. */
|
/** Working-tree or checkpoint changes through the same unified diff renderer. */
|
||||||
export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly selected: number; readonly expanded: Readonly<Record<string, { patch?: string; error?: string }>> }) {
|
export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly selected: number; readonly expanded: Readonly<Record<string, { patch?: string; error?: string }>>; readonly onFile: (index: number) => void }) {
|
||||||
const { diff } = props;
|
const { diff } = props;
|
||||||
const files = diff.patch ? splitPatch(diff.patch) : [];
|
const files = diff.patch ? splitPatch(diff.patch) : [];
|
||||||
return (
|
return (
|
||||||
@@ -38,7 +39,7 @@ export function DiffView(props: { readonly diff: DiffState; readonly scrollRef:
|
|||||||
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
|
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
|
||||||
{files.map((file, index) => (
|
{files.map((file, index) => (
|
||||||
<box key={file.path} id={`diff-file-${index}`} flexDirection="column" marginTop={1}>
|
<box key={file.path} id={`diff-file-${index}`} flexDirection="column" marginTop={1}>
|
||||||
<text fg={index === props.selected ? colors.accent : colors.muted}>{`${index === props.selected ? "▸ " : " "}${file.path}`}</text>
|
<FileHeader path={file.path} selected={index === props.selected} canExpand={diff.source !== undefined} onPress={() => props.onFile(index)} />
|
||||||
{props.expanded[file.path] && !props.expanded[file.path]?.patch ? <text fg={props.expanded[file.path]?.error ? colors.bad : colors.muted}>{props.expanded[file.path]?.error ?? "Loading full file…"}</text> : null}
|
{props.expanded[file.path] && !props.expanded[file.path]?.patch ? <text fg={props.expanded[file.path]?.error ? colors.bad : colors.muted}>{props.expanded[file.path]?.error ?? "Loading full file…"}</text> : null}
|
||||||
<diff
|
<diff
|
||||||
diff={props.expanded[file.path]?.patch ?? file.patch}
|
diff={props.expanded[file.path]?.patch ?? file.patch}
|
||||||
@@ -63,6 +64,17 @@ export function DiffView(props: { readonly diff: DiffState; readonly scrollRef:
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A click selects the file; a click on the selected one shows its whole file, as x does. */
|
||||||
|
function FileHeader(props: { readonly path: string; readonly selected: boolean; readonly canExpand: boolean; readonly onPress: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && props.onPress()}>
|
||||||
|
<text fg={props.selected ? colors.accent : hover ? colors.text : colors.muted} selectable={false}>{`${props.selected ? "▸ " : " "}${props.path}`}</text>
|
||||||
|
{hover && props.selected && props.canExpand ? <text fg={colors.faint} selectable={false}>{" click for the whole file"}</text> : null}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export { splitPatch } from "../model/diffs.ts";
|
export { splitPatch } from "../model/diffs.ts";
|
||||||
|
|
||||||
const FILETYPES: Record<string, string> = { ts: "typescript", tsx: "tsx", js: "javascript", jsx: "javascript", json: "json", md: "markdown", rs: "rust", py: "python", go: "go", css: "css", html: "html", sh: "bash", yml: "yaml", yaml: "yaml", zig: "zig" };
|
const FILETYPES: Record<string, string> = { ts: "typescript", tsx: "tsx", js: "javascript", jsx: "javascript", json: "json", md: "markdown", rs: "rust", py: "python", go: "go", css: "css", html: "html", sh: "bash", yml: "yaml", yaml: "yaml", zig: "zig" };
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { ClickRow } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
export interface DraftLine {
|
export interface DraftLine {
|
||||||
@@ -23,11 +24,11 @@ export function DraftView(props: { readonly lines: readonly DraftLine[] }) {
|
|||||||
</box>
|
</box>
|
||||||
<box flexDirection="column" marginTop={1}>
|
<box flexDirection="column" marginTop={1}>
|
||||||
{props.lines.map((line) => (
|
{props.lines.map((line) => (
|
||||||
<box key={line.key} flexDirection="row" height={1} onMouseDown={line.onPick}>
|
<ClickRow key={line.key} flexDirection="row" height={1} onPress={line.onPick}>
|
||||||
<text fg={colors.muted} flexShrink={0}>{line.label.padEnd(labelWidth)}</text>
|
<text fg={colors.muted} flexShrink={0}>{line.label.padEnd(labelWidth)}</text>
|
||||||
<text fg={colors.text} flexShrink={0}>{line.value}</text>
|
<text fg={colors.text} flexShrink={0}>{line.value}</text>
|
||||||
<text fg={colors.faint} wrapMode="none">{` ${line.shortcut}`}</text>
|
<text fg={colors.faint} wrapMode="none">{` ${line.shortcut}`}</text>
|
||||||
</box>
|
</ClickRow>
|
||||||
))}
|
))}
|
||||||
</box>
|
</box>
|
||||||
<text fg={colors.faint} marginTop={1}>Write the first message below; sending it starts the thread.</text>
|
<text fg={colors.faint} marginTop={1}>Write the first message below; sending it starts the thread.</text>
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { MouseEvent } from "@opentui/core";
|
||||||
|
|
||||||
|
import { hintKey, type HintKey } from "../model/hints.ts";
|
||||||
|
import { isLeftClick, useHover } from "./Button.tsx";
|
||||||
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
|
/** The key hints along the bottom; each one that names a single key presses it when clicked. */
|
||||||
|
export function HintBar(props: { readonly text: string; readonly mode: string; readonly onPress: (key: HintKey) => void }) {
|
||||||
|
const parts = props.text.split(" · ");
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" overflow="hidden">
|
||||||
|
{parts.map((part, index) => (
|
||||||
|
<Hint key={`${index}:${part}`} text={part} separator={index > 0} hintKey={hintKey(part, props.mode)} onPress={props.onPress} />
|
||||||
|
))}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Hint(props: { readonly text: string; readonly separator: boolean; readonly hintKey: HintKey | null; readonly onPress: (key: HintKey) => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
const key = props.hintKey;
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" flexShrink={0}>
|
||||||
|
{props.separator ? <text fg={colors.faint} selectable={false}>{" · "}</text> : null}
|
||||||
|
<text
|
||||||
|
fg={key && hover ? colors.text : colors.faint}
|
||||||
|
selectable={false}
|
||||||
|
{...(key ? { ...hoverProps, onMouseDown: (event: MouseEvent) => isLeftClick(event) && props.onPress(key) } : {})}
|
||||||
|
>
|
||||||
|
{props.text}
|
||||||
|
</text>
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
+8
-3
@@ -1,4 +1,7 @@
|
|||||||
import type { PaletteEntry, PaletteGroup } from "../model/palette.ts";
|
import type { PaletteEntry, PaletteGroup } from "../model/palette.ts";
|
||||||
|
import type { MouseEvent } from "@opentui/core";
|
||||||
|
|
||||||
|
import { ClickRow, wheelStep } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,6 +19,8 @@ export function Palette(props: {
|
|||||||
readonly onQuery: (query: string) => void;
|
readonly onQuery: (query: string) => void;
|
||||||
readonly onSubmit: () => void;
|
readonly onSubmit: () => void;
|
||||||
readonly onPick: (index: number) => void;
|
readonly onPick: (index: number) => void;
|
||||||
|
/** The wheel moves the selection, as the arrows do. */
|
||||||
|
readonly onMove: (step: -1 | 1) => void;
|
||||||
}) {
|
}) {
|
||||||
const width = Math.min(80, props.width - 4);
|
const width = Math.min(80, props.width - 4);
|
||||||
const listHeight = Math.max(4, Math.min(props.height - 8, 22));
|
const listHeight = Math.max(4, Math.min(props.height - 8, 22));
|
||||||
@@ -37,7 +42,7 @@ export function Palette(props: {
|
|||||||
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
|
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
|
||||||
</box>
|
</box>
|
||||||
{props.status ? <text fg={colors.muted} paddingLeft={1}>{props.status}</text> : null}
|
{props.status ? <text fg={colors.muted} paddingLeft={1}>{props.status}</text> : null}
|
||||||
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
|
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1} onMouseScroll={(event: MouseEvent) => { const step = wheelStep(event); if (step) props.onMove(step); }}>
|
||||||
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
|
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
|
||||||
{rows.slice(start, start + listHeight).map((row) =>
|
{rows.slice(start, start + listHeight).map((row) =>
|
||||||
row.kind === "header" ? (
|
row.kind === "header" ? (
|
||||||
@@ -58,11 +63,11 @@ function Row(props: { readonly entry: PaletteEntry; readonly selected: boolean;
|
|||||||
const right = entry.kind === "command" ? (entry.command.shortcut ?? "") : entry.project;
|
const right = entry.kind === "command" ? (entry.command.shortcut ?? "") : entry.project;
|
||||||
const title = entry.kind === "command" ? entry.command.title : `${entry.subagent ? "↳ " : ""}${entry.snippet ? truncate(entry.title, Math.max(12, Math.floor(props.inner / 3))) : entry.title}${entry.snippet ? ` — ${entry.snippet}` : ""}`;
|
const title = entry.kind === "command" ? entry.command.title : `${entry.subagent ? "↳ " : ""}${entry.snippet ? truncate(entry.title, Math.max(12, Math.floor(props.inner / 3))) : entry.title}${entry.snippet ? ` — ${entry.snippet}` : ""}`;
|
||||||
return (
|
return (
|
||||||
<box flexDirection="row" paddingLeft={1} paddingRight={1} backgroundColor={props.selected ? colors.selectedBg : "transparent"} onMouseDown={props.onPick}>
|
<ClickRow flexDirection="row" paddingLeft={1} paddingRight={1} selected={props.selected} onPress={props.onPick}>
|
||||||
<text fg={props.selected ? colors.text : entry.kind === "command" ? colors.text : colors.muted}>{truncate(title, props.inner - right.length - 2)}</text>
|
<text fg={props.selected ? colors.text : entry.kind === "command" ? colors.text : colors.muted}>{truncate(title, props.inner - right.length - 2)}</text>
|
||||||
<box flexGrow={1} />
|
<box flexGrow={1} />
|
||||||
<text fg={colors.faint}>{right}</text>
|
<text fg={colors.faint}>{right}</text>
|
||||||
</box>
|
</ClickRow>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { ScrollBoxRenderable } from "@opentui/core";
|
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||||
import type { RefObject } from "react";
|
import type { RefObject } from "react";
|
||||||
|
|
||||||
import type { PullRequestLine } from "../model/pullRequests.ts";
|
import type { PullRequestLine } from "../model/pullRequests.ts";
|
||||||
|
import { Button, isLeftClick, isRightClick, useHover } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
export interface PullRequestViewState {
|
export interface PullRequestViewState {
|
||||||
@@ -23,17 +24,20 @@ const LINE_COLORS: Record<PullRequestLine["kind"], string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** A linked pull request in place of the conversation: j/k scroll, o opens it, esc closes. */
|
/** A linked pull request in place of the conversation: j/k scroll, o opens it, esc closes. */
|
||||||
export function PullRequestView(props: { readonly view: PullRequestViewState; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
|
/** o opens the URL; a right-click anywhere offers the view's actions. */
|
||||||
|
export function PullRequestView(props: { readonly view: PullRequestViewState; readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly onOpenUrl: () => void; readonly onMenu: () => void; readonly onClose: () => void }) {
|
||||||
const { view } = props;
|
const { view } = props;
|
||||||
return (
|
return (
|
||||||
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
|
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1} onMouseDown={(event: MouseEvent) => isRightClick(event) && props.onMenu()}>
|
||||||
<box flexDirection="row" flexShrink={0} height={1}>
|
<box flexDirection="row" flexShrink={0} height={1}>
|
||||||
<text fg={colors.text}>
|
<text fg={colors.text}>
|
||||||
<strong>Pull request</strong>
|
<strong>Pull request</strong>
|
||||||
</text>
|
</text>
|
||||||
{view.watching ? <text fg={colors.good}>{" watching"}</text> : null}
|
{view.watching ? <text fg={colors.good}>{" watching"}</text> : null}
|
||||||
<box flexGrow={1} />
|
<box flexGrow={1} />
|
||||||
<text fg={colors.faint}>esc close</text>
|
<Button label="Actions" shortcut="right-click" onPress={props.onMenu} />
|
||||||
|
<text> </text>
|
||||||
|
<Button label="Close" shortcut="esc" onPress={props.onClose} />
|
||||||
</box>
|
</box>
|
||||||
{view.status === "loading" ? <text fg={colors.muted}>Loading pull request…</text> : null}
|
{view.status === "loading" ? <text fg={colors.muted}>Loading pull request…</text> : null}
|
||||||
{view.status === "error" ? <text fg={colors.bad}>{`Could not load the pull request: ${view.error ?? "unknown error"}`}</text> : null}
|
{view.status === "error" ? <text fg={colors.bad}>{`Could not load the pull request: ${view.error ?? "unknown error"}`}</text> : null}
|
||||||
@@ -47,6 +51,8 @@ export function PullRequestView(props: { readonly view: PullRequestViewState; re
|
|||||||
<text key={index} fg={colors.text}>
|
<text key={index} fg={colors.text}>
|
||||||
<strong>{line.text}</strong>
|
<strong>{line.text}</strong>
|
||||||
</text>
|
</text>
|
||||||
|
) : /^https?:\/\//.test(line.text) ? (
|
||||||
|
<Link key={index} text={line.text} onPress={props.onOpenUrl} />
|
||||||
) : (
|
) : (
|
||||||
<text key={index} fg={line.kind === "check" ? checkColor(line.text) : LINE_COLORS[line.kind]}>
|
<text key={index} fg={line.kind === "check" ? checkColor(line.text) : LINE_COLORS[line.kind]}>
|
||||||
{line.text || " "}
|
{line.text || " "}
|
||||||
@@ -58,6 +64,15 @@ export function PullRequestView(props: { readonly view: PullRequestViewState; re
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Link(props: { readonly text: string; readonly onPress: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<text fg={hover ? colors.text : colors.user} selectable={false} {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && props.onPress()}>
|
||||||
|
<u>{props.text}</u>
|
||||||
|
</text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function checkColor(text: string): string {
|
function checkColor(text: string): string {
|
||||||
if (text.startsWith("✓")) return colors.good;
|
if (text.startsWith("✓")) return colors.good;
|
||||||
if (text.startsWith("✕")) return colors.bad;
|
if (text.startsWith("✕")) return colors.bad;
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import type { ThreadPendingUserInput } from "@t3tools/client-runtime/state/thread-requests";
|
import type { ThreadPendingUserInput } from "@t3tools/client-runtime/state/thread-requests";
|
||||||
import { isPendingUserInputOptionSelected, type PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
|
import { isPendingUserInputOptionSelected, type PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
|
||||||
|
|
||||||
|
import type { MouseEvent } from "@opentui/core";
|
||||||
|
|
||||||
|
import { Button, Buttons, isLeftClick, useHover } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,6 +14,10 @@ export function QuestionPanel(props: {
|
|||||||
readonly request: ThreadPendingUserInput;
|
readonly request: ThreadPendingUserInput;
|
||||||
readonly index: number;
|
readonly index: number;
|
||||||
readonly draft: PendingUserInputDraftAnswer | undefined;
|
readonly draft: PendingUserInputDraftAnswer | undefined;
|
||||||
|
readonly onPick: (optionIndex: number) => void;
|
||||||
|
/** Multi-select questions move on with a click here, as enter does. */
|
||||||
|
readonly onNext: () => void;
|
||||||
|
readonly onDismiss?: (() => void) | undefined;
|
||||||
}) {
|
}) {
|
||||||
const { request, index, draft } = props;
|
const { request, index, draft } = props;
|
||||||
const question = request.questions[index];
|
const question = request.questions[index];
|
||||||
@@ -29,14 +36,25 @@ export function QuestionPanel(props: {
|
|||||||
{question.options.slice(0, 9).map((option, optionIndex) => {
|
{question.options.slice(0, 9).map((option, optionIndex) => {
|
||||||
const selected = isPendingUserInputOptionSelected(question, draft, option.value ?? option.label);
|
const selected = isPendingUserInputOptionSelected(question, draft, option.value ?? option.label);
|
||||||
const mark = question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○";
|
const mark = question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○";
|
||||||
return (
|
return <Option key={option.label} label={option.label} description={option.description} prefix={`${optionIndex + 1} ${mark} `} selected={selected} onPick={() => props.onPick(optionIndex)} />;
|
||||||
<box key={option.label} flexDirection="row">
|
|
||||||
<text fg={selected ? colors.input : colors.faint}>{`${optionIndex + 1} ${mark} `}</text>
|
|
||||||
<text fg={selected ? colors.text : colors.muted}>{option.label}</text>
|
|
||||||
<text fg={colors.faint}>{option.description ? ` ${option.description}` : ""}</text>
|
|
||||||
</box>
|
|
||||||
);
|
|
||||||
})}
|
})}
|
||||||
|
{question.multiSelect || props.onDismiss ? (
|
||||||
|
<Buttons>
|
||||||
|
{question.multiSelect ? <Button label={index + 1 < total ? "Next" : "Submit"} shortcut="enter" color={colors.input} onPress={props.onNext} /> : null}
|
||||||
|
{props.onDismiss ? <Button label="Dismiss" shortcut="x" onPress={props.onDismiss} /> : null}
|
||||||
|
</Buttons>
|
||||||
|
) : null}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Option(props: { readonly label: string; readonly description?: string | undefined; readonly prefix: string; readonly selected: boolean; readonly onPick: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" backgroundColor={hover ? colors.hoverBg : "transparent"} {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && props.onPick()}>
|
||||||
|
<text fg={props.selected ? colors.input : colors.faint} selectable={false}>{props.prefix}</text>
|
||||||
|
<text fg={props.selected ? colors.text : colors.muted} selectable={false}>{props.label}</text>
|
||||||
|
<text fg={colors.faint} selectable={false}>{props.description ? ` ${props.description}` : ""}</text>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+39
-8
@@ -1,6 +1,18 @@
|
|||||||
|
import type { MouseEvent } from "@opentui/core";
|
||||||
|
|
||||||
import type { QueuedMessage } from "../model/queue.ts";
|
import type { QueuedMessage } from "../model/queue.ts";
|
||||||
|
import { Button, Buttons, isLeftClick, useHover } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
|
export interface QueueActions {
|
||||||
|
readonly focus: (index: number) => void;
|
||||||
|
readonly sendNow: (index: number) => void;
|
||||||
|
readonly edit: (index: number) => void;
|
||||||
|
readonly remove: (index: number) => void;
|
||||||
|
/** Continue after an interrupt, or send what it held back. */
|
||||||
|
readonly resume: (() => void) | null;
|
||||||
|
}
|
||||||
|
|
||||||
/** As the web: three rows, then the rest behind "show all". */
|
/** As the web: three rows, then the rest behind "show all". */
|
||||||
const VISIBLE_ROWS = 3;
|
const VISIBLE_ROWS = 3;
|
||||||
|
|
||||||
@@ -8,23 +20,22 @@ const VISIBLE_ROWS = 3;
|
|||||||
* The web's queued messages, just above the composer: each waits for the run to finish. Focused
|
* The web's queued messages, just above the composer: each waits for the run to finish. Focused
|
||||||
* (Q), j/k move, enter sends now, e edits in the composer, x removes.
|
* (Q), j/k move, enter sends now, e edits in the composer, x removes.
|
||||||
*/
|
*/
|
||||||
export function QueuePanel(props: { readonly queued: readonly QueuedMessage[]; readonly focus: number | null; readonly editingRunId: string | null; readonly held: boolean; readonly width: number }) {
|
export function QueuePanel(props: { readonly queued: readonly QueuedMessage[]; readonly focus: number | null; readonly editingRunId: string | null; readonly held: boolean; readonly width: number; readonly actions: QueueActions }) {
|
||||||
|
const { actions } = props;
|
||||||
const { queued, focus } = props;
|
const { queued, focus } = props;
|
||||||
const start = focus === null ? 0 : Math.max(0, Math.min(focus - 1, queued.length - VISIBLE_ROWS));
|
const start = focus === null ? 0 : Math.max(0, Math.min(focus - 1, queued.length - VISIBLE_ROWS));
|
||||||
const shown = queued.slice(start, start + VISIBLE_ROWS);
|
const shown = queued.slice(start, start + VISIBLE_ROWS);
|
||||||
const inner = Math.max(10, props.width - 8);
|
const inner = Math.max(10, props.width - 8);
|
||||||
return (
|
return (
|
||||||
<box border borderStyle="rounded" borderColor={focus === null ? colors.border : colors.borderFocused} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
|
<box border borderStyle="rounded" borderColor={focus === null ? colors.border : colors.borderFocused} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
|
||||||
<text fg={colors.muted}>{`${queued.length} queued${props.held ? " · held after the interrupt" : ""}`}</text>
|
<box flexDirection="row" columnGap={1}>
|
||||||
|
<text fg={colors.muted}>{`${queued.length} queued${props.held ? " · held after the interrupt" : ""}`}</text>
|
||||||
|
{props.held && actions.resume ? <Button label="Send them now" shortcut="enter" color={colors.accent} onPress={actions.resume} /> : null}
|
||||||
|
</box>
|
||||||
{shown.map((message, offset) => {
|
{shown.map((message, offset) => {
|
||||||
const index = start + offset;
|
const index = start + offset;
|
||||||
const editing = message.runId === props.editingRunId;
|
const editing = message.runId === props.editingRunId;
|
||||||
return (
|
return <QueueRow key={message.runId} text={message.text} width={inner} focused={index === focus} editing={editing} index={index} actions={actions} />;
|
||||||
<box key={message.runId} flexDirection="row" backgroundColor={index === focus ? colors.selectedBg : "transparent"}>
|
|
||||||
<text fg={editing ? colors.accent : colors.text}>{`${index + 1}. ${truncate(message.text, inner)}`}</text>
|
|
||||||
{editing ? <text fg={colors.accent}>{" editing in the composer"}</text> : null}
|
|
||||||
</box>
|
|
||||||
);
|
|
||||||
})}
|
})}
|
||||||
{queued.length > shown.length ? <text fg={colors.faint}>{`${queued.length - shown.length} more · Q to go through them`}</text> : null}
|
{queued.length > shown.length ? <text fg={colors.faint}>{`${queued.length - shown.length} more · Q to go through them`}</text> : null}
|
||||||
</box>
|
</box>
|
||||||
@@ -35,3 +46,23 @@ function truncate(text: string, width: number): string {
|
|||||||
const single = text.replace(/\s+/g, " ").trim();
|
const single = text.replace(/\s+/g, " ").trim();
|
||||||
return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single;
|
return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function QueueRow(props: { readonly text: string; readonly width: number; readonly focused: boolean; readonly editing: boolean; readonly index: number; readonly actions: QueueActions }) {
|
||||||
|
const { index, actions } = props;
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
const buttons = props.focused || hover;
|
||||||
|
return (
|
||||||
|
<box flexDirection="row" columnGap={1} backgroundColor={props.focused ? colors.selectedBg : hover ? colors.hoverBg : "transparent"} {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && actions.focus(index)}>
|
||||||
|
<text fg={props.editing ? colors.accent : colors.text} selectable={false}>{`${index + 1}. ${truncate(props.text, props.width - (buttons ? 34 : 0) - (props.editing ? 24 : 0))}`}</text>
|
||||||
|
{props.editing ? <text fg={colors.accent} selectable={false}>{" editing in the composer"}</text> : null}
|
||||||
|
<box flexGrow={1} />
|
||||||
|
{buttons ? (
|
||||||
|
<Buttons>
|
||||||
|
<Button label="Send now" shortcut="s" onPress={() => actions.sendNow(index)} />
|
||||||
|
<Button label="Edit" shortcut="e" onPress={() => actions.edit(index)} />
|
||||||
|
<Button label="Remove" shortcut="x" color={colors.bad} onPress={() => actions.remove(index)} />
|
||||||
|
</Buttons>
|
||||||
|
) : null}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestPrivacyNote, type SecretRequestItem } from "@t3tools/client-runtime/secret-request";
|
import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestPrivacyNote, type SecretRequestItem } from "@t3tools/client-runtime/secret-request";
|
||||||
|
|
||||||
|
import { Button, Buttons } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The web's secret request card: the agent asks for a value it never sees. Typing is masked;
|
* The web's secret request card: the agent asks for a value it never sees. Typing is masked;
|
||||||
* `value` is null until the field is focused (enter).
|
* `value` is null until the field is focused (enter).
|
||||||
*/
|
*/
|
||||||
export function SecretPanel(props: { readonly request: SecretRequestItem; readonly value: string | null; readonly error: string | null; readonly busy: boolean }) {
|
export function SecretPanel(props: { readonly request: SecretRequestItem; readonly value: string | null; readonly error: string | null; readonly busy: boolean; readonly actions: { readonly focus: () => void; readonly cancel: () => void; readonly save: () => void; readonly decline: () => void } }) {
|
||||||
|
const { actions } = props;
|
||||||
const { request, value } = props;
|
const { request, value } = props;
|
||||||
const focused = value !== null;
|
const focused = value !== null;
|
||||||
return (
|
return (
|
||||||
@@ -15,9 +17,13 @@ export function SecretPanel(props: { readonly request: SecretRequestItem; readon
|
|||||||
<strong>{`🔒 ${request.label}`}</strong>
|
<strong>{`🔒 ${request.label}`}</strong>
|
||||||
</text>
|
</text>
|
||||||
{request.reason.trim() ? <text fg={colors.muted}>{request.reason}</text> : null}
|
{request.reason.trim() ? <text fg={colors.muted}>{request.reason}</text> : null}
|
||||||
<text fg={focused && value ? colors.text : colors.faint}>{focused ? (value ? "•".repeat(Math.min(value.length, 64)) : (request.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER)) : "enter to answer · x decline"}</text>
|
{focused ? <text fg={value ? colors.text : colors.faint} selectable={false}>{value ? "•".repeat(Math.min(value.length, 64)) : (request.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER)}</text> : null}
|
||||||
{props.error ? <text fg={colors.bad}>{props.error}</text> : null}
|
{props.error ? <text fg={colors.bad}>{props.error}</text> : null}
|
||||||
<text fg={colors.faint}>{props.busy ? "Saving…" : `${secretRequestPrivacyNote(request)}${focused ? " · enter save securely · esc cancel" : ""}`}</text>
|
<text fg={colors.faint}>{props.busy ? "Saving…" : secretRequestPrivacyNote(request)}</text>
|
||||||
|
<Buttons>
|
||||||
|
{focused ? <Button label="Save securely" shortcut="enter" color={colors.warn} onPress={actions.save} /> : <Button label="Answer" shortcut="enter" color={colors.warn} onPress={actions.focus} />}
|
||||||
|
{focused ? <Button label="Cancel" shortcut="esc" onPress={actions.cancel} /> : <Button label="Decline" shortcut="x" onPress={actions.decline} />}
|
||||||
|
</Buttons>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { SettingRow } from "../model/settings.ts";
|
import type { SettingRow } from "../model/settings.ts";
|
||||||
|
import { ClickRow } from "./Button.tsx";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
|
|
||||||
/** Settings in place of the conversation: tui3's own (cycled with enter or a click), then the server's, read-only. */
|
/** Settings in place of the conversation: tui3's own (cycled with enter or a click), then the server's, read-only. */
|
||||||
@@ -27,11 +28,11 @@ export function SettingsView(props: {
|
|||||||
{props.rows.map((row, index) => {
|
{props.rows.map((row, index) => {
|
||||||
const selected = index === props.selected;
|
const selected = index === props.selected;
|
||||||
return (
|
return (
|
||||||
<box key={row.key} flexDirection="row" height={1} backgroundColor={selected ? colors.selectedBg : "transparent"} onMouseDown={() => props.onCycle(index)}>
|
<ClickRow key={row.key} flexDirection="row" height={1} selected={selected} onPress={() => props.onCycle(index)}>
|
||||||
<text fg={colors.muted} flexShrink={0}>{`${selected ? "▸ " : " "}${row.label.padEnd(labelWidth)}`}</text>
|
<text fg={colors.muted} flexShrink={0}>{`${selected ? "▸ " : " "}${row.label.padEnd(labelWidth)}`}</text>
|
||||||
<text fg={colors.text} flexShrink={0}>{row.value}</text>
|
<text fg={colors.text} flexShrink={0}>{row.value}</text>
|
||||||
<text fg={colors.faint} wrapMode="none">{` ${row.help}`}</text>
|
<text fg={colors.faint} wrapMode="none">{` ${row.help}`}</text>
|
||||||
</box>
|
</ClickRow>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
<text fg={colors.faint} marginTop={1}>T3 Code · change these in the app</text>
|
<text fg={colors.faint} marginTop={1}>T3 Code · change these in the app</text>
|
||||||
|
|||||||
+32
-8
@@ -1,7 +1,9 @@
|
|||||||
import type { MouseEvent } from "@opentui/core";
|
import type { MouseEvent } from "@opentui/core";
|
||||||
import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts";
|
import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts";
|
||||||
import type { ThreadId } from "@t3tools/contracts";
|
import type { ThreadId } from "@t3tools/contracts";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { ClickRow, wheelStep } from "./Button.tsx";
|
||||||
import { colors, statusColor } from "./theme.ts";
|
import { colors, statusColor } from "./theme.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,7 +36,12 @@ export function ThreadList(props: {
|
|||||||
const { rows, selected, focused, width, height, now } = props;
|
const { rows, selected, focused, width, height, now } = props;
|
||||||
// Rows take two lines plus a header per section; keep the selection in view.
|
// Rows take two lines plus a header per section; keep the selection in view.
|
||||||
const visibleCount = Math.max(1, Math.floor((height - (props.filtering ? 9 : 6)) / 2));
|
const visibleCount = Math.max(1, Math.floor((height - (props.filtering ? 9 : 6)) / 2));
|
||||||
const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount));
|
const maxStart = Math.max(0, rows.length - visibleCount);
|
||||||
|
// The wheel scrolls the list without moving the selection; moving the selection brings it back.
|
||||||
|
const [scrolled, setScrolled] = useState<number | null>(null);
|
||||||
|
useEffect(() => setScrolled(null), [selected]);
|
||||||
|
const centred = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), maxStart));
|
||||||
|
const start = Math.min(scrolled ?? centred, maxStart);
|
||||||
const windowRows = rows.slice(start, start + visibleCount);
|
const windowRows = rows.slice(start, start + visibleCount);
|
||||||
const inner = Math.max(8, width - 3);
|
const inner = Math.max(8, width - 3);
|
||||||
// Active goes unlabelled when it leads the list, as in the web sidebar.
|
// Active goes unlabelled when it leads the list, as in the web sidebar.
|
||||||
@@ -56,13 +63,15 @@ export function ThreadList(props: {
|
|||||||
const recede = !isSelected && (row.status === "working" || row.status === "waiting" || (row.status === "ready" && !row.unread));
|
const recede = !isSelected && (row.status === "working" || row.status === "waiting" || (row.status === "ready" && !row.unread));
|
||||||
const title = truncate(row.thread.title || "New thread", inner);
|
const title = truncate(row.thread.title || "New thread", inner);
|
||||||
lines.push(
|
lines.push(
|
||||||
<box
|
<ClickRow
|
||||||
key={row.thread.id}
|
key={row.thread.id}
|
||||||
flexDirection="column"
|
flexDirection="column"
|
||||||
paddingLeft={1}
|
paddingLeft={1}
|
||||||
paddingRight={1}
|
paddingRight={1}
|
||||||
backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.panel) : "transparent"}
|
selected={isSelected}
|
||||||
onMouseDown={(event: MouseEvent) => (event.button === 2 ? props.onMenu(row.thread.id) : props.onPick(row.thread.id))}
|
selectedBg={focused ? colors.selectedBg : colors.panel}
|
||||||
|
onPress={() => props.onPick(row.thread.id)}
|
||||||
|
onMenu={() => props.onMenu(row.thread.id)}
|
||||||
>
|
>
|
||||||
<box flexDirection="row">
|
<box flexDirection="row">
|
||||||
<text fg={colors.faint}>{left}</text>
|
<text fg={colors.faint}>{left}</text>
|
||||||
@@ -70,12 +79,21 @@ export function ThreadList(props: {
|
|||||||
<text fg={status ? statusColor[status.tone] : colors.faint}>{right}</text>
|
<text fg={status ? statusColor[status.tone] : colors.faint}>{right}</text>
|
||||||
</box>
|
</box>
|
||||||
<text fg={recede ? colors.muted : colors.text}>{attention ? <strong>{title}</strong> : title}</text>
|
<text fg={recede ? colors.muted : colors.text}>{attention ? <strong>{title}</strong> : title}</text>
|
||||||
</box>,
|
</ClickRow>,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
const collapsed = [...props.collapsed].filter(([, count]) => count > 0);
|
const collapsed = [...props.collapsed].filter(([, count]) => count > 0);
|
||||||
return (
|
return (
|
||||||
<box border={["right"]} borderColor={colors.border} width={width} flexShrink={0} overflow="hidden" flexDirection="column">
|
<box
|
||||||
|
width={width}
|
||||||
|
flexShrink={0}
|
||||||
|
overflow="hidden"
|
||||||
|
flexDirection="column"
|
||||||
|
onMouseScroll={(event: MouseEvent) => {
|
||||||
|
const step = wheelStep(event);
|
||||||
|
if (step) setScrolled(Math.max(0, Math.min(maxStart, start + step)));
|
||||||
|
}}
|
||||||
|
>
|
||||||
{props.filtering ? (
|
{props.filtering ? (
|
||||||
<box border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0}>
|
<box border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0}>
|
||||||
<input focused placeholder="Filter threads…" value={props.filter} onInput={props.onFilter} onSubmit={props.onFilterDone} />
|
<input focused placeholder="Filter threads…" value={props.filter} onInput={props.onFilter} onSubmit={props.onFilterDone} />
|
||||||
@@ -86,9 +104,15 @@ export function ThreadList(props: {
|
|||||||
{rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
|
{rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
|
||||||
<box flexGrow={1} />
|
<box flexGrow={1} />
|
||||||
{props.shelfStatus ? <text fg={colors.muted} paddingLeft={1}>{props.shelfStatus}</text> : null}
|
{props.shelfStatus ? <text fg={colors.muted} paddingLeft={1}>{props.shelfStatus}</text> : null}
|
||||||
{props.showMore ? <text fg={colors.accent} paddingLeft={1} onMouseDown={() => props.onShowMore?.()}>Show more settled threads (ctrl+k)</text> : null}
|
{props.showMore ? (
|
||||||
|
<ClickRow paddingLeft={1} onPress={() => props.onShowMore?.()}>
|
||||||
|
<text fg={colors.accent} selectable={false}>Show more settled threads</text>
|
||||||
|
</ClickRow>
|
||||||
|
) : null}
|
||||||
{collapsed.map(([section, count]) => (
|
{collapsed.map(([section, count]) => (
|
||||||
<text key={section} fg={colors.faint} onMouseDown={props.onUnfold}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
|
<ClickRow key={section} onPress={props.onUnfold}>
|
||||||
|
<text fg={colors.faint} selectable={false}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
|
||||||
|
</ClickRow>
|
||||||
))}
|
))}
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
|
|||||||
+68
-29
@@ -1,5 +1,5 @@
|
|||||||
import type { ScrollBoxRenderable } from "@opentui/core";
|
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||||
import type { ThreadId } from "@t3tools/contracts";
|
import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts";
|
||||||
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
|
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
|
||||||
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
|
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
|
||||||
import { memo, useState, type RefObject } from "react";
|
import { memo, useState, type RefObject } from "react";
|
||||||
@@ -7,6 +7,7 @@ import { findTextSegments } from "../model/search.ts";
|
|||||||
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
|
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
|
||||||
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
|
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
|
||||||
import { FindText } from "./FindText.tsx";
|
import { FindText } from "./FindText.tsx";
|
||||||
|
import { Button, Buttons, isLeftClick, isRightClick, useHover } from "./Button.tsx";
|
||||||
|
|
||||||
import { CommandOutput } from "./CommandOutput.tsx";
|
import { CommandOutput } from "./CommandOutput.tsx";
|
||||||
import type { T3Session, ThreadHistory } from "../client/session.ts";
|
import type { T3Session, ThreadHistory } from "../client/session.ts";
|
||||||
@@ -14,6 +15,21 @@ import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, ty
|
|||||||
import { blockFor } from "../model/transcript.ts";
|
import { blockFor } from "../model/transcript.ts";
|
||||||
import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
|
import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
|
||||||
|
|
||||||
|
/** What a right-click in the conversation was on. */
|
||||||
|
export type ConversationTarget =
|
||||||
|
| { readonly kind: "message"; readonly messageId: string; readonly role: "user" | "assistant" | "system"; readonly text: string }
|
||||||
|
| { readonly kind: "command"; readonly command: string; readonly output: string };
|
||||||
|
|
||||||
|
export interface ConversationMouse {
|
||||||
|
readonly respond: (decision: ProviderApprovalDecision) => void;
|
||||||
|
/** A click on a prompt: the turn cursor, as [ and ] move it. */
|
||||||
|
readonly selectTurn: (messageId: string) => void;
|
||||||
|
/** A click on a folded turn or work group: its own expansion, apart from e. */
|
||||||
|
readonly toggleFold: (id: string) => void;
|
||||||
|
readonly loadEarlier: () => void;
|
||||||
|
readonly menu: (target: ConversationTarget) => void;
|
||||||
|
}
|
||||||
|
|
||||||
/** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */
|
/** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */
|
||||||
export function ThreadView(props: {
|
export function ThreadView(props: {
|
||||||
readonly project: string;
|
readonly project: string;
|
||||||
@@ -35,6 +51,8 @@ export function ThreadView(props: {
|
|||||||
readonly parent?: { readonly title: string; readonly threadId: ThreadId } | undefined;
|
readonly parent?: { readonly title: string; readonly threadId: ThreadId } | undefined;
|
||||||
/** Opens another thread: a subagent from its work row, or the parent from the header. Keep it stable; rows are memoized on it. */
|
/** Opens another thread: a subagent from its work row, or the parent from the header. Keep it stable; rows are memoized on it. */
|
||||||
readonly onOpenThread: (threadId: ThreadId) => void;
|
readonly onOpenThread: (threadId: ThreadId) => void;
|
||||||
|
/** The mouse in the conversation. Keep these stable too. */
|
||||||
|
readonly mouse: ConversationMouse;
|
||||||
}) {
|
}) {
|
||||||
const { timeline, history } = props;
|
const { timeline, history } = props;
|
||||||
const pendingIds = new Set<string>(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []);
|
const pendingIds = new Set<string>(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []);
|
||||||
@@ -56,7 +74,7 @@ export function ThreadView(props: {
|
|||||||
{props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null}
|
{props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null}
|
||||||
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
|
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
|
||||||
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
|
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
|
||||||
{history?.hasMore || history?.error ? <LoadEarlier history={history} /> : null}
|
{history?.hasMore || history?.error ? <LoadEarlier history={history} onLoad={props.mouse.loadEarlier} /> : null}
|
||||||
{timeline?.rows.map((row) => (
|
{timeline?.rows.map((row) => (
|
||||||
<Row
|
<Row
|
||||||
key={row.id}
|
key={row.id}
|
||||||
@@ -72,6 +90,7 @@ export function ThreadView(props: {
|
|||||||
now={row.kind === "working" ? props.now : 0}
|
now={row.kind === "working" ? props.now : 0}
|
||||||
workStartedAt={timeline.workStartedAt}
|
workStartedAt={timeline.workStartedAt}
|
||||||
onOpenThread={props.onOpenThread}
|
onOpenThread={props.onOpenThread}
|
||||||
|
mouse={props.mouse}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</scrollbox>
|
</scrollbox>
|
||||||
@@ -79,16 +98,17 @@ export function ThreadView(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function LoadEarlier({ history }: { readonly history: ThreadHistory }) {
|
function LoadEarlier({ history, onLoad }: { readonly history: ThreadHistory; readonly onLoad: () => void }) {
|
||||||
const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)";
|
const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)";
|
||||||
return <Divider label={label} color={history.error ? colors.bad : colors.faint} />;
|
return <Divider label={label} color={history.error ? colors.bad : colors.accent} onPress={history.loading ? undefined : onLoad} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function Divider({ label, color }: { readonly label: string; readonly color: string }) {
|
function Divider({ label, color, onPress }: { readonly label: string; readonly color: string; readonly onPress?: (() => void) | undefined }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
return (
|
return (
|
||||||
<box flexDirection="row" marginTop={1}>
|
<box flexDirection="row" marginTop={1} {...(onPress ? { ...hoverProps, onMouseDown: (event: MouseEvent) => isLeftClick(event) && onPress() } : {})}>
|
||||||
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
|
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
|
||||||
<text fg={color}>{` ${label} `}</text>
|
<text fg={onPress && hover ? colors.text : color} selectable={!onPress}>{` ${label} `}</text>
|
||||||
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
|
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
@@ -112,8 +132,9 @@ const Row = memo(function Row(props: {
|
|||||||
readonly now: number;
|
readonly now: number;
|
||||||
readonly workStartedAt: string | null;
|
readonly workStartedAt: string | null;
|
||||||
readonly onOpenThread: (threadId: ThreadId) => void;
|
readonly onOpenThread: (threadId: ThreadId) => void;
|
||||||
|
readonly mouse: ConversationMouse;
|
||||||
}) {
|
}) {
|
||||||
const { row, workspaceRoot } = props;
|
const { row, workspaceRoot, mouse } = props;
|
||||||
switch (row.kind) {
|
switch (row.kind) {
|
||||||
case "message": {
|
case "message": {
|
||||||
const { message } = row;
|
const { message } = row;
|
||||||
@@ -121,10 +142,11 @@ const Row = memo(function Row(props: {
|
|||||||
const segments = findTextSegments(message.text, message.role === "user");
|
const segments = findTextSegments(message.text, message.role === "user");
|
||||||
if (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
|
if (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
|
||||||
}
|
}
|
||||||
if (message.role === "user") return <UserMessage text={message.text} messageId={message.id} selected={props.selected} />;
|
const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text } as const;
|
||||||
if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>;
|
if (message.role === "user") return <UserMessage text={message.text} messageId={message.id} selected={props.selected} onSelect={() => mouse.selectTurn(message.id)} onMenu={() => mouse.menu(menu)} />;
|
||||||
|
if (message.role === "system") return <text marginTop={1} fg={colors.muted} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>{message.text}</text>;
|
||||||
return (
|
return (
|
||||||
<box marginTop={1}>
|
<box marginTop={1} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>
|
||||||
<markdown content={message.text || "…"} syntaxStyle={getMarkdownStyle()} streaming={message.streaming} conceal />
|
<markdown content={message.text || "…"} syntaxStyle={getMarkdownStyle()} streaming={message.streaming} conceal />
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
@@ -133,21 +155,21 @@ const Row = memo(function Row(props: {
|
|||||||
case "attempt-fold":
|
case "attempt-fold":
|
||||||
// The finished turn's work, folded: the web's turn separator.
|
// The finished turn's work, folded: the web's turn separator.
|
||||||
return (
|
return (
|
||||||
<box marginTop={1} border={["bottom"]} borderColor={colors.border} flexDirection="row">
|
<Toggle onPress={() => mouse.toggleFold(row.kind === "turn-fold" ? row.runId : row.attemptId)} border>
|
||||||
<text fg={colors.muted}>{`${row.label} ${row.expanded ? "⌄" : "›"}`}</text>
|
{(hover) => <text fg={hover ? colors.text : colors.muted} selectable={false}>{`${row.label} ${row.expanded ? "⌄" : "›"}`}</text>}
|
||||||
</box>
|
</Toggle>
|
||||||
);
|
);
|
||||||
case "work-toggle":
|
case "work-toggle":
|
||||||
return (
|
return (
|
||||||
<box marginTop={1} flexDirection="row">
|
<Toggle onPress={() => mouse.toggleFold(row.groupId)}>
|
||||||
<text fg={row.hasFailure ? colors.bad : colors.muted}>{`${SUMMARY_GLYPH[row.summaryKind] ?? "•"} ${row.summary} ${row.expanded ? "⌄" : "›"}`}</text>
|
{(hover) => <text fg={row.hasFailure ? colors.bad : hover ? colors.text : colors.muted} selectable={false}>{`${SUMMARY_GLYPH[row.summaryKind] ?? "•"} ${row.summary} ${row.expanded ? "⌄" : "›"}`}</text>}
|
||||||
</box>
|
</Toggle>
|
||||||
);
|
);
|
||||||
case "work":
|
case "work":
|
||||||
return (
|
return (
|
||||||
<box marginTop={row.continuesWorkLog ? 0 : 1} flexDirection="column">
|
<box marginTop={row.continuesWorkLog ? 0 : 1} flexDirection="column">
|
||||||
{row.groupedEntries.map((entry) => (
|
{row.groupedEntries.map((entry) => (
|
||||||
<WorkEntry key={entry.id} entry={entry} expanded={row.isExpandedToolGroup} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} onOpenThread={props.onOpenThread} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
|
<WorkEntry key={entry.id} entry={entry} expanded={row.isExpandedToolGroup} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} onOpenThread={props.onOpenThread} onMenu={mouse.menu} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
|
||||||
))}
|
))}
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
@@ -155,7 +177,7 @@ const Row = memo(function Row(props: {
|
|||||||
return (
|
return (
|
||||||
<box marginTop={1} flexDirection="column">
|
<box marginTop={1} flexDirection="column">
|
||||||
{row.thought?.detail ? <text fg={colors.faint}>{`∴ ${liveThoughtLine(row.thought.detail)}`}</text> : null}
|
{row.thought?.detail ? <text fg={colors.faint}>{`∴ ${liveThoughtLine(row.thought.detail)}`}</text> : null}
|
||||||
<WorkEntry entry={row.entry} expanded={row.expanded} label={liveWorkEntryLabel(row.entry, workspaceRoot, row.active)} onOpenThread={props.onOpenThread} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
|
<WorkEntry entry={row.entry} expanded={row.expanded} label={liveWorkEntryLabel(row.entry, workspaceRoot, row.active)} onOpenThread={props.onOpenThread} onMenu={mouse.menu} session={props.session} streamCommandOutput={props.streamCommandOutput} scrollRef={props.scrollRef} />
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
case "working": {
|
case "working": {
|
||||||
@@ -178,7 +200,7 @@ const Row = memo(function Row(props: {
|
|||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
case "event":
|
case "event":
|
||||||
return <EventRow item={row.projectedItem.item} pending={props.pending} />;
|
return <EventRow item={row.projectedItem.item} pending={props.pending} onRespond={mouse.respond} />;
|
||||||
case "worktree-setup":
|
case "worktree-setup":
|
||||||
return <text marginTop={1} fg={colors.info}>◐ Setting up worktree…</text>;
|
return <text marginTop={1} fg={colors.info}>◐ Setting up worktree…</text>;
|
||||||
default:
|
default:
|
||||||
@@ -191,22 +213,24 @@ const USER_FOLD_LINES = 8;
|
|||||||
const USER_FOLD_CHARS = 600;
|
const USER_FOLD_CHARS = 600;
|
||||||
|
|
||||||
/** The web's user bubble: right-aligned, at most 80% wide, folded past 8 lines or 600 characters. */
|
/** The web's user bubble: right-aligned, at most 80% wide, folded past 8 lines or 600 characters. */
|
||||||
function UserMessage({ text, messageId, selected }: { readonly text: string; readonly messageId: string; readonly selected: boolean }) {
|
function UserMessage({ text, messageId, selected, onSelect, onMenu }: { readonly text: string; readonly messageId: string; readonly selected: boolean; readonly onSelect: () => void; readonly onMenu: () => void }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
const trimmed = text.trim();
|
const trimmed = text.trim();
|
||||||
const lines = trimmed.split("\n");
|
const lines = trimmed.split("\n");
|
||||||
let shown = lines.slice(0, USER_FOLD_LINES).join("\n");
|
let shown = lines.slice(0, USER_FOLD_LINES).join("\n");
|
||||||
if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`;
|
if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`;
|
||||||
const folded = shown.length < trimmed.length;
|
const folded = shown.length < trimmed.length;
|
||||||
return (
|
return (
|
||||||
<box id={`turn-${messageId}`} border={selected ? ["left"] : []} borderColor={colors.accent} marginTop={1} alignSelf="flex-end" maxWidth="80%" backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
|
<box id={`turn-${messageId}`} border={selected ? ["left"] : []} borderColor={colors.accent} marginTop={1} alignSelf="flex-end" maxWidth="80%" backgroundColor={hover && !selected ? colors.selectedBg : colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu() : isLeftClick(event) ? onSelect() : undefined)}>
|
||||||
<text fg={colors.text}>{shown}</text>
|
<text fg={colors.text}>{shown}</text>
|
||||||
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
|
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
|
function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly onMenu: (target: ConversationTarget) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
|
||||||
const [open, setExpanded] = useState<boolean | null>(null);
|
const [open, setExpanded] = useState<boolean | null>(null);
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
const expanded = open ?? groupExpanded;
|
const expanded = open ?? groupExpanded;
|
||||||
const item = entry.structuredPayload;
|
const item = entry.structuredPayload;
|
||||||
const command = item?.type === "command_execution" ? item : null;
|
const command = item?.type === "command_execution" ? item : null;
|
||||||
@@ -214,13 +238,14 @@ function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, sessio
|
|||||||
const failed = workEntryDisplayIndicatesToolFailure(entry);
|
const failed = workEntryDisplayIndicatesToolFailure(entry);
|
||||||
const child = childThreadOf(entry);
|
const child = childThreadOf(entry);
|
||||||
const tone = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : entry.tone === "thinking" ? colors.faint : colors.muted;
|
const tone = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : entry.tone === "thinking" ? colors.faint : colors.muted;
|
||||||
const text = <text fg={tone}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}</text>;
|
const clickable = Boolean(command || child);
|
||||||
|
const text = <text fg={clickable && hover ? colors.text : tone} selectable={!clickable}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}</text>;
|
||||||
if (command) return <box flexDirection="column">
|
if (command) return <box flexDirection="column">
|
||||||
<box flexDirection="row" onMouseDown={() => setExpanded(!expanded)}><text fg={colors.faint}>{expanded ? "⌄ " : "› "}</text>{text}</box>
|
<box flexDirection="row" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu({ kind: "command", command: command.input, output: command.output ?? "" }) : isLeftClick(event) ? setExpanded(!expanded) : undefined)}><text fg={colors.faint} selectable={false}>{expanded ? "⌄ " : "› "}</text>{text}</box>
|
||||||
{expanded && streamCommandOutput && projected ? <CommandOutput session={session} threadId={projected.sourceThreadId} itemId={projected.sourceItemId} scrollRef={scrollRef} />
|
{expanded && streamCommandOutput && projected ? <CommandOutput session={session} threadId={projected.sourceThreadId} itemId={projected.sourceItemId} scrollRef={scrollRef} />
|
||||||
: expanded ? <text fg={colors.muted}>{command.output || "No output."}</text> : null}
|
: expanded ? <text fg={colors.muted}>{command.output || "No output."}</text> : null}
|
||||||
</box>;
|
</box>;
|
||||||
return child ? <box onMouseDown={() => onOpenThread(child)}>{text}</box> : text;
|
return child ? <box {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && onOpenThread(child)}>{text}</box> : text;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The thread a subagent work row ran in, when it has its own. */
|
/** The thread a subagent work row ran in, when it has its own. */
|
||||||
@@ -229,7 +254,7 @@ export function childThreadOf(entry: WorkLogEntry): ThreadId | null {
|
|||||||
return item?.type === "subagent" ? (item.childThreadId ?? null) : null;
|
return item?.type === "subagent" ? (item.childThreadId ?? null) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) {
|
function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision: ProviderApprovalDecision) => void; readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) {
|
||||||
if (item.type === "approval_request" && pending) {
|
if (item.type === "approval_request" && pending) {
|
||||||
return (
|
return (
|
||||||
<box marginTop={1} border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" paddingLeft={1} paddingRight={1}>
|
<box marginTop={1} border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" paddingLeft={1} paddingRight={1}>
|
||||||
@@ -238,7 +263,11 @@ function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extend
|
|||||||
</text>
|
</text>
|
||||||
{item.prompt ? <text fg={colors.text}>{item.prompt}</text> : null}
|
{item.prompt ? <text fg={colors.text}>{item.prompt}</text> : null}
|
||||||
{item.reason ? <text fg={colors.muted}>{item.reason}</text> : null}
|
{item.reason ? <text fg={colors.muted}>{item.reason}</text> : null}
|
||||||
<text fg={colors.faint}>Waiting for approval · y Approve · Y Always allow this session · n Decline</text>
|
<Buttons>
|
||||||
|
<Button label="Approve" shortcut="y" color={colors.good} onPress={() => onRespond("accept")} />
|
||||||
|
<Button label="Always allow this session" shortcut="Y" onPress={() => onRespond("acceptForSession")} />
|
||||||
|
<Button label="Decline" shortcut="n" color={colors.bad} onPress={() => onRespond("decline")} />
|
||||||
|
</Buttons>
|
||||||
</box>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -272,6 +301,16 @@ function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): s
|
|||||||
return item.type === "approval_request" ? item.requestId : undefined;
|
return item.type === "approval_request" ? item.requestId : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A folded turn or work group: a click opens or closes just this one. */
|
||||||
|
function Toggle({ onPress, border, children }: { readonly onPress: () => void; readonly border?: boolean; readonly children: (hover: boolean) => React.ReactNode }) {
|
||||||
|
const [hover, hoverProps] = useHover();
|
||||||
|
return (
|
||||||
|
<box marginTop={1} flexDirection="row" {...(border ? { border: ["bottom"] as const, borderColor: colors.border } : {})} {...hoverProps} onMouseDown={(event: MouseEvent) => isLeftClick(event) && onPress()}>
|
||||||
|
{children(hover)}
|
||||||
|
</box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Terminal stand-ins for the web's lucide icons. */
|
/** Terminal stand-ins for the web's lucide icons. */
|
||||||
const SUMMARY_GLYPH: Partial<Record<ToolGroupSummaryKind, string>> = {
|
const SUMMARY_GLYPH: Partial<Record<ToolGroupSummaryKind, string>> = {
|
||||||
read: "◉",
|
read: "◉",
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ export const colors = {
|
|||||||
bad: "#f7768e",
|
bad: "#f7768e",
|
||||||
warn: "#e0af68",
|
warn: "#e0af68",
|
||||||
selectedBg: "#283457",
|
selectedBg: "#283457",
|
||||||
|
/** Under the pointer: lighter than the panel, quieter than a selection. */
|
||||||
|
hoverBg: "#202437",
|
||||||
|
buttonBg: "#24283b",
|
||||||
/** The web app's sky / indigo / violet status hues. */
|
/** The web app's sky / indigo / violet status hues. */
|
||||||
info: "#7dcfff",
|
info: "#7dcfff",
|
||||||
input: "#bb9af7",
|
input: "#bb9af7",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export interface Attachments {
|
|||||||
readonly commands: readonly (PaletteCommand & { readonly run: () => void })[];
|
readonly commands: readonly (PaletteCommand & { readonly run: () => void })[];
|
||||||
/** Prompts for a path and uploads it; the `a` key and the palette both call this. */
|
/** Prompts for a path and uploads it; the `a` key and the palette both call this. */
|
||||||
readonly attachFile: () => void;
|
readonly attachFile: () => void;
|
||||||
|
readonly remove: (attachment: ChatAttachment) => void;
|
||||||
/** Hands the pending attachments to a send and clears them. */
|
/** Hands the pending attachments to a send and clears them. */
|
||||||
readonly take: () => readonly ChatAttachment[];
|
readonly take: () => readonly ChatAttachment[];
|
||||||
}
|
}
|
||||||
@@ -113,6 +114,7 @@ export function useAttachments(deps: {
|
|||||||
line: attachmentLine(pending),
|
line: attachmentLine(pending),
|
||||||
commands,
|
commands,
|
||||||
attachFile,
|
attachFile,
|
||||||
|
remove,
|
||||||
take: () => {
|
take: () => {
|
||||||
const taken = byComposer.get(composerKey) ?? [];
|
const taken = byComposer.get(composerKey) ?? [];
|
||||||
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, []));
|
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, []));
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ export function useDiffContext(session: T3Session, diff: DiffState | null, scrol
|
|||||||
const [selected, setSelected] = useState(0);
|
const [selected, setSelected] = useState(0);
|
||||||
const [expanded, setExpanded] = useState<Record<string, { patch?: string; error?: string }>>({});
|
const [expanded, setExpanded] = useState<Record<string, { patch?: string; error?: string }>>({});
|
||||||
useEffect(() => { setSelected(0); setExpanded({}); }, [diff]);
|
useEffect(() => { setSelected(0); setExpanded({}); }, [diff]);
|
||||||
const expand = () => {
|
const expand = (index = selected) => {
|
||||||
const file = files[selected];
|
const file = files[index];
|
||||||
if (!file || !diff?.source) return;
|
if (!file || !diff?.source) return;
|
||||||
if (expanded[file.path]?.patch) {
|
if (expanded[file.path]?.patch) {
|
||||||
setExpanded((old) => { const next = { ...old }; delete next[file.path]; return next; });
|
setExpanded((old) => { const next = { ...old }; delete next[file.path]; return next; });
|
||||||
@@ -41,5 +41,10 @@ export function useDiffContext(session: T3Session, diff: DiffState | null, scrol
|
|||||||
if (key.name === "x" || key.name === "return") { expand(); return true; }
|
if (key.name === "x" || key.name === "return") { expand(); return true; }
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
return { selected, expanded, onKey, move, expand };
|
/** A click on a file's header: select it, and a second click opens its whole file. */
|
||||||
|
const click = (index: number) => {
|
||||||
|
if (index === selected) return expand(index);
|
||||||
|
setSelected(index);
|
||||||
|
};
|
||||||
|
return { selected, expanded, onKey, move, expand, click };
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { useCallback, useRef } from "react";
|
||||||
|
|
||||||
|
/** A callback that keeps one identity across renders but always runs the latest closure, for memoized rows. */
|
||||||
|
export function useEvent<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
|
||||||
|
const ref = useRef(fn);
|
||||||
|
ref.current = fn;
|
||||||
|
return useCallback((...args: A) => ref.current(...args), []);
|
||||||
|
}
|
||||||
+13
-1
@@ -152,5 +152,17 @@ export function useQueue(input: {
|
|||||||
|
|
||||||
const placeholder = editing ? "Edit the queued message (enter saves, esc cancels)" : canResume ? (queue?.resumableRunId ? "Ask anything, or press enter to continue where it left off" : "Ask anything, or press enter to send the held messages") : null;
|
const placeholder = editing ? "Edit the queued message (enter saves, esc cancels)" : canResume ? (queue?.resumableRunId ? "Ask anything, or press enter to continue where it left off" : "Ask anything, or press enter to send the held messages") : null;
|
||||||
|
|
||||||
return { queue, queued, focus, focused: focus !== null, editingRunId: editing?.runId ?? null, editing: editing !== null, key, submit, commands, placeholder };
|
const at = (index: number, action: (message: QueuedMessage) => void) => () => {
|
||||||
|
const message = queued[index];
|
||||||
|
if (message) action(message);
|
||||||
|
};
|
||||||
|
const actions = {
|
||||||
|
focus: (index: number) => setFocus(index),
|
||||||
|
sendNow: (index: number) => at(index, sendNow)(),
|
||||||
|
edit: (index: number) => at(index, beginEdit)(),
|
||||||
|
remove: (index: number) => at(index, remove)(),
|
||||||
|
resume: canResume ? resume : null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { queue, queued, focus, focused: focus !== null, editingRunId: editing?.runId ?? null, editing: editing !== null, key, submit, commands, placeholder, actions };
|
||||||
}
|
}
|
||||||
@@ -67,5 +67,11 @@ export function useSecretRequest(input: { readonly session: T3Session; readonly
|
|||||||
]
|
]
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
return { request, value, error, busy, focused: value !== null, key, commands };
|
const actions = {
|
||||||
|
focus: () => setValue(""),
|
||||||
|
cancel: () => setValue(null),
|
||||||
|
save: () => value !== null && answer({ type: "save", secret: value }),
|
||||||
|
decline: () => answer({ type: "decline" }),
|
||||||
|
};
|
||||||
|
return { request, value, error, busy, focused: value !== null, key, commands, actions };
|
||||||
}
|
}
|
||||||
+26
-8
@@ -46,10 +46,14 @@ export function useTurns(input: {
|
|||||||
setCursor({ threadId: input.threadId, messageId: next.messageId });
|
setCursor({ threadId: input.threadId, messageId: next.messageId });
|
||||||
setTimeout(() => input.scrollRef.current?.scrollChildIntoView(`turn-${next.messageId}`), 0);
|
setTimeout(() => input.scrollRef.current?.scrollChildIntoView(`turn-${next.messageId}`), 0);
|
||||||
};
|
};
|
||||||
const openDiff = (fullThread: boolean) => {
|
/** A click or right-click on a prompt points the cursor at it without scrolling away. */
|
||||||
|
const select = (messageId: string) => {
|
||||||
|
if (input.threadId && turns.some((turn) => turn.messageId === messageId)) setCursor({ threadId: input.threadId, messageId });
|
||||||
|
};
|
||||||
|
const openDiff = (fullThread: boolean, messageId = selectedMessageId) => {
|
||||||
const checkpoint = fullThread
|
const checkpoint = fullThread
|
||||||
? turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint?.status === "ready").sort((a, b) => b.checkpointTurnCount - a.checkpointTurnCount)[0]
|
? turns.map((turn) => turn.checkpoint).filter((checkpoint): checkpoint is TurnCheckpoint => checkpoint?.status === "ready").sort((a, b) => b.checkpointTurnCount - a.checkpointTurnCount)[0]
|
||||||
: diffTurn(turns, selectedMessageId);
|
: diffTurn(turns, messageId);
|
||||||
if (!input.threadId || !input.cwd || !checkpoint) return input.say("No changes from this turn.");
|
if (!input.threadId || !input.cwd || !checkpoint) return input.say("No changes from this turn.");
|
||||||
const toTurnCount = checkpoint.checkpointTurnCount;
|
const toTurnCount = checkpoint.checkpointTurnCount;
|
||||||
const state: DiffState = { cwd: input.cwd, path: null, title: fullThread ? "Changes" : `Turn ${toTurnCount}`, status: "loading" };
|
const state: DiffState = { cwd: input.cwd, path: null, title: fullThread ? "Changes" : `Turn ${toTurnCount}`, status: "loading" };
|
||||||
@@ -62,16 +66,16 @@ export function useTurns(input: {
|
|||||||
(error) => input.setDiff((current) => current === state ? { ...state, status: "error", error: messageOf(error) } : current),
|
(error) => input.setDiff((current) => current === state ? { ...state, status: "error", error: messageOf(error) } : current),
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
const revert = (restoreFiles = false) => {
|
const revert = (restoreFiles = false, target = selected) => {
|
||||||
const projection = input.projection;
|
const projection = input.projection;
|
||||||
if (!selected || !projection || reverting) return input.say("Select a turn with [ or ] first.");
|
if (!target || !projection || reverting) return input.say("Select a turn with [ or ] first.");
|
||||||
const provider = input.config?.providers.find((provider) => provider.instanceId === projection.thread.providerInstanceId);
|
const provider = input.config?.providers.find((provider) => provider.instanceId === projection.thread.providerInstanceId);
|
||||||
if (!provider || provider.supportsConversationRollback === false) return input.say("This provider does not support reverting conversation history. Start a new thread instead.", true);
|
if (!provider || provider.supportsConversationRollback === false) return input.say("This provider does not support reverting conversation history. Start a new thread instead.", true);
|
||||||
if (input.timeline?.isWorking) return input.say("Interrupt the current turn before reverting checkpoints.", true);
|
if (input.timeline?.isWorking) return input.say("Interrupt the current turn before reverting checkpoints.", true);
|
||||||
const turnCount = selected.revertTurnCount;
|
const turnCount = target.revertTurnCount;
|
||||||
const checkpoint = turnCount === undefined ? undefined : findRevertCheckpoint(projection.checkpoints, turnCount);
|
const checkpoint = turnCount === undefined ? undefined : findRevertCheckpoint(projection.checkpoints, turnCount);
|
||||||
if (turnCount === undefined || !checkpoint) return input.say("This message has no available checkpoint to rewind to.", true);
|
if (turnCount === undefined || !checkpoint) return input.say("This message has no available checkpoint to rewind to.", true);
|
||||||
if (selected.hasAttachments) return input.say("Use the T3 Code app to rewind a message with attachments.", true);
|
if (target.hasAttachments) return input.say("Use the T3 Code app to rewind a message with attachments.", true);
|
||||||
input.confirm({
|
input.confirm({
|
||||||
title: "Edit from here?",
|
title: "Edit from here?",
|
||||||
detail: "Rewind chat to before this message. Your prompt returns to the composer. “Revert files too” also undoes your own edits.",
|
detail: "Rewind chat to before this message. Your prompt returns to the composer. “Revert files too” also undoes your own edits.",
|
||||||
@@ -79,7 +83,7 @@ export function useTurns(input: {
|
|||||||
run: () => {
|
run: () => {
|
||||||
setReverting(true);
|
setReverting(true);
|
||||||
input.session.rewind(projection, checkpoint, turnCount, restoreFiles).then(() => {
|
input.session.rewind(projection, checkpoint, turnCount, restoreFiles).then(() => {
|
||||||
input.restorePrompt(projection.thread.id, recallableComposerPrompt(selected.text));
|
input.restorePrompt(projection.thread.id, recallableComposerPrompt(target.text));
|
||||||
if (currentThread.current === projection.thread.id) { setCursor(null); input.setDiff(null); }
|
if (currentThread.current === projection.thread.id) { setCursor(null); input.setDiff(null); }
|
||||||
input.say("Thread rewound");
|
input.say("Thread rewound");
|
||||||
}, (error) => input.say(`Could not rewind: ${messageOf(error)}`, true)).finally(() => setReverting(false));
|
}, (error) => input.say(`Could not rewind: ${messageOf(error)}`, true)).finally(() => setReverting(false));
|
||||||
@@ -113,7 +117,21 @@ export function useTurns(input: {
|
|||||||
if (key.name === "escape" && !input.diff && selectedMessageId) { setCursor(null); return true; }
|
if (key.name === "escape" && !input.diff && selectedMessageId) { setCursor(null); return true; }
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
return { selectedMessageId, commands, onKey, diffContext };
|
/** The prompt's right-click menu. */
|
||||||
|
const menuFor = (messageId: string) => {
|
||||||
|
const turn = turns.find((candidate) => candidate.messageId === messageId);
|
||||||
|
if (!turn) return [];
|
||||||
|
const run = (action: () => void) => () => { select(messageId); action(); };
|
||||||
|
return [
|
||||||
|
{ id: "turn-select", title: "Select this turn", hint: "[ ]", run: run(() => undefined) },
|
||||||
|
{ id: "turn-diff", title: "View changes from this turn", hint: "D", run: run(() => openDiff(false, messageId)) },
|
||||||
|
...(turn.revertTurnCount !== undefined ? [
|
||||||
|
{ id: "turn-revert", title: "Revert to before this prompt…", hint: "R", run: run(() => revert(false, turn)) },
|
||||||
|
{ id: "turn-revert-files", title: "Revert files too…", run: run(() => revert(true, turn)) },
|
||||||
|
] : []),
|
||||||
|
];
|
||||||
|
};
|
||||||
|
return { selectedMessageId, commands, onKey, diffContext, select, menuFor };
|
||||||
}
|
}
|
||||||
|
|
||||||
function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); }
|
function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); }
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
|
||||||
|
import { hintKey } from "../src/model/hints.ts";
|
||||||
|
|
||||||
|
describe("clickable key hints", () => {
|
||||||
|
test("single keys, shifted keys and ctrl chords", () => {
|
||||||
|
expect(hintKey("y approve", "nav")).toEqual({ name: "y", sequence: "y", shift: false, ctrl: false });
|
||||||
|
expect(hintKey("Y always", "nav")).toEqual({ name: "y", sequence: "Y", shift: true, ctrl: false });
|
||||||
|
expect(hintKey("ctrl+k commands", "nav")).toEqual({ name: "k", sequence: "\x0b", shift: false, ctrl: true });
|
||||||
|
expect(hintKey("esc close", "palette")?.name).toBe("escape");
|
||||||
|
expect(hintKey(". actions", "nav")?.name).toBe(".");
|
||||||
|
expect(hintKey("/ filter", "nav")?.name).toBe("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("choices of keys, ranges and sending chords stay text", () => {
|
||||||
|
expect(hintKey("j/k threads", "nav")).toBeNull();
|
||||||
|
expect(hintKey("ctrl+n/p thread", "input")).toBeNull();
|
||||||
|
expect(hintKey("1-9 pick", "nav")).toBeNull();
|
||||||
|
expect(hintKey("alt+enter steer", "input")).toBeNull();
|
||||||
|
expect(hintKey("alt+↑ edit queued", "input")).toBeNull();
|
||||||
|
expect(hintKey("shift+enter or \\ newline", "input")).toBeNull();
|
||||||
|
expect(hintKey("enter send", "input")).toBeNull();
|
||||||
|
expect(hintKey("enter confirm", "confirm")?.name).toBe("return");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user