Merge features-08: terminal and editor pane, images, split diffs, selection, links, terminal themes, composer chips
This commit is contained in:
commit
b6470966cf
40 files changed
+1845
-204
No files matched your search
+8
-3
@@ -173,9 +173,14 @@ async function runUi(attachNeedle?: string) {
|
||||
setInterval(() => {
|
||||
if (Date.now() - lastInput > 5_000) Bun.gc(true);
|
||||
}, 30_000).unref();
|
||||
const { applyTheme } = await import("./ui/theme.ts");
|
||||
// Terminals that don't say what their background is get the dark palette.
|
||||
applyTheme(config.theme === "auto" ? ((await renderer.waitForThemeMode(300)) ?? "dark") : config.theme);
|
||||
const { applyTheme, terminalPalette, themeModeOf } = await import("./ui/theme.ts");
|
||||
if (config.theme === "dark" || config.theme === "light") applyTheme(config.theme);
|
||||
else {
|
||||
// The terminal's colours through OSC 4, 10 and 11; terminals that don't answer get the dark palette.
|
||||
const detected = await renderer.getPalette({ timeout: 300, size: 16 }).catch(() => null);
|
||||
const mode = themeModeOf(detected) ?? renderer.themeMode ?? "dark";
|
||||
applyTheme(config.theme === "terminal" ? (terminalPalette(detected) ?? mode) : mode);
|
||||
}
|
||||
createRoot(renderer).render(createElement(App, { session, config, layout, ...(attachThreadId ? { attachThreadId } : {}) }));
|
||||
}
|
||||
|
||||
|
||||
@@ -200,6 +200,7 @@ export class T3Session {
|
||||
private readonly shellListeners = new Set<Listener<ShellState>>();
|
||||
private readonly threads = new Map<ThreadId, ThreadEntry>();
|
||||
private readonly feeds = new Map<string, FeedEntry>();
|
||||
private readonly attachmentImages = new Map<string, Promise<Uint8Array>>();
|
||||
|
||||
async start(): Promise<void> {
|
||||
const scope = Effect.runSync(Scope.make());
|
||||
@@ -477,6 +478,23 @@ export class T3Session {
|
||||
return { type: upload.type === "file" ? "file" : "image", id: minted.attachmentId, name: upload.name, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes } as ChatAttachment;
|
||||
}
|
||||
|
||||
/** A sent image's bytes, fetched once per session through a signed inline URL, as the web shows it. */
|
||||
attachmentImage(attachment: Pick<ChatAttachment, "id" | "name" | "mimeType">): Promise<Uint8Array> {
|
||||
const cached = this.attachmentImages.get(attachment.id);
|
||||
if (cached) return cached;
|
||||
const loading = (async () => {
|
||||
const { rpc, target } = this.requireConnection();
|
||||
const resource = { _tag: "attachment", attachmentId: attachment.id, fileName: attachment.name, mimeType: attachment.mimeType, disposition: "inline" } as const;
|
||||
const minted = await Effect.runPromise(rpc[WS_METHODS.assetsCreateUrl]({ resource }));
|
||||
const response = await fetch(new URL(minted.relativeUrl, target.httpBaseUrl));
|
||||
if (!response.ok) throw new Error(`Image request failed (${response.status})`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
})();
|
||||
this.attachmentImages.set(attachment.id, loading);
|
||||
loading.catch(() => this.attachmentImages.delete(attachment.id));
|
||||
return loading;
|
||||
}
|
||||
|
||||
/** Deletes an unsent upload, as removing it in the web composer does. */
|
||||
deleteAttachment(attachmentId: string): Promise<unknown> {
|
||||
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.attachmentsDelete]({ attachmentId }));
|
||||
|
||||
+3
-3
@@ -18,8 +18,8 @@ export interface T3tuiConfig {
|
||||
readonly notificationMode: "off" | "notifications" | "sound" | "notifications-and-sound";
|
||||
/** As the web's in-app toasts: a line at the bottom for threads you aren't looking at. */
|
||||
readonly inAppNotificationsEnabled: boolean;
|
||||
/** auto follows the terminal's background colour. */
|
||||
readonly theme: "auto" | "dark" | "light";
|
||||
/** auto picks dark or light from the terminal's background; terminal builds the palette from its colours. */
|
||||
readonly theme: "auto" | "dark" | "light" | "terminal";
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG: T3tuiConfig = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true, theme: "auto" };
|
||||
@@ -32,7 +32,7 @@ export const CONFIG_CHOICES: { readonly [K in keyof T3tuiConfig]: readonly T3tui
|
||||
diffIgnoreWhitespace: [true, false],
|
||||
notificationMode: ["off", "sound", "notifications", "notifications-and-sound"],
|
||||
inAppNotificationsEnabled: [true, false],
|
||||
theme: ["auto", "dark", "light"],
|
||||
theme: ["auto", "dark", "light", "terminal"],
|
||||
};
|
||||
|
||||
export const configPath = () => join(configDir(), "config.json");
|
||||
|
||||
@@ -32,16 +32,80 @@ export function expandAttachmentPath(input: string, cwd: string | null): string
|
||||
return isAbsolute(expanded) ? expanded : resolve(cwd ?? process.cwd(), expanded);
|
||||
}
|
||||
|
||||
/** Image types asked of the clipboard, in order of preference; all of them can be sent. */
|
||||
export const CLIPBOARD_IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const;
|
||||
|
||||
/** A platform tool that reads a clipboard image, for when OpenTUI's clipboard service can't. */
|
||||
export interface ClipboardImageTool {
|
||||
/** Lists the clipboard's types, one per line; absent for a tool that reads one fixed type. */
|
||||
readonly types?: readonly string[];
|
||||
readonly read: (mimeType: string) => readonly string[];
|
||||
/** The type a fixed-type tool reads. */
|
||||
readonly mimeType?: string;
|
||||
/** Turns what the tool printed into the image's bytes, when it doesn't print them raw. */
|
||||
readonly decode?: (stdout: Uint8Array) => Uint8Array | null;
|
||||
}
|
||||
|
||||
/** The clipboard readers, in order: the platform's usual image grabber first. */
|
||||
export function clipboardImageCommands(platform: string): readonly (readonly string[])[] {
|
||||
export function clipboardImageCommands(platform: string): readonly ClipboardImageTool[] {
|
||||
return platform === "darwin"
|
||||
? [["pngpaste", "-"]]
|
||||
? [
|
||||
{ read: () => ["pngpaste", "-"], mimeType: "image/png" },
|
||||
{ read: () => ["osascript", "-e", "the clipboard as «class PNGf»"], mimeType: "image/png", decode: decodeAppleScriptData },
|
||||
]
|
||||
: [
|
||||
["wl-paste", "--type", "image/png"],
|
||||
["xclip", "-selection", "clipboard", "-t", "image/png", "-o"],
|
||||
{ types: ["wl-paste", "--list-types"], read: (type) => ["wl-paste", "--type", type] },
|
||||
{ types: ["xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"], read: (type) => ["xclip", "-selection", "clipboard", "-t", type, "-o"] },
|
||||
];
|
||||
}
|
||||
|
||||
/** The image type to ask for among the clipboard's: a preferred one, else any image. */
|
||||
export function pickClipboardImageType(types: readonly string[]): string | null {
|
||||
const offered = types.map((type) => type.trim().toLowerCase());
|
||||
return CLIPBOARD_IMAGE_TYPES.find((type) => offered.includes(type)) ?? offered.find((type) => type.startsWith("image/")) ?? null;
|
||||
}
|
||||
|
||||
/** AppleScript prints clipboard data as `«data PNGf89504E47…»`; this is the bytes. */
|
||||
export function decodeAppleScriptData(stdout: Uint8Array): Uint8Array | null {
|
||||
const hex = /«data \w{4}([0-9A-Fa-f]+)»/.exec(new TextDecoder().decode(stdout))?.[1];
|
||||
return hex ? Uint8Array.from(hex.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16)) : null;
|
||||
}
|
||||
|
||||
/** The file name for a pasted image of this type. */
|
||||
export function pastedImageName(mimeType: string): string {
|
||||
const extension = Object.entries(IMAGE_MIME_BY_EXTENSION).find(([, type]) => type === mimeType)?.[0] ?? "png";
|
||||
return `pasted-image.${extension === "jpeg" ? "jpg" : extension}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The image file a paste names, as terminals paste a dropped file: quoted, as a file://
|
||||
* URL, or with its spaces escaped. Null unless it is one path with an image's extension;
|
||||
* whether the file exists is the caller's to check.
|
||||
*/
|
||||
export function pastedImagePath(text: string, cwd: string | null): string | null {
|
||||
const raw = text.trim().replace(/^(['"])(.*)\1$/s, "$2");
|
||||
if (!raw || raw.includes("\n")) return null;
|
||||
let path: string;
|
||||
if (raw.startsWith("file://")) {
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.hostname && url.hostname !== "localhost") return null;
|
||||
path = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
path = raw.replace(/\\(.)/g, "$1");
|
||||
}
|
||||
if (!path.startsWith("/") && !path.startsWith("~") && !path.startsWith(".")) return null;
|
||||
return imageMimeTypeForName(path) ? expandAttachmentPath(path, cwd) : null;
|
||||
}
|
||||
|
||||
/** Over SSH the clipboard is on the other machine, out of reach of the tools here. */
|
||||
export function isRemoteTerminal(env: Record<string, string | undefined>): boolean {
|
||||
return Boolean(env.SSH_CONNECTION || env.SSH_TTY);
|
||||
}
|
||||
|
||||
export type AttachmentCheck =
|
||||
| { readonly ok: true; readonly upload: AttachmentCreateUploadUrlInput; readonly mimeType: string }
|
||||
| { readonly ok: false; readonly error: string };
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface ComposerItem {
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
readonly replacement: string | null;
|
||||
/** What the composer shows in place of the replacement, as one chip; the replacement is still what's sent. */
|
||||
readonly chip?: string;
|
||||
/** A mention's record (a thread, or a pull request), sent with the message. */
|
||||
readonly record?: ComposerContextRecord;
|
||||
readonly action?: "model";
|
||||
@@ -138,14 +140,19 @@ export function pathItems(entries: readonly ProjectEntry[]): ComposerItem[] {
|
||||
label: `${entry.path.slice(slash + 1)}${entry.kind === "directory" ? "/" : ""}`,
|
||||
description: slash > 0 ? entry.path.slice(0, slash) : "",
|
||||
replacement: `${serializeComposerFileLink(entry.path)} `,
|
||||
chip: `@${entry.path}${entry.kind === "directory" ? "/" : ""}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** The text with the trigger replaced; a trailing space swallows one already there, as the web does. */
|
||||
export function applyComposerItem(text: string, trigger: ComposerTrigger, replacement: string): { text: string; cursor: number } {
|
||||
const end = replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd;
|
||||
return replaceTextRange(text, trigger.rangeStart, end, replacement);
|
||||
return replaceTextRange(text, trigger.rangeStart, composerItemEnd(text, trigger, replacement), replacement);
|
||||
}
|
||||
|
||||
/** Where the text a choice replaces ends: the trigger's range, and a space the replacement brings its own of. */
|
||||
export function composerItemEnd(text: string, trigger: ComposerTrigger, replacement: string): number {
|
||||
return replacement.endsWith(" ") && text[trigger.rangeEnd] === " " ? trigger.rangeEnd + 1 : trigger.rangeEnd;
|
||||
}
|
||||
|
||||
/** The records for the mentions (threads, pull requests) still in the text, as the message's context. */
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/** Characters a file path on screen is made of, with an optional `:line` or `:line:col` after it. */
|
||||
const PATH_CHARS = /[\w.~/@+-]/;
|
||||
|
||||
/**
|
||||
* The file path the text has at `index`, as an agent writes them: `src/ui/App.tsx`,
|
||||
* `./bin.ts:12`, `~/notes.md`. Null for words, URLs and anything else without a folder
|
||||
* or an extension.
|
||||
*/
|
||||
export function pathAt(text: string, index: number): string | null {
|
||||
if (!PATH_CHARS.test(text[index] ?? "")) return null;
|
||||
let start = index;
|
||||
let end = index + 1;
|
||||
while (start > 0 && PATH_CHARS.test(text[start - 1]!)) start--;
|
||||
while (end < text.length && (PATH_CHARS.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
|
||||
if (text[start - 1] === ":" || text.slice(end, end + 3) === "://") return null;
|
||||
const token = text.slice(start, end).replace(/[.,]+$/, "");
|
||||
const path = token.replace(/(:\d+){1,2}$/, "");
|
||||
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/")) return null;
|
||||
return path.includes("/") || /\.[A-Za-z]\w*$/.test(path) ? path : null;
|
||||
}
|
||||
|
||||
/** A link's target is a web page unless it is a bare path. */
|
||||
export function isWebUrl(url: string): boolean {
|
||||
return /^[a-z][a-z\d+.-]*:/i.test(url) && !url.toLowerCase().startsWith("file:");
|
||||
}
|
||||
@@ -21,7 +21,7 @@ const LABELS: { readonly [K in keyof T3tuiConfig]: { readonly label: string; rea
|
||||
values: { off: "off", sound: "bell", notifications: "desktop notifications", "notifications-and-sound": "bell and desktop notifications" },
|
||||
},
|
||||
inAppNotificationsEnabled: { label: "In-app alerts", help: "a line at the bottom for other threads", values: { true: "on", false: "off" } },
|
||||
theme: { label: "Colours", help: "from the next start", values: { auto: "match the terminal", dark: "dark", light: "light" } },
|
||||
theme: { label: "Colours", help: "from the next start", values: { auto: "dark or light, as the terminal is", dark: "dark", light: "light", terminal: "the terminal's own colours" } },
|
||||
};
|
||||
|
||||
/** t3tui's own settings, in display order, each cycled with enter. */
|
||||
|
||||
+171
-49
@@ -1,14 +1,18 @@
|
||||
import type { KeyEvent, MouseEvent, ScrollBoxRenderable, Selection, TextareaRenderable } from "@opentui/core";
|
||||
import { decodePasteBytes, type KeyEvent, type MouseEvent, type PasteEvent, type ScrollBoxRenderable, type Selection, type TextareaRenderable } from "@opentui/core";
|
||||
import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react";
|
||||
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
|
||||
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
|
||||
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
|
||||
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
|
||||
import { createAlerts, type Alert } from "../model/alerts.ts";
|
||||
import { pastedImagePath } from "../model/attachments.ts";
|
||||
import { isWebUrl, pathAt } from "../model/links.ts";
|
||||
import { modelSummary } from "../model/models.ts";
|
||||
import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts";
|
||||
import { saveLayout, type Layout } from "../layout.ts";
|
||||
@@ -31,7 +35,8 @@ import { useDraft } from "./useDraft.ts";
|
||||
import { useModelPicker } from "./useModelPicker.ts";
|
||||
import { useQuestion } from "./useQuestion.ts";
|
||||
import { useThreadMenu } from "./useThreadMenu.ts";
|
||||
import { editInEditor } from "./editor.ts";
|
||||
import { editorCommand, scratchFile } from "./editor.ts";
|
||||
import { TerminalPane, type PaneProgram } from "./TerminalPane.tsx";
|
||||
import { Palette } from "./Palette.tsx";
|
||||
import { ApprovalPanel } from "./ApprovalPanel.tsx";
|
||||
import { LiveStatus } from "./LiveStatus.tsx";
|
||||
@@ -42,8 +47,11 @@ import { PullRequestView } from "./PullRequestView.tsx";
|
||||
import { SettingsView } from "./SettingsView.tsx";
|
||||
import { useWorkspace } from "./useWorkspace.ts";
|
||||
import { usePullRequests } from "./usePullRequests.ts";
|
||||
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
||||
import { colors, statusColor } from "./theme.ts";
|
||||
import { rendererClipboard, type Clipboard } from "./clipboard.ts";
|
||||
import { composerText, useComposerChips } from "./useComposerChips.ts";
|
||||
import { openInBrowser, screenTextAt } from "./links.ts";
|
||||
import { desktopNotify, ring } from "./terminalOut.ts";
|
||||
import { colors, statusColor, useMarkdownStyle } from "./theme.ts";
|
||||
import { BAR, NO_BORDER } from "./edges.ts";
|
||||
import { ThreadList } from "./ThreadList.tsx";
|
||||
import { useTurns } from "./useTurns.ts";
|
||||
@@ -68,9 +76,10 @@ import { useUsageSummary } from "./useUsage.ts";
|
||||
/**
|
||||
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
|
||||
* "details": j/k move through the details panel. "settings": j/k move through settings.
|
||||
* "pane": every key but ctrl+\ goes to the program in the terminal pane.
|
||||
* The rest are overlays with their own input.
|
||||
*/
|
||||
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request";
|
||||
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request" | "pane";
|
||||
|
||||
/** Holding j/k skims past threads; only subscribe to one you stop on. */
|
||||
const SUBSCRIBE_DELAY_MS = 120;
|
||||
@@ -84,6 +93,8 @@ const DETAILS_WIDTH = 38;
|
||||
const MIN_DETAILS_WIDTH = 28;
|
||||
/** Below this, the details panel takes the conversation's place instead of a column beside it. */
|
||||
const MIN_CONVERSATION_WIDTH = 70;
|
||||
/** The conversation this wide or wider shows diffs side by side. */
|
||||
const SPLIT_DIFF_WIDTH = 140;
|
||||
|
||||
const COMPOSER_KEYS = {
|
||||
enter: [
|
||||
@@ -99,10 +110,12 @@ const COMPOSER_KEYS = {
|
||||
/** The composer's key while a new thread is being drafted. */
|
||||
const DRAFT_KEY = "draft";
|
||||
|
||||
export function App(props: { readonly session: T3Session; readonly config: T3tuiConfig; readonly layout?: Layout; readonly attachThreadId?: ThreadId }) {
|
||||
export function App(props: { readonly session: T3Session; readonly config: T3tuiConfig; readonly layout?: Layout; readonly attachThreadId?: ThreadId; readonly clipboard?: Clipboard }) {
|
||||
const { session, attachThreadId } = props;
|
||||
const attached = attachThreadId !== undefined;
|
||||
const renderer = useRenderer();
|
||||
const [clipboard] = useState(() => props.clipboard ?? rendererClipboard(renderer));
|
||||
const markdownStyle = useMarkdownStyle();
|
||||
const { width, height } = useTerminalDimensions();
|
||||
const [shell, setShell] = useState<ShellState>(session.getShell());
|
||||
// Any thread, listed or not: subagents open here too.
|
||||
@@ -111,6 +124,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const [filter, setFilter] = useState("");
|
||||
const [showFolded, setShowFolded] = useState(false);
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
/** Side-by-side diffs, once toggled for the session; null follows the conversation's width. */
|
||||
const [splitDiffPref, setSplitDiffPref] = useState<boolean | null>(null);
|
||||
/** 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 and details column's widths once their edges are dragged; null follows the window. */
|
||||
@@ -134,6 +149,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
/** The edge being dragged. */
|
||||
const [resizing, setResizing] = useState<"list" | "details" | null>(null);
|
||||
const [diff, setDiff] = useState<DiffState | null>(null);
|
||||
/** The program in the right-hand pane: one of T3's terminals, or $EDITOR. */
|
||||
const [pane, setPane] = useState<PaneProgram | null>(null);
|
||||
/** The conversation area's height, for the pane when it takes that place. */
|
||||
const [contentHeight, setContentHeight] = useState(0);
|
||||
const [config, setConfig] = useState(props.config);
|
||||
const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
|
||||
const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null);
|
||||
@@ -341,8 +360,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
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`}`);
|
||||
void clipboard.copy(text).then((copied) => (copied ? say("Copied") : say("Could not reach the clipboard.", true)));
|
||||
});
|
||||
useEffect(() => {
|
||||
renderer.on("selection", copySelection);
|
||||
@@ -411,12 +429,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const attachCwd = draft ? (shell.snapshot?.projects.find((candidate) => candidate.id === draft.projectId)?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null);
|
||||
const attach = useAttachments({
|
||||
session,
|
||||
clipboard,
|
||||
composerKey,
|
||||
cwd: attachCwd,
|
||||
maxFileBytes: serverConfig?.config ? (serverConfig.config.environment.capabilities.fileAttachments?.maxUploadBytes ?? null) : undefined,
|
||||
confirm,
|
||||
say,
|
||||
});
|
||||
const chips = useComposerChips({ composerRef, composerKey, pending: attach.pending, remove: attach.remove });
|
||||
const usage = useUsageSummary(session, settingsIndex !== null && live);
|
||||
const usageInfo = useMemo(() => usageLimits(serverConfig?.config ?? null, now), [serverConfig, now]);
|
||||
const spendResetCredit = (credit: (typeof usageInfo.credits)[number]) =>
|
||||
@@ -459,6 +479,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
say,
|
||||
progress: (text) => setFlash({ text }),
|
||||
openThread,
|
||||
editFile: (path, cwd) => editFile(path, cwd),
|
||||
focus: (focused) => setMode(focused ? "details" : "nav"),
|
||||
});
|
||||
|
||||
@@ -488,7 +509,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const runtimeMode = models.runtimeMode;
|
||||
const threadMenu = useThreadMenu({
|
||||
session,
|
||||
renderer,
|
||||
clipboard,
|
||||
snapshot: shell.snapshot,
|
||||
config: providerConfig,
|
||||
timestampFormat: config.timestampFormat,
|
||||
@@ -513,17 +534,70 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
},
|
||||
});
|
||||
|
||||
const workspace = useWorkspace({ session, renderer, live, thread: threadShell, project, serverConfig: serverConfig?.config ?? null, draft: draft !== null, diff, openPicker, confirm, run, say });
|
||||
/** Puts a program in the pane and gives it the keys. An editor there may hold unsaved work, so it isn't replaced. */
|
||||
const showPane = (program: PaneProgram) => {
|
||||
if (pane?.kind === "local" && pane.id !== program.id) return say("The editor in the pane is still open; ctrl+\\ there and quit it first.", true);
|
||||
setPane(program);
|
||||
setMode("pane");
|
||||
};
|
||||
const closePane = (message?: string) => {
|
||||
setPane(null);
|
||||
setMode((current) => (current === "pane" ? "nav" : current));
|
||||
if (message) say(message);
|
||||
};
|
||||
const workspace = useWorkspace({
|
||||
session,
|
||||
renderer,
|
||||
live,
|
||||
thread: threadShell,
|
||||
project,
|
||||
serverConfig: serverConfig?.config ?? null,
|
||||
draft: draft !== null,
|
||||
diff,
|
||||
openPicker,
|
||||
openPane: (target) => showPane({ kind: "server", id: `server:${target.threadId}:${target.terminalId}`, title: `Terminal · ${target.label}`, target }),
|
||||
confirm,
|
||||
run,
|
||||
say,
|
||||
});
|
||||
|
||||
/** The composer's text in $EDITOR. */
|
||||
const openEditor = async () => {
|
||||
/** The composer's text in $EDITOR, in the pane; what's saved comes back when it exits. */
|
||||
const openEditor = () => {
|
||||
const composer = composerRef.current;
|
||||
if (!composer) return;
|
||||
const edited = await editInEditor(renderer, composer.plainText);
|
||||
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
|
||||
composer.setText(edited);
|
||||
composer.gotoBufferEnd();
|
||||
setMode("input");
|
||||
const key = composerKey;
|
||||
const file = scratchFile(composerText(composer));
|
||||
showPane({
|
||||
kind: "local",
|
||||
id: `message:${file.path}`,
|
||||
title: "Message · save and quit to bring it back",
|
||||
command: editorCommand(file.path),
|
||||
onExit: (code) => {
|
||||
const edited = code === 0 ? file.read() : null;
|
||||
file.remove();
|
||||
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
|
||||
putMessage(key, edited);
|
||||
setMode((current) => (current === "pane" ? "input" : current));
|
||||
},
|
||||
});
|
||||
};
|
||||
/** A workspace file in $EDITOR, in the pane, when the workspace is on this machine. */
|
||||
const editFile = (path: string, cwd: string | null) => {
|
||||
const file = cwd ? resolvePathLinkTarget(path, cwd) : path;
|
||||
if (!existsSync(file)) return say(`${path} isn't on this machine.`, true);
|
||||
showPane({ kind: "local", id: `edit:${file}`, title: `Editing ${path}`, command: editorCommand(file), cwd: cwd ?? undefined, onExit: () => {} });
|
||||
};
|
||||
|
||||
/** A click on a link opens it in the browser; on a path to a workspace file, in the editor pane. A drag doesn't. */
|
||||
const openAt = (x: number, y: number) => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return;
|
||||
const url = renderer.getLinkAt(x, y);
|
||||
if (url && isWebUrl(url)) return openInBrowser(url, (reason) => say(`Could not open the browser (${reason}): ${url}`, true));
|
||||
const shown = url ? null : screenTextAt(renderer, x, y);
|
||||
const raw = url ? (url.startsWith("file:") ? decodeURIComponent(parseFileUrlHref(url)?.path ?? "") : url) : shown && pathAt(shown.text, shown.index);
|
||||
if (!raw || !attachCwd) return;
|
||||
const { path } = splitFilePathPosition(resolvePathLinkTarget(raw, attachCwd));
|
||||
if (existsSync(path) && statSync(path).isFile()) editFile(path, attachCwd);
|
||||
};
|
||||
|
||||
const settingsRows = settingRows(config);
|
||||
@@ -545,6 +619,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
setMode("nav");
|
||||
};
|
||||
|
||||
/** Replaces a composer's text, the open one's or a stored draft's. */
|
||||
const putMessage = (key: string, text: string) => {
|
||||
const composer = composerRef.current;
|
||||
if (key !== activeComposerKey.current || !composer) return void drafts.current.set(key, text);
|
||||
chips.replaceText(composer, text);
|
||||
composer.gotoBufferEnd();
|
||||
setComposerLines(composerLineCount(composer));
|
||||
setComposerEmpty(text.trim() === "");
|
||||
};
|
||||
|
||||
/**
|
||||
* A message that didn't go comes back to its composer, as the web's does: its text, its
|
||||
* attachments and its mentions, unless something new was typed there meanwhile.
|
||||
@@ -552,8 +636,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const restoreMessage = (key: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[]) => {
|
||||
const composer = composerRef.current;
|
||||
if (key === activeComposerKey.current && composer) {
|
||||
if (composer.plainText.trim()) return;
|
||||
composer.setText(text);
|
||||
if (composerText(composer).trim()) return;
|
||||
chips.replaceText(composer, text);
|
||||
composer.gotoBufferEnd();
|
||||
setComposerLines(composerLineCount(composer));
|
||||
setComposerEmpty(text === "");
|
||||
@@ -577,7 +661,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
};
|
||||
|
||||
const clearComposer = () => {
|
||||
composerRef.current?.setText("");
|
||||
if (composerRef.current) chips.replaceText(composerRef.current, "");
|
||||
if (threadId) drafts.current.delete(threadId);
|
||||
composerMenu.forget();
|
||||
setComposerLines(1);
|
||||
@@ -587,11 +671,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
/** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */
|
||||
const submit = (alternate = false) => {
|
||||
const composer = composerRef.current;
|
||||
const raw = composer?.plainText ?? "";
|
||||
const raw = composer ? composerText(composer) : "";
|
||||
// A trailing backslash continues onto a new line, for terminals that can't send shift+enter.
|
||||
if (!alternate && config.sendShortcut === "enter" && composer && raw.endsWith("\\")) {
|
||||
composer.setText(raw.slice(0, -1));
|
||||
composer.gotoBufferEnd();
|
||||
composer.deleteCharBackward();
|
||||
composer.newLine();
|
||||
return;
|
||||
}
|
||||
@@ -646,10 +730,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const turns = useTurns({ session, threadId, projection, timeline: current, config: providerConfig, cwd: panel.cwd, ignoreWhitespace: config.diffIgnoreWhitespace, enabled: draft === null, diff, setDiff, scrollRef, confirm, say,
|
||||
showConversation: () => { setMode("nav"); setDetailsPrefState((value) => (width < MIN_CONVERSATION_WIDTH + DETAILS_WIDTH ? false : value)); },
|
||||
restorePrompt: (id, text) => {
|
||||
const previous = id === activeComposerKey.current ? composerRef.current?.plainText ?? "" : drafts.current.get(id) ?? "";
|
||||
const previous = id === activeComposerKey.current && composerRef.current ? composerText(composerRef.current) : drafts.current.get(id) ?? "";
|
||||
const next = text ? previous ? `${previous}\n\n${text}` : text : previous;
|
||||
drafts.current.set(id, next);
|
||||
if (id === activeComposerKey.current) { composerRef.current?.setText(next); setMode("input"); }
|
||||
if (id === activeComposerKey.current && composerRef.current) { chips.replaceText(composerRef.current, next); setMode("input"); }
|
||||
},
|
||||
});
|
||||
|
||||
@@ -657,6 +741,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const pullRequests = usePullRequests({
|
||||
session,
|
||||
renderer,
|
||||
clipboard,
|
||||
threadShell,
|
||||
project: draft ? draftProject : project,
|
||||
projects: shell.snapshot?.projects ?? [],
|
||||
@@ -724,12 +809,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
const quitKey: Binding = { keys: ["ctrl+c"], run: quit };
|
||||
const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette };
|
||||
const terminalKey: Binding = { keys: ["ctrl+j"], run: workspace.openTerminal };
|
||||
const paneKey: Binding | null = pane && { keys: ["ctrl+\\"], run: () => setMode(mode === "pane" ? "nav" : "pane"), hint: mode === "pane" ? "leave pane" : "pane", command: { id: "pane-focus", title: mode === "pane" ? "Leave the terminal pane" : "Focus the terminal pane", keywords: ["terminal", "editor"] } };
|
||||
const editorKey: Binding | null = hasComposer ? { keys: ["ctrl+g"], run: openEditor, command: { id: "editor", title: "Write the message in $EDITOR", keywords: ["vim", "editor", "compose"] } } : null;
|
||||
const nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) };
|
||||
const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], run: () => move(-1) };
|
||||
// Anywhere with a text field, ctrl+u and ctrl+d edit (delete to line start, delete forward); page up/down still scroll.
|
||||
const lineInput = mode === "filter" || mode === "input" || mode === "find" || mode === "palette" || mode === "picker" || mode === "confirm";
|
||||
const globalKeys = keys(
|
||||
paneKey,
|
||||
quitKey,
|
||||
paletteKey,
|
||||
terminalKey,
|
||||
@@ -795,15 +882,20 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
cancelDraftKey,
|
||||
);
|
||||
// A diff and a draft name their own few keys; everything else names the lot.
|
||||
const navHints = diff
|
||||
? [scrollDiffDown, closeDiff, detailsKey]
|
||||
: draft
|
||||
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey)
|
||||
: navKeys;
|
||||
const navHints = keys(
|
||||
paneKey,
|
||||
diff
|
||||
? [scrollDiffDown, closeDiff, detailsKey]
|
||||
: draft
|
||||
? keys(hinted(typeKey, "write the first message"), projectKey, modelKey && hinted(modelKey, "model & mode"), worktreeKey, cancelDraftKey)
|
||||
: navKeys,
|
||||
);
|
||||
|
||||
// Commands only the palette runs.
|
||||
const paletteOnly = keys(
|
||||
editorKey,
|
||||
pane?.kind === "server" && { keys: [], run: () => closePane(), command: { id: "pane-close", title: "Close the terminal pane", keywords: ["detach", "hide"] } },
|
||||
{ keys: [], run: () => setSplitDiffPref(!splitDiff), command: { id: "split-diff", title: "Toggle split diff", keywords: ["side by side", "unified", "diff view"] } },
|
||||
queue.keys.input,
|
||||
queue.keys.palette,
|
||||
(projection?.subagents ?? []).filter((agent) => threadId && canStopSubagent(agent)).map((agent): Binding => ({ keys: [], run: () => run("Stop requested", () => session.stopSubagent(agent)), command: { id: `stop-subagent:${agent.id}`, title: `Stop subagent: ${agent.title ?? "subagent"}`, keywords: ["interrupt", "cancel", "kill"] } })),
|
||||
@@ -814,7 +906,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
pullRequests.commands.map((command): Binding => ({ ...fromCommand(command), keys: [], ...(command.shortcut ? { label: command.shortcut } : {}) })),
|
||||
{ keys: [], run: openSettings, command: { id: "settings", title: "Settings", keywords: ["preferences", "config", "options", "notifications", "alerts"] } },
|
||||
);
|
||||
const commands = commandsFor([...navKeys, ...paletteOnly]);
|
||||
const commands = commandsFor(keys(paneKey, navKeys, paletteOnly));
|
||||
|
||||
// The composer. Enter and newlines are the textarea's own; their hints only explain.
|
||||
const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
|
||||
@@ -828,6 +920,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
queue.keys.input,
|
||||
{ keys: [], label: config.sendShortcut === "enter" ? "shift+enter or \\" : "enter", hint: "newline" },
|
||||
editorKey && hinted(editorKey, "editor"),
|
||||
{ keys: ["ctrl+v"], run: () => attach.paste((text) => composerRef.current?.insertText(text)) },
|
||||
{ keys: ["esc"], run: () => setMode("nav"), hint: "navigate" },
|
||||
!attached && hinted(nextThreadKey, "thread"),
|
||||
);
|
||||
@@ -888,6 +981,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
return { layers: [confirmKeys], hints: confirmKeys };
|
||||
}
|
||||
}
|
||||
if (mode === "pane" && paneKey) return { layers: [[paneKey]], hints: [paneKey] };
|
||||
// The secret field takes every key while it's focused.
|
||||
if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings };
|
||||
switch (mode) {
|
||||
@@ -921,7 +1015,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
return key.preventDefault();
|
||||
}
|
||||
}
|
||||
if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm") {
|
||||
if (secret.focused && mode !== "find" && mode !== "picker" && mode !== "palette" && mode !== "confirm" && mode !== "pane") {
|
||||
secret.type(key);
|
||||
key.preventDefault();
|
||||
}
|
||||
@@ -948,9 +1042,10 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
loadEarlier: useEvent(() => loadEarlier()),
|
||||
menu: useEvent((target: ConversationTarget) => openConversationMenu(target)),
|
||||
openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)),
|
||||
click: useEvent((x: number, y: number) => openAt(x, y)),
|
||||
};
|
||||
const copy = (label: string, text: string) => {
|
||||
copyText(renderer, text);
|
||||
void clipboard.copy(text);
|
||||
say(`Copied ${label}`);
|
||||
};
|
||||
/** Long output stays on the server until it's asked for. */
|
||||
@@ -985,7 +1080,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
});
|
||||
/** A click in the conversation, a diff or the PR view takes the keys there, out of the composer or details. */
|
||||
const focusConversation = (event: MouseEvent) => {
|
||||
if (event.button !== 0 || (mode !== "input" && mode !== "details")) return;
|
||||
if (event.button !== 0 || (mode !== "input" && mode !== "details" && mode !== "pane")) return;
|
||||
panel.leave();
|
||||
};
|
||||
|
||||
@@ -999,8 +1094,13 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
// Room for the details column and its edge beside the conversation; a dragged width gives way to the conversation first.
|
||||
const detailsRoom = width - listWidth - 1 - MIN_CONVERSATION_WIDTH;
|
||||
const detailsWidth = Math.min(detailsWidthPref ?? DETAILS_WIDTH, Math.max(DETAILS_WIDTH, detailsRoom));
|
||||
const detailsColumn = panel.show && detailsWidth <= detailsRoom;
|
||||
const detailsInPlace = panel.show && !detailsColumn;
|
||||
// The pane takes the details column's place, or the conversation's when there's no room beside it.
|
||||
const paneColumn = pane !== null && detailsWidth <= detailsRoom;
|
||||
const detailsColumn = !pane && panel.show && detailsWidth <= detailsRoom;
|
||||
const detailsInPlace = !pane && panel.show && !detailsColumn;
|
||||
const rightColumn = paneColumn || detailsColumn;
|
||||
const conversationWidth = width - (showList ? listWidth + 1 : 0) - (rightColumn ? detailsWidth + 1 : 0);
|
||||
const splitDiff = splitDiffPref ?? conversationWidth >= SPLIT_DIFF_WIDTH;
|
||||
// The block's height: a row of padding on top, the text, then the model line inside it.
|
||||
// Padding row, text, a blank row, then the model line.
|
||||
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 3;
|
||||
@@ -1044,6 +1144,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
inPlace={inPlace}
|
||||
selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? panel.selected : null}
|
||||
onActivate={panel.activateById}
|
||||
onEdit={panel.edit}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1118,8 +1219,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
saveLayoutNow({ listWidth: null });
|
||||
}} />}
|
||||
<box flexDirection="column" flexGrow={1} minHeight={0}>
|
||||
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation}>
|
||||
{settingsIndex !== null ? (
|
||||
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation} onSizeChange={function (this: { height: number }) { setContentHeight(this.height); }}>
|
||||
{pane && !paneColumn ? null : settingsIndex !== null ? (
|
||||
<SettingsView
|
||||
rows={settingsRows}
|
||||
server={serverSettingLines(serverConfig?.config ?? null)}
|
||||
@@ -1135,7 +1236,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
) : mode === "pull-request" && pullRequests.view ? (
|
||||
<PullRequestView view={pullRequests.view} scrollRef={scrollRef} onOpenUrl={() => pullRequests.commands.find((candidate) => candidate.id === "pr-open")?.run()} onMenu={openPullRequestMenu} onClose={pullRequests.close} />
|
||||
) : diff ? (
|
||||
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} onFile={turns.diffContext.click} />
|
||||
<DiffView diff={diff} split={splitDiff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} onFile={turns.diffContext.click} />
|
||||
) : draft ? (
|
||||
<DraftView lines={newThread.lines(models.open)} />
|
||||
) : threadId && detailsInPlace && mode !== "find" ? (
|
||||
@@ -1171,7 +1272,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
|
||||
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
|
||||
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} actions={secret.actions} /> : null}
|
||||
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? detailsWidth + 1 : 0) - 3} actions={queue.actions} /> : null}
|
||||
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (rightColumn ? detailsWidth + 1 : 0) - 3} actions={queue.actions} /> : null}
|
||||
{mode !== "confirm" && questions.request && questions.draft ? <QuestionPanel
|
||||
request={questions.request}
|
||||
index={questions.draft.index}
|
||||
@@ -1192,7 +1293,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
onCancel={closeOverlay}
|
||||
/>
|
||||
) : null}
|
||||
{menu ? <ComposerMenu items={menu.items} selected={composerMenu.selected} empty={menu.empty} width={width - listWidth - (detailsColumn ? detailsWidth + 1 : 0) - 2} onPick={composerMenu.pick} /> : null}
|
||||
{menu ? <ComposerMenu items={menu.items} selected={composerMenu.selected} empty={menu.empty} width={width - listWidth - (rightColumn ? detailsWidth + 1 : 0) - 2} onPick={composerMenu.pick} /> : null}
|
||||
{attach.pending.length > 0 ? (
|
||||
<box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
|
||||
<text fg={colors.muted}>Attached:</text>
|
||||
@@ -1236,12 +1337,23 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
focusedBackgroundColor={colors.element}
|
||||
wrapMode="word"
|
||||
keyBindings={[...COMPOSER_KEYS[config.sendShortcut]]}
|
||||
syntaxStyle={markdownStyle}
|
||||
onSubmit={() => submit()}
|
||||
onPaste={(event: PasteEvent) => {
|
||||
const text = decodePasteBytes(event.bytes);
|
||||
// An empty paste is how terminals pass on a copied image they can't send as text.
|
||||
const path = text.trim() ? pastedImagePath(text, attachCwd) : null;
|
||||
if (text.trim() && !(path && existsSync(path))) return;
|
||||
event.preventDefault();
|
||||
if (path) attach.attachPath(path);
|
||||
else attach.paste();
|
||||
}}
|
||||
onCursorChange={composerMenu.sync}
|
||||
onContentChange={() => {
|
||||
composerMenu.sync();
|
||||
chips.sync();
|
||||
const composer = composerRef.current;
|
||||
const text = composer?.plainText ?? "";
|
||||
const text = composer ? composerText(composer) : "";
|
||||
if (text) drafts.current.set(composerKey, text);
|
||||
else drafts.current.delete(composerKey);
|
||||
// Wrapped lines count too, so a long paragraph grows the box.
|
||||
@@ -1275,14 +1387,24 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
</box>
|
||||
) : null}
|
||||
</box>
|
||||
{detailsColumn ? (
|
||||
<>
|
||||
<ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => {
|
||||
setDetailsWidthPref(null);
|
||||
saveLayoutNow({ detailsWidth: null });
|
||||
}} />
|
||||
{detailsPanel(false)}
|
||||
</>
|
||||
{rightColumn ? (
|
||||
<ResizeHandle active={resizing === "details"} onStart={() => setResizing("details")} onReset={() => {
|
||||
setDetailsWidthPref(null);
|
||||
saveLayoutNow({ detailsWidth: null });
|
||||
}} />
|
||||
) : null}
|
||||
{detailsColumn ? detailsPanel(false) : null}
|
||||
{/* One place in the tree in both layouts, so a narrower window doesn't restart its program. */}
|
||||
{pane ? (
|
||||
<TerminalPane
|
||||
key={pane.id}
|
||||
program={pane}
|
||||
session={session}
|
||||
focused={mode === "pane"}
|
||||
onFocus={() => setMode("pane")}
|
||||
onClose={closePane}
|
||||
place={paneColumn ? { width: detailsWidth } : { left: showList ? listWidth + 1 : 0, height: contentHeight }}
|
||||
/>
|
||||
) : null}
|
||||
</box>
|
||||
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
|
||||
|
||||
+17
-8
@@ -1,9 +1,9 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { MAX_DETAIL_FILES, type ChangedFile, type DetailsAction, type DetailsFold, type LineageLine, type ThreadDetails } from "../model/details.ts";
|
||||
import { ClickRow } from "./Button.tsx";
|
||||
import { Button, ClickRow } from "./Button.tsx";
|
||||
import { truncate } from "./text.ts";
|
||||
import { colors, statusColor } from "./theme.ts";
|
||||
import { colors, scrollbarOptions, statusColor } from "./theme.ts";
|
||||
|
||||
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */
|
||||
const IN_PLACE_MAX_WIDTH = 64;
|
||||
@@ -25,6 +25,8 @@ export function DetailsPanel(props: {
|
||||
readonly selected: string | null;
|
||||
readonly unfolded: ReadonlySet<DetailsFold>;
|
||||
readonly onActivate: (id: string) => void;
|
||||
/** Opens a changed file in $EDITOR, from its ▸ Edit. */
|
||||
readonly onEdit: (path: string) => void;
|
||||
/** Shown when there are no details, which defaults to no thread being selected. */
|
||||
readonly empty?: string;
|
||||
}) {
|
||||
@@ -44,11 +46,11 @@ export function DetailsPanel(props: {
|
||||
overflow="hidden"
|
||||
backgroundColor={colors.panel}
|
||||
>
|
||||
<scrollbox flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1}>
|
||||
<scrollbox flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1} scrollbarOptions={scrollbarOptions()}>
|
||||
{!details ? (
|
||||
<text fg={colors.faint}>{props.empty ?? "No thread selected."}</text>
|
||||
) : (
|
||||
<Sections details={details} inner={inner} loading={props.loading} unfolded={props.unfolded} selected={props.selected} onActivate={props.onActivate} />
|
||||
<Sections details={details} inner={inner} loading={props.loading} unfolded={props.unfolded} selected={props.selected} onActivate={props.onActivate} onEdit={props.onEdit} />
|
||||
)}
|
||||
</scrollbox>
|
||||
</box>
|
||||
@@ -60,7 +62,7 @@ interface LineProps {
|
||||
readonly onActivate: (id: string) => void;
|
||||
}
|
||||
|
||||
function Sections({ details, inner, loading, unfolded, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet<DetailsFold> } & LineProps) {
|
||||
function Sections({ details, inner, loading, unfolded, selected, onActivate, onEdit }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean; readonly unfolded: ReadonlySet<DetailsFold>; readonly onEdit: (path: string) => void } & LineProps) {
|
||||
const { branch, changes, git, tasks } = details;
|
||||
const files = changes?.files ?? [];
|
||||
const line = { selected, onActivate };
|
||||
@@ -102,9 +104,16 @@ function Sections({ details, inner, loading, unfolded, selected, onActivate }: {
|
||||
{changes ? (
|
||||
<Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}>
|
||||
{files.slice(0, MAX_DETAIL_FILES).map((file) => (
|
||||
<Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}>
|
||||
<FileLine file={file} inner={inner} />
|
||||
</Selectable>
|
||||
<box key={file.path} flexDirection="column">
|
||||
<Selectable id={`diff:${file.path}`} {...line} inner={inner}>
|
||||
<FileLine file={file} inner={inner} />
|
||||
</Selectable>
|
||||
{selected === `diff:${file.path}` && !file.path.endsWith("/") ? (
|
||||
<box flexDirection="row" marginLeft={1}>
|
||||
<Button label="▸ Edit" shortcut="o" plain onPress={() => onEdit(file.path)} />
|
||||
</box>
|
||||
) : null}
|
||||
</box>
|
||||
))}
|
||||
{files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null}
|
||||
{files.length === 0 ? <text fg={colors.faint}>Working tree clean</text> : null}
|
||||
|
||||
+13
-7
@@ -4,7 +4,7 @@ import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||
import type { RefObject } from "react";
|
||||
|
||||
import { isLeftClick, useHover } from "./Button.tsx";
|
||||
import { colors, useMarkdownStyle } from "./theme.ts";
|
||||
import { colors, scrollbarOptions, useMarkdownStyle } from "./theme.ts";
|
||||
|
||||
export interface DiffState {
|
||||
readonly cwd: string;
|
||||
@@ -18,8 +18,8 @@ export interface DiffState {
|
||||
readonly error?: string;
|
||||
}
|
||||
|
||||
/** 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 }>>; readonly onFile: (index: number) => void }) {
|
||||
/** Working-tree or checkpoint changes through the same diff renderer: side by side when `split`, else unified. */
|
||||
export function DiffView(props: { readonly diff: DiffState; readonly split: boolean; 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 markdownStyle = useMarkdownStyle();
|
||||
const files = diff.patch ? splitPatch(diff.patch) : [];
|
||||
@@ -37,14 +37,15 @@ export function DiffView(props: { readonly diff: DiffState; readonly scrollRef:
|
||||
{diff.status === "error" ? <text fg={colors.bad} flexShrink={0}>{`Could not load the diff: ${diff.error ?? "unknown error"}`}</text> : null}
|
||||
{diff.status === "ready" && files.length === 0 ? <text fg={colors.muted} flexShrink={0}>No changes.</text> : null}
|
||||
{diff.truncated ? <text fg={colors.warn} flexShrink={0}>The diff was too large and is cut short.</text> : null}
|
||||
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
|
||||
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0} scrollbarOptions={scrollbarOptions()}>
|
||||
{files.map((file, index) => (
|
||||
<box key={file.path} id={`diff-file-${index}`} flexDirection="column" marginTop={1}>
|
||||
<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}
|
||||
<diff
|
||||
diff={props.expanded[file.path]?.patch ?? file.patch}
|
||||
view="unified"
|
||||
view={props.split ? "split" : "unified"}
|
||||
syncScroll
|
||||
{...(filetypeOf(file.path) ? { filetype: filetypeOf(file.path)! } : {})}
|
||||
syntaxStyle={markdownStyle}
|
||||
showLineNumbers
|
||||
@@ -52,11 +53,16 @@ export function DiffView(props: { readonly diff: DiffState; readonly scrollRef:
|
||||
fg={colors.text}
|
||||
addedBg={colors.diffAddedBg}
|
||||
removedBg={colors.diffRemovedBg}
|
||||
contextBg={colors.bg}
|
||||
addedContentBg={colors.diffAddedBg}
|
||||
removedContentBg={colors.diffRemovedBg}
|
||||
addedSignColor={colors.good}
|
||||
removedSignColor={colors.bad}
|
||||
contextContentBg={colors.bg}
|
||||
addedSignColor={colors.diffAddedSign}
|
||||
removedSignColor={colors.diffRemovedSign}
|
||||
lineNumberFg={colors.faint}
|
||||
lineNumberBg={colors.diffGutterBg}
|
||||
addedLineNumberBg={colors.diffAddedGutterBg}
|
||||
removedLineNumberBg={colors.diffRemovedGutterBg}
|
||||
/>
|
||||
</box>
|
||||
))}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { RefObject } from "react";
|
||||
|
||||
import type { PullRequestLine } from "../model/pullRequests.ts";
|
||||
import { Button, isLeftClick, isRightClick, useHover } from "./Button.tsx";
|
||||
import { colors, type Palette } from "./theme.ts";
|
||||
import { colors, type Palette, scrollbarOptions } from "./theme.ts";
|
||||
|
||||
export interface PullRequestViewState {
|
||||
readonly status: "loading" | "ready" | "error";
|
||||
@@ -41,7 +41,7 @@ export function PullRequestView(props: { readonly view: PullRequestViewState; re
|
||||
</box>
|
||||
{view.status === "loading" ? <text fg={colors.muted} flexShrink={0}>Loading pull request…</text> : null}
|
||||
{view.status === "error" ? <text fg={colors.bad} flexShrink={0}>{`Could not load the pull request: ${view.error ?? "unknown error"}`}</text> : null}
|
||||
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
|
||||
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0} scrollbarOptions={scrollbarOptions()}>
|
||||
{view.lines.map((line, index) =>
|
||||
line.kind === "title" && index > 0 ? (
|
||||
<text key={index} fg={colors[LINE_COLORS[line.kind]]} marginTop={1}>
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { EmbeddedTerminalRenderable, type EmbeddedTerminalDataSource } from "@opentui/core";
|
||||
import { extend } from "@opentui/react";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import type { T3Session } from "../client/session.ts";
|
||||
import { BAR } from "./edges.ts";
|
||||
import type { TerminalTarget } from "./terminalAttach.ts";
|
||||
import { truncate } from "./text.ts";
|
||||
import { colors } from "./theme.ts";
|
||||
import { useEvent } from "./useEvent.ts";
|
||||
|
||||
declare module "@opentui/react" {
|
||||
interface OpenTUIComponents {
|
||||
embeddedTerminal: typeof EmbeddedTerminalRenderable;
|
||||
}
|
||||
}
|
||||
|
||||
extend({ embeddedTerminal: EmbeddedTerminalRenderable });
|
||||
|
||||
/** What runs in the pane: one of T3's terminals, or a program run here, like $EDITOR. */
|
||||
export type PaneProgram =
|
||||
| { readonly kind: "server"; readonly id: string; readonly title: string; readonly target: TerminalTarget }
|
||||
| { readonly kind: "local"; readonly id: string; readonly title: string; readonly command: readonly string[]; readonly cwd?: string | undefined; readonly onExit: (code: number) => void };
|
||||
|
||||
/** How the pane talks to its program once it knows its size. */
|
||||
interface Link {
|
||||
readonly send: (data: Uint8Array, source: EmbeddedTerminalDataSource) => void;
|
||||
readonly resize: (cols: number, rows: number) => void;
|
||||
readonly stop: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A terminal in the right-hand column: keys go to its program while it has focus, its size
|
||||
* follows the column, and it closes when the program exits. Key it by the program's id.
|
||||
*/
|
||||
export function TerminalPane(props: {
|
||||
readonly program: PaneProgram;
|
||||
readonly session: T3Session;
|
||||
readonly focused: boolean;
|
||||
/** A column this wide beside the conversation, or the conversation's place: from `left`, `height` tall. */
|
||||
readonly place: { readonly width: number } | { readonly left: number; readonly height: number };
|
||||
readonly onFocus: () => void;
|
||||
readonly onClose: (message?: string) => void;
|
||||
}) {
|
||||
const { program, focused, place } = props;
|
||||
const terminal = useRef<EmbeddedTerminalRenderable | null>(null);
|
||||
const link = useRef<Link | null>(null);
|
||||
const onFocus = useEvent(props.onFocus);
|
||||
const onClose = useEvent(props.onClose);
|
||||
|
||||
useEffect(() => () => link.current?.stop(), []);
|
||||
useEffect(() => {
|
||||
const term = terminal.current;
|
||||
if (!term) return;
|
||||
if (focused) term.focus();
|
||||
else term.blur();
|
||||
}, [focused]);
|
||||
// A click the program takes as a mouse event still focuses the terminal; that is the pane's focus too.
|
||||
useEffect(() => {
|
||||
const term = terminal.current;
|
||||
term?.on("focused", onFocus);
|
||||
return () => void term?.off("focused", onFocus);
|
||||
}, [onFocus]);
|
||||
|
||||
const start = (term: EmbeddedTerminalRenderable, cols: number, rows: number) => {
|
||||
paint(term);
|
||||
link.current = program.kind === "server" ? attachServer(props.session, program.target, term, cols, rows, onClose) : spawnLocal(program, term, cols, rows, onClose);
|
||||
};
|
||||
|
||||
return (
|
||||
<box
|
||||
{...("width" in place ? { width: place.width, flexShrink: 0 } : { position: "absolute", left: place.left, right: 0, top: 0, height: place.height })}
|
||||
minHeight={0}
|
||||
flexDirection="column"
|
||||
overflow="hidden"
|
||||
backgroundColor={colors.panel}
|
||||
border={["left"]}
|
||||
customBorderChars={BAR}
|
||||
borderColor={focused ? colors.accent : colors.panel}
|
||||
onMouseDown={onFocus}
|
||||
>
|
||||
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1}>
|
||||
<text fg={focused ? colors.text : colors.muted} wrapMode="none">{truncate(program.title, Math.max(8, ("width" in place ? place.width : 80) - 17))}</text>
|
||||
<box flexGrow={1} />
|
||||
<text fg={colors.faint} wrapMode="none" flexShrink={0}>{focused ? "ctrl+\\ leave" : "ctrl+\\ focus"}</text>
|
||||
</box>
|
||||
<embeddedTerminal
|
||||
ref={terminal}
|
||||
flexGrow={1}
|
||||
minHeight={0}
|
||||
width="100%"
|
||||
onTerminalResize={function (this: EmbeddedTerminalRenderable, cols: number, rows: number) {
|
||||
if (link.current) link.current.resize(cols, rows);
|
||||
else start(this, cols, rows);
|
||||
}}
|
||||
onData={(data, source) => link.current?.send(data, source)}
|
||||
/>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
/** The program's default colours are the pane's. */
|
||||
function paint(term: EmbeddedTerminalRenderable): void {
|
||||
term.write(`\x1b]10;${colors.text}\x1b\\\x1b]11;${colors.panel}\x1b\\`);
|
||||
}
|
||||
|
||||
/**
|
||||
* One of T3's terminals: its scrollback, then live output; typed keys go to it. Only keys:
|
||||
* the emulator's own answers to queries replayed from history must not reach the shell.
|
||||
*/
|
||||
function attachServer(session: T3Session, target: TerminalTarget, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
|
||||
const { threadId, terminalId } = target;
|
||||
const decoder = new TextDecoder();
|
||||
let stopped = false;
|
||||
let detach = () => {};
|
||||
const end = (message?: string) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
detach();
|
||||
close(message);
|
||||
};
|
||||
detach = session.attachTerminal(
|
||||
{ threadId, terminalId, cwd: target.cwd, worktreePath: target.worktreePath, cols, rows },
|
||||
(event) => {
|
||||
if (stopped) return;
|
||||
switch (event.type) {
|
||||
case "snapshot":
|
||||
case "restarted":
|
||||
term.write("\x1bc");
|
||||
paint(term);
|
||||
term.write(event.snapshot.history);
|
||||
return;
|
||||
case "output":
|
||||
term.write(event.data);
|
||||
return;
|
||||
case "cleared":
|
||||
term.write("\x1b[H\x1b[2J");
|
||||
return;
|
||||
case "error":
|
||||
term.write(`\r\n\x1b[31m[${event.message}]\x1b[0m\r\n`);
|
||||
return;
|
||||
case "exited":
|
||||
return end(`${target.label} exited`);
|
||||
case "closed":
|
||||
return end("Terminal closed");
|
||||
}
|
||||
},
|
||||
(error) => end(error ? `Terminal: ${error}` : undefined),
|
||||
);
|
||||
// A fake or failing session can end the stream before it returns.
|
||||
if (stopped) detach();
|
||||
return {
|
||||
send: (data, source) => {
|
||||
if (source === "input" && !stopped) session.writeTerminal(threadId, terminalId, decoder.decode(data, { stream: true })).catch(() => {});
|
||||
},
|
||||
resize: (next, height) => void session.resizeTerminal(threadId, terminalId, next, height).catch(() => {}),
|
||||
stop: () => {
|
||||
stopped = true;
|
||||
detach();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A program run here on its own pty, answering its terminal queries through the emulator. */
|
||||
function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
|
||||
let stopped = false;
|
||||
const child = Bun.spawn([...program.command], {
|
||||
...(program.cwd ? { cwd: program.cwd } : {}),
|
||||
terminal: { cols, rows, data: (_pty, data) => term.write(data) },
|
||||
});
|
||||
void child.exited.then((code) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
program.onExit(code);
|
||||
close();
|
||||
});
|
||||
return {
|
||||
send: (data) => void child.terminal?.write(data),
|
||||
resize: (next, height) => child.terminal?.resize(next, height),
|
||||
stop: () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
child.kill();
|
||||
},
|
||||
};
|
||||
}
|
||||
+49
-8
@@ -1,7 +1,7 @@
|
||||
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||
import type { ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import type { ImageRenderable, MouseEvent, ScrollBoxRenderable } from "@opentui/core";
|
||||
import type { ChatAttachment, ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
|
||||
import { memo, useEffect, useState, type RefObject } from "react";
|
||||
import { memo, useEffect, useRef, useState, type RefObject } from "react";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { findTextSegments } from "../model/search.ts";
|
||||
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
|
||||
@@ -18,7 +18,7 @@ import type { T3Session, ThreadHistory } from "../client/session.ts";
|
||||
import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts";
|
||||
import { blockFor } from "../model/transcript.ts";
|
||||
import { firstLine, truncate } from "./text.ts";
|
||||
import { colors, toneColor, useMarkdownStyle } from "./theme.ts";
|
||||
import { colors, scrollbarOptions, toneColor, useMarkdownStyle } from "./theme.ts";
|
||||
|
||||
/** What a right-click in the conversation was on. */
|
||||
export type ConversationTarget =
|
||||
@@ -35,6 +35,8 @@ export interface ConversationMouse {
|
||||
readonly menu: (target: ConversationTarget) => void;
|
||||
/** A click on a changed file: that turn's diff. */
|
||||
readonly openTurnDiff: (checkpointTurnCount: number) => void;
|
||||
/** A click in a reply's text, at its screen position, for the link or path under it. */
|
||||
readonly click: (x: number, y: number) => void;
|
||||
}
|
||||
|
||||
/** Prose stops at this width on wide terminals, left-aligned. */
|
||||
@@ -72,7 +74,7 @@ export function ThreadView(props: {
|
||||
</box>
|
||||
) : 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" scrollbarOptions={scrollbarOptions()}>
|
||||
{/* Prose stops at reading width on wide terminals; the composer below stays full width. */}
|
||||
<box flexDirection="column" maxWidth={CONTENT_WIDTH}>
|
||||
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
|
||||
@@ -175,11 +177,11 @@ const Row = memo(function Row(props: {
|
||||
}
|
||||
const summary = row.assistantTurnDiffSummary;
|
||||
const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text, ...(summary && summary.files.length > 0 ? { checkpointTurnCount: summary.checkpointTurnCount } : {}) } as const;
|
||||
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 === "user") return <UserMessage session={props.session} text={message.text} attachments={message.attachments ?? []} 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 (
|
||||
<box marginTop={1} flexDirection="column" onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>
|
||||
<markdown content={message.text || "…"} syntaxStyle={markdownStyle} streaming={message.streaming} conceal />
|
||||
<markdown content={message.text || "…"} syntaxStyle={markdownStyle} streaming={message.streaming} conceal tableOptions={{ widthMode: "content", wrapMode: "word", cellPaddingX: 1, borderColor: colors.border }} onMouseUp={(event: MouseEvent) => isLeftClick(event) && mouse.click(event.x, event.y)} />
|
||||
{summary && summary.files.length > 0 ? <ChangedFiles summary={summary} onOpenTurnDiff={mouse.openTurnDiff} /> : null}
|
||||
{props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null}
|
||||
</box>
|
||||
@@ -308,7 +310,7 @@ const USER_FOLD_LINES = 8;
|
||||
const USER_FOLD_CHARS = 600;
|
||||
|
||||
/** Your message: a full-width raised block, folded past 8 lines or 600 characters. */
|
||||
function UserMessage({ text, messageId, selected, onSelect, onMenu }: { readonly text: string; readonly messageId: string; readonly selected: boolean; readonly onSelect: () => void; readonly onMenu: () => void }) {
|
||||
function UserMessage({ session, text, attachments, messageId, selected, onSelect, onMenu }: { readonly session: T3Session; readonly text: string; readonly attachments: readonly ChatAttachment[]; readonly messageId: string; readonly selected: boolean; readonly onSelect: () => void; readonly onMenu: () => void }) {
|
||||
const [hover, hoverProps] = useHover();
|
||||
const trimmed = text.trim();
|
||||
const lines = trimmed.split("\n");
|
||||
@@ -319,6 +321,45 @@ function UserMessage({ text, messageId, selected, onSelect, onMenu }: { readonly
|
||||
<box id={`turn-${messageId}`} border={["left"]} customBorderChars={BAR} borderColor={colors.accent} marginTop={1} backgroundColor={hover ? colors.elementHover : selected ? colors.selectedBg : colors.element} paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2} flexDirection="column" {...hoverProps} onMouseDown={(event: MouseEvent) => (isRightClick(event) ? onMenu() : isLeftClick(event) ? onSelect() : undefined)}>
|
||||
<text fg={colors.text}>{shown}</text>
|
||||
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
|
||||
{attachments.map((attachment) => (attachment.type === "image" ? <MessageImage key={attachment.id} session={session} attachment={attachment} /> : <text key={attachment.id} fg={colors.muted}>{`▤ ${attachment.name}`}</text>))}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
const IMAGE_ROWS = 12;
|
||||
|
||||
/** A sent image, shown in the terminal's best image protocol; its name alone until it loads, or if it can't. */
|
||||
function MessageImage({ session, attachment }: { readonly session: T3Session; readonly attachment: ChatAttachment }) {
|
||||
const [bytes, setBytes] = useState<Uint8Array | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [size, setSize] = useState({ width: CONTENT_WIDTH, height: IMAGE_ROWS });
|
||||
const image = useRef<ImageRenderable | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
session.attachmentImage(attachment).then(
|
||||
(loaded) => !cancelled && setBytes(loaded),
|
||||
() => !cancelled && setFailed(true),
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [session, attachment]);
|
||||
const name = <text fg={colors.muted}>{`▣ ${attachment.name}`}</text>;
|
||||
if (!bytes || failed) return <box marginTop={1}>{name}</box>;
|
||||
return (
|
||||
<box marginTop={1} flexDirection="column">
|
||||
<image
|
||||
ref={image}
|
||||
source={bytes}
|
||||
fit="fit"
|
||||
protocol="auto"
|
||||
width={size.width}
|
||||
maxWidth="100%"
|
||||
height={size.height}
|
||||
onLoad={() => image.current && setSize(image.current.getFittedSize(CONTENT_WIDTH, IMAGE_ROWS))}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
{name}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createClipboard, createHostClipboard, createRendererClipboardAdapter, type CliRenderer } from "@opentui/core";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { CLIPBOARD_IMAGE_TYPES, clipboardImageCommands, pickClipboardImageType } from "../model/attachments.ts";
|
||||
|
||||
export type ClipboardImage = { readonly bytes: Uint8Array; readonly mimeType: string } | "empty" | "no-tool";
|
||||
|
||||
/** The clipboard as the app uses it: images and text in, copied text out. */
|
||||
export interface Clipboard {
|
||||
readonly readImage: () => Promise<ClipboardImage>;
|
||||
readonly readText: () => Promise<string | null>;
|
||||
/** OSC 52 first, which works over SSH, then the desktop's clipboard; false if neither took it. */
|
||||
readonly copy: (text: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
/** OpenTUI's clipboard service, with the platform tools behind it for images it can't read. */
|
||||
export function rendererClipboard(renderer: CliRenderer): Clipboard {
|
||||
const service = createClipboard({ host: createHostClipboard(), terminal: createRendererClipboardAdapter(renderer) });
|
||||
return {
|
||||
readImage: async () => {
|
||||
const result = await service.read({ preferredTypes: CLIPBOARD_IMAGE_TYPES }).catch(() => null);
|
||||
if (result?.status === "read") return { bytes: result.representation.bytes, mimeType: result.representation.mimeType };
|
||||
if (result?.status === "empty") return "empty";
|
||||
return imageFromTools(process.platform);
|
||||
},
|
||||
readText: async () => {
|
||||
const result = await service.read({ preferredTypes: ["text/plain;charset=utf-8", "text/plain"] }).catch(() => null);
|
||||
return result?.status === "read" ? new TextDecoder().decode(result.representation.bytes) : null;
|
||||
},
|
||||
copy: async (text) => {
|
||||
const result = await service.writeText(text, { destination: "all-available" }).catch(() => null);
|
||||
return result !== null && (result.terminal.status === "attempted" || result.host.status === "written");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** wl-paste, xclip, pngpaste or osascript: the first one installed answers. */
|
||||
function imageFromTools(platform: string): ClipboardImage {
|
||||
for (const tool of clipboardImageCommands(platform)) {
|
||||
const run = (argv: readonly string[]) => spawnSync(argv[0]!, argv.slice(1), { maxBuffer: 64 * 1024 * 1024 });
|
||||
let mimeType = tool.mimeType ?? null;
|
||||
if (tool.types) {
|
||||
const listed = run(tool.types);
|
||||
if ((listed.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") continue;
|
||||
mimeType = listed.status === 0 ? pickClipboardImageType(listed.stdout.toString().split("\n")) : null;
|
||||
if (!mimeType) return "empty";
|
||||
}
|
||||
const result = run(tool.read(mimeType!));
|
||||
if ((result.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") continue;
|
||||
const bytes = result.status === 0 && result.stdout.length > 0 ? (tool.decode ? tool.decode(result.stdout) : result.stdout) : null;
|
||||
return bytes && bytes.length > 0 ? { bytes, mimeType: mimeType! } : "empty";
|
||||
}
|
||||
return "no-tool";
|
||||
}
|
||||
+19
-8
@@ -4,23 +4,34 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** $VISUAL or $EDITOR (falling back to vi) on `file`, through the shell so EDITOR="code --wait" works. */
|
||||
export function editorCommand(file: string): string[] {
|
||||
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
|
||||
return [process.env.SHELL || "sh", "-c", `${editor} "$1"`, "sh", file];
|
||||
}
|
||||
|
||||
/** A scratch copy of `text` to edit: `read` returns what was saved, `remove` cleans up. */
|
||||
export function scratchFile(text: string): { readonly path: string; readonly read: () => string; readonly remove: () => void } {
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
|
||||
const path = join(dir, "prompt.md");
|
||||
writeFileSync(path, text);
|
||||
return { path, read: () => readFileSync(path, "utf8").replace(/\n$/, ""), remove: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the terminal to $VISUAL or $EDITOR on a copy of `text` and returns what was saved,
|
||||
* or null if the editor failed. The renderer is suspended meanwhile.
|
||||
*/
|
||||
export async function editInEditor(renderer: CliRenderer, text: string): Promise<string | null> {
|
||||
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
|
||||
const file = join(dir, "prompt.md");
|
||||
writeFileSync(file, text);
|
||||
const file = scratchFile(text);
|
||||
await renderer.suspend();
|
||||
try {
|
||||
// Through the shell, so EDITOR="code --wait" works.
|
||||
const result = spawnSync(process.env.SHELL || "sh", ["-c", `${editor} "$1"`, "sh", file], { stdio: "inherit" });
|
||||
const [command, ...args] = editorCommand(file.path);
|
||||
const result = spawnSync(command!, args, { stdio: "inherit" });
|
||||
if (result.status !== 0) return null;
|
||||
return readFileSync(file, "utf8").replace(/\n$/, "");
|
||||
return file.read();
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
file.remove();
|
||||
await renderer.resume();
|
||||
renderer.requestRender();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { CliRenderer } from "@opentui/core";
|
||||
|
||||
/** Opens a web link in the desktop's browser; `fail` hears why it couldn't, as over SSH. */
|
||||
export function openInBrowser(url: string, fail: (reason: string) => void): void {
|
||||
try {
|
||||
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
||||
// The environment as it is now: Bun otherwise looks the opener up on the PATH it started with.
|
||||
const child = Bun.spawn([opener, url], { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
void child.exited.then((code) => {
|
||||
if (code !== 0) fail(`${opener} exited with ${code}`);
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
|
||||
/** The screen row `y` as drawn, and the index in it of the character in column `x`. */
|
||||
export function screenTextAt(renderer: CliRenderer, x: number, y: number): { readonly text: string; readonly index: number } | null {
|
||||
const row = new TextDecoder().decode(renderer.currentRenderBuffer.getRealCharBytes(true)).split("\n")[y];
|
||||
if (row === undefined) return null;
|
||||
// Wide characters take two columns but one place in the text.
|
||||
let column = 0;
|
||||
let index = 0;
|
||||
for (const char of row) {
|
||||
column += Bun.stringWidth(char);
|
||||
if (column > x) return { text: row, index };
|
||||
index += char.length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+1
-25
@@ -1,5 +1,4 @@
|
||||
/** Escape sequences t3tui writes past the renderer: the bell, desktop notifications, the clipboard. */
|
||||
import type { CliRenderer } from "@opentui/core";
|
||||
/** Escape sequences t3tui writes past the renderer: the bell and desktop notifications. */
|
||||
|
||||
/** Inside tmux, escape sequences other than the bell need passthrough to reach the outer terminal. */
|
||||
function passthrough(sequence: string): string {
|
||||
@@ -25,26 +24,3 @@ export function desktopNotify(title: string, body: string): void {
|
||||
: `\x1b]9;${clean(title)}: ${clean(body)}\x07`;
|
||||
process.stdout.write(passthrough(sequence));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies text: through the terminal (OSC 52, which also works over SSH), and on a local
|
||||
* desktop through its clipboard tool too, for terminals that ignore OSC 52.
|
||||
*/
|
||||
export function copyText(renderer: CliRenderer, text: string): void {
|
||||
try {
|
||||
renderer.copyToClipboardOSC52(text);
|
||||
} catch {
|
||||
// OpenTUI refuses when it isn't drawing (suspended, or a test renderer); the tool may still copy.
|
||||
}
|
||||
if (process.env.SSH_CONNECTION) return;
|
||||
const tool =
|
||||
process.platform === "darwin" ? ["pbcopy"] : process.env.WAYLAND_DISPLAY ? ["wl-copy"] : process.env.DISPLAY ? ["xclip", "-selection", "clipboard"] : null;
|
||||
if (!tool || !Bun.which(tool[0]!)) return;
|
||||
try {
|
||||
const child = Bun.spawn(tool, { stdin: "pipe", stdout: "ignore", stderr: "ignore" });
|
||||
child.stdin.write(text);
|
||||
void child.stdin.end();
|
||||
} catch {
|
||||
// OSC 52 already went out; the tool is a fallback.
|
||||
}
|
||||
}
|
||||
+91
-3
@@ -1,4 +1,4 @@
|
||||
import { type NativeResourceOwner, SyntaxStyle, type ThemeMode } from "@opentui/core";
|
||||
import { type NativeResourceOwner, SyntaxStyle, type TerminalColors, type ThemeMode } from "@opentui/core";
|
||||
import { useRenderer } from "@opentui/react";
|
||||
|
||||
import type { StatusTone } from "../model/threads.ts";
|
||||
@@ -34,6 +34,12 @@ const DARK = {
|
||||
plan: "#fab283",
|
||||
diffAddedBg: "#14261a",
|
||||
diffRemovedBg: "#2a1517",
|
||||
/** The line-number gutter: a shade off the background, deeper beside added and removed lines. */
|
||||
diffGutterBg: "#111111",
|
||||
diffAddedGutterBg: "#1b3322",
|
||||
diffRemovedGutterBg: "#381c1f",
|
||||
diffAddedSign: "#7fd88f",
|
||||
diffRemovedSign: "#e06c75",
|
||||
};
|
||||
|
||||
export type Palette = { readonly [K in keyof typeof DARK]: string };
|
||||
@@ -63,22 +69,102 @@ const LIGHT: Palette = {
|
||||
plan: "#c06a2b",
|
||||
diffAddedBg: "#e3f3e6",
|
||||
diffRemovedBg: "#fbe4e4",
|
||||
diffGutterBg: "#f7f7f7",
|
||||
diffAddedGutterBg: "#cdebd3",
|
||||
diffRemovedGutterBg: "#f5cfcf",
|
||||
diffAddedSign: "#3d9a57",
|
||||
diffRemovedSign: "#d1383d",
|
||||
};
|
||||
|
||||
/** The palette in use. Read at render time, so applyTheme before the first frame sets it everywhere. */
|
||||
export const colors: Palette = { ...DARK };
|
||||
|
||||
export function applyTheme(mode: ThemeMode): void {
|
||||
Object.assign(colors, mode === "light" ? LIGHT : DARK);
|
||||
/** Sets the palette: the dark or light one, or one built with terminalPalette. */
|
||||
export function applyTheme(theme: ThemeMode | Palette): void {
|
||||
Object.assign(colors, theme === "light" ? LIGHT : theme === "dark" ? DARK : theme);
|
||||
markdownStyles = new WeakMap();
|
||||
}
|
||||
|
||||
/** Dark or light, by the background's luminance; null if the terminal didn't say. */
|
||||
export function themeModeOf(terminal: TerminalColors | null): ThemeMode | null {
|
||||
const background = rgb(terminal?.defaultBackground ?? null);
|
||||
if (!background) return null;
|
||||
const [r, g, b] = background;
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b > 127 ? "light" : "dark";
|
||||
}
|
||||
|
||||
/**
|
||||
* The terminal's own colours as a palette: panels and raised blocks a few small steps off
|
||||
* its background, text from its foreground, status hues from its ANSI colours. Null without
|
||||
* a background and foreground; colours it didn't report come from the dark or light palette.
|
||||
*/
|
||||
export function terminalPalette(terminal: TerminalColors | null): Palette | null {
|
||||
const mode = themeModeOf(terminal);
|
||||
const bg = terminal?.defaultBackground;
|
||||
const text = terminal?.defaultForeground;
|
||||
if (!mode || !bg || !text || !rgb(text)) return null;
|
||||
const base = mode === "light" ? LIGHT : DARK;
|
||||
const ansi = (index: number, fallback: string) => (rgb(terminal.palette[index] ?? null) ? terminal.palette[index]! : fallback);
|
||||
// Lighter steps on a dark background, darker on a light one.
|
||||
const step = (amount: number) => mix(bg, mode === "dark" ? "#ffffff" : "#000000", amount);
|
||||
const accent = ansi(12, ansi(4, base.accent));
|
||||
const good = ansi(2, base.good);
|
||||
const bad = ansi(1, base.bad);
|
||||
const cyan = ansi(6, base.info);
|
||||
return {
|
||||
bg,
|
||||
panel: step(0.04),
|
||||
element: step(0.08),
|
||||
elementHover: step(0.12),
|
||||
border: mix(bg, text, 0.22),
|
||||
borderFocused: accent,
|
||||
text,
|
||||
muted: mix(text, bg, 0.4),
|
||||
faint: mix(text, bg, 0.6),
|
||||
accent,
|
||||
user: cyan,
|
||||
userBg: step(0.08),
|
||||
good,
|
||||
bad,
|
||||
warn: ansi(3, base.warn),
|
||||
selectedBg: mix(bg, accent, 0.22),
|
||||
hoverBg: step(0.06),
|
||||
buttonBg: step(0.08),
|
||||
info: cyan,
|
||||
input: ansi(5, base.input),
|
||||
plan: ansi(11, ansi(3, base.plan)),
|
||||
diffAddedBg: mix(bg, good, 0.14),
|
||||
diffRemovedBg: mix(bg, bad, 0.14),
|
||||
diffGutterBg: step(0.03),
|
||||
diffAddedGutterBg: mix(bg, good, 0.26),
|
||||
diffRemovedGutterBg: mix(bg, bad, 0.26),
|
||||
diffAddedSign: good,
|
||||
diffRemovedSign: bad,
|
||||
};
|
||||
}
|
||||
|
||||
/** A `#rrggbb` colour's channels, or null for anything else. */
|
||||
function rgb(hex: string | null): [number, number, number] | null {
|
||||
const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex ?? "");
|
||||
return match ? [Number.parseInt(match[1]!, 16), Number.parseInt(match[2]!, 16), Number.parseInt(match[3]!, 16)] : null;
|
||||
}
|
||||
|
||||
/** `amount` of the way from one colour to another. */
|
||||
function mix(from: string, to: string, amount: number): string {
|
||||
const a = rgb(from)!;
|
||||
const b = rgb(to)!;
|
||||
return `#${a.map((channel, index) => Math.round(channel + (b[index]! - channel) * amount).toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<StatusTone, keyof Palette> = { info: "info", muted: "muted", warn: "warn", input: "input", bad: "bad", good: "good" };
|
||||
export const statusColor = (tone: StatusTone): string => colors[STATUS_COLORS[tone]];
|
||||
|
||||
const TONE_COLORS: Record<Tone, keyof Palette> = { normal: "text", muted: "muted", good: "good", bad: "bad", warn: "warn" };
|
||||
export const toneColor = (tone: Tone): string => colors[TONE_COLORS[tone]];
|
||||
|
||||
/** A scrollbox's bars in the palette: OpenTUI's own track is dark whatever the theme. */
|
||||
export const scrollbarOptions = () => ({ trackOptions: { foregroundColor: colors.muted, backgroundColor: colors.element } });
|
||||
|
||||
let markdownStyles = new WeakMap<NativeResourceOwner, SyntaxStyle>();
|
||||
|
||||
/** One per renderer: a SyntaxStyle belongs to the renderer's native scene that created it. */
|
||||
@@ -100,6 +186,8 @@ export function useMarkdownStyle(): SyntaxStyle {
|
||||
"markup.quote": { fg: colors.muted, italic: true },
|
||||
"markup.raw": { fg: colors.plan },
|
||||
"markup.raw.block": { fg: colors.text },
|
||||
// Attachments and mentions in the message box.
|
||||
"extmark.chip": { fg: colors.accent, bg: colors.element },
|
||||
}, owner);
|
||||
markdownStyles.set(owner, style);
|
||||
return style;
|
||||
|
||||
+31
-25
@@ -1,11 +1,11 @@
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { T3Session } from "../client/session.ts";
|
||||
import { attachmentLine, checkAttachment, clipboardImageCommands, expandAttachmentPath } from "../model/attachments.ts";
|
||||
import { attachmentLine, checkAttachment, expandAttachmentPath, isRemoteTerminal, pastedImageName } from "../model/attachments.ts";
|
||||
import type { PaletteCommand } from "../model/palette.ts";
|
||||
import type { Clipboard } from "./clipboard.ts";
|
||||
import type { Confirmation } from "./ConfirmBar.tsx";
|
||||
|
||||
export interface Attachments {
|
||||
@@ -16,6 +16,10 @@ export interface Attachments {
|
||||
readonly commands: readonly (PaletteCommand & { readonly run: () => void })[];
|
||||
/** Prompts for a path and uploads it; the `a` key and the palette both call this. */
|
||||
readonly attachFile: () => void;
|
||||
/** Uploads the file at this path, as a pasted or dropped path does. */
|
||||
readonly attachPath: (path: string) => void;
|
||||
/** Attaches the clipboard's image; with `insert`, its text goes there when there is no image. */
|
||||
readonly paste: (insert?: (text: string) => void) => void;
|
||||
readonly remove: (attachment: ChatAttachment) => void;
|
||||
/** Hands the pending attachments to a send and clears them. */
|
||||
readonly take: () => readonly ChatAttachment[];
|
||||
@@ -29,6 +33,7 @@ export interface Attachments {
|
||||
*/
|
||||
export function useAttachments(deps: {
|
||||
readonly session: T3Session;
|
||||
readonly clipboard: Clipboard;
|
||||
/** The composer they belong to; switching threads keeps each one's list. */
|
||||
readonly composerKey: string;
|
||||
/** Relative paths resolve here: the thread's worktree or project folder. */
|
||||
@@ -38,7 +43,7 @@ export function useAttachments(deps: {
|
||||
readonly confirm: (confirmation: Confirmation) => void;
|
||||
readonly say: (text: string, bad?: boolean) => void;
|
||||
}): Attachments {
|
||||
const { session, composerKey, cwd, maxFileBytes, confirm, say } = deps;
|
||||
const { session, clipboard, composerKey, cwd, maxFileBytes, confirm, say } = deps;
|
||||
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
|
||||
const pending = byComposer.get(composerKey) ?? [];
|
||||
|
||||
@@ -74,6 +79,17 @@ export function useAttachments(deps: {
|
||||
);
|
||||
};
|
||||
|
||||
const attachPath = (path: string) => {
|
||||
void (async () => {
|
||||
const info = await stat(path);
|
||||
if (!info.isFile()) throw new Error("not a file");
|
||||
return readFile(path);
|
||||
})().then(
|
||||
(bytes) => upload(path, bytes, Bun.file(path).type || undefined),
|
||||
() => say(`Could not read ${path}.`, true),
|
||||
);
|
||||
};
|
||||
|
||||
const attachFile = () =>
|
||||
confirm({
|
||||
title: "Attach file",
|
||||
@@ -81,30 +97,18 @@ export function useAttachments(deps: {
|
||||
message: { placeholder: "~/screenshot.png or ./report.pdf" },
|
||||
confirmLabel: "attach",
|
||||
run: (text) => {
|
||||
const path = text.trim();
|
||||
if (!path) return;
|
||||
const resolved = expandAttachmentPath(path, cwd);
|
||||
void (async () => {
|
||||
const info = await stat(resolved);
|
||||
if (!info.isFile()) throw new Error("not a file");
|
||||
return readFile(resolved);
|
||||
})().then(
|
||||
(bytes) => upload(resolved, bytes, Bun.file(resolved).type || undefined),
|
||||
() => say(`Could not read ${resolved}.`, true),
|
||||
);
|
||||
if (text.trim()) attachPath(expandAttachmentPath(text, cwd));
|
||||
},
|
||||
});
|
||||
|
||||
const pasteImage = () => {
|
||||
let missing = true;
|
||||
for (const [command, ...args] of clipboardImageCommands(process.platform)) {
|
||||
const result = spawnSync(command!, args, { maxBuffer: 64 * 1024 * 1024 });
|
||||
if (result.error && (result.error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
||||
missing = false;
|
||||
if (result.status === 0 && result.stdout.length > 0) return upload("pasted-image.png", result.stdout, "image/png");
|
||||
break;
|
||||
}
|
||||
say(missing ? "No clipboard image tool found (wl-paste, xclip, or pngpaste)." : "No image on the clipboard.", true);
|
||||
const paste = (insert?: (text: string) => void) => {
|
||||
if (isRemoteTerminal(process.env)) return say("Over SSH the clipboard is on the other machine; attach the file with a.", true);
|
||||
void clipboard.readImage().then(async (image) => {
|
||||
if (typeof image !== "string") return upload(pastedImageName(image.mimeType), image.bytes, image.mimeType);
|
||||
const text = insert ? await clipboard.readText() : null;
|
||||
if (text) return insert?.(text);
|
||||
say(image === "no-tool" ? "No clipboard image tool found (wl-paste, xclip, pngpaste or osascript)." : "No image on the clipboard.", true);
|
||||
});
|
||||
};
|
||||
|
||||
const remove = (attachment: ChatAttachment) => {
|
||||
@@ -121,7 +125,7 @@ export function useAttachments(deps: {
|
||||
|
||||
const commands: Attachments["commands"][number][] = [
|
||||
{ id: "attach-file", title: "Attach file…", shortcut: "a", keywords: ["attachment", "image", "upload", "file"], run: attachFile },
|
||||
{ id: "attach-paste-image", title: "Paste image from clipboard", keywords: ["attachment", "image", "screenshot", "clipboard"], run: pasteImage },
|
||||
{ id: "attach-paste-image", title: "Paste image from clipboard", keywords: ["attachment", "image", "screenshot", "clipboard"], run: () => paste() },
|
||||
...pending.map((attachment) => ({
|
||||
id: `attach-remove:${attachment.id}`,
|
||||
title: `Remove attachment: ${attachment.name}`,
|
||||
@@ -135,6 +139,8 @@ export function useAttachments(deps: {
|
||||
line: attachmentLine(pending),
|
||||
commands,
|
||||
attachFile,
|
||||
attachPath,
|
||||
paste,
|
||||
remove,
|
||||
take: () => {
|
||||
const taken = byComposer.get(composerKey) ?? [];
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { Extmark, TextareaRenderable } from "@opentui/core";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
|
||||
/** What a chip stands for: an attachment, which the sent text leaves out, or a mention, sent as `sent`. */
|
||||
interface ChipData {
|
||||
readonly attachmentId?: string;
|
||||
readonly sent?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes `start`–`end` of the composer (in its cursor offsets) one chip: drawn in the accent
|
||||
* colour, stepped over by the cursor and deleted whole by backspace.
|
||||
*/
|
||||
export function markChip(composer: TextareaRenderable, start: number, end: number, data: ChipData): void {
|
||||
const extmarks = composer.extmarks;
|
||||
const typeId = extmarks.getTypeId("chip") ?? extmarks.registerType("chip");
|
||||
const styleId = composer.syntaxStyle?.getStyleId("extmark.chip");
|
||||
extmarks.create({ start, end, virtual: true, typeId, data, ...(styleId ? { styleId } : {}) });
|
||||
}
|
||||
|
||||
/** Inserts `label` at the cursor as a chip, apart from the words either side. */
|
||||
function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void {
|
||||
const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1];
|
||||
if (before && !/\s/.test(before)) composer.insertText(" ");
|
||||
const start = composer.cursorOffset;
|
||||
composer.insertText(label);
|
||||
markChip(composer, start, composer.cursorOffset, data);
|
||||
composer.insertText(" ");
|
||||
}
|
||||
|
||||
function chipsOf(composer: TextareaRenderable): Extmark[] {
|
||||
const typeId = composer.extmarks.getTypeId("chip");
|
||||
return typeId === null ? [] : composer.extmarks.getAllForTypeId(typeId);
|
||||
}
|
||||
|
||||
const attachmentChips = (composer: TextareaRenderable) => chipsOf(composer).filter((chip) => (chip.data as ChipData | undefined)?.attachmentId);
|
||||
|
||||
/** The index in `text` of a cursor offset, which counts columns, and one for each line break. */
|
||||
function indexAtOffset(text: string, offset: number): number {
|
||||
let column = 0;
|
||||
let index = 0;
|
||||
for (const char of text) {
|
||||
if (column >= offset) break;
|
||||
column += char === "\n" ? 1 : Bun.stringWidth(char);
|
||||
index += char.length;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/** The composer's text as it is sent and kept as a draft: mentions as they're sent, attachments (and the space after each) left out. */
|
||||
export function composerText(composer: TextareaRenderable): string {
|
||||
const text = composer.plainText;
|
||||
let kept = "";
|
||||
let from = 0;
|
||||
for (const chip of chipsOf(composer).sort((a, b) => a.start - b.start)) {
|
||||
const data = (chip.data ?? {}) as ChipData;
|
||||
const start = indexAtOffset(text, chip.start);
|
||||
let end = indexAtOffset(text, chip.end);
|
||||
if (data.attachmentId && text[end] === " ") end++;
|
||||
kept += text.slice(from, start) + (data.sent ?? "");
|
||||
from = end;
|
||||
}
|
||||
return kept + text.slice(from);
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer's attachments as chips, `[image 1]` or `[report.pdf]`: each pending one gets a
|
||||
* chip at the cursor, removing an attachment takes its chip out, and deleting a chip removes
|
||||
* its attachment. Replace the text through `replaceText`, so the old chips going with the old
|
||||
* text doesn't count as deleting them.
|
||||
*/
|
||||
export function useComposerChips(deps: {
|
||||
readonly composerRef: RefObject<TextareaRenderable | null>;
|
||||
readonly composerKey: string;
|
||||
readonly pending: readonly ChatAttachment[];
|
||||
readonly remove: (attachment: ChatAttachment) => void;
|
||||
}) {
|
||||
const { composerRef, composerKey, pending } = deps;
|
||||
/** The attachments with a chip in the composer as it is now. */
|
||||
const shown = useRef(new Set<string>());
|
||||
/** Bumped when the text is replaced, so the chips go back in. */
|
||||
const [replaced, setReplaced] = useState(0);
|
||||
|
||||
// A new composer, new attachments or new text: each needs its chips.
|
||||
useEffect(() => {
|
||||
const composer = composerRef.current;
|
||||
if (!composer) return;
|
||||
const chips = attachmentChips(composer);
|
||||
const present = new Set(chips.map((chip) => (chip.data as ChipData).attachmentId));
|
||||
for (const chip of chips) {
|
||||
if (pending.some((attachment) => attachment.id === (chip.data as ChipData).attachmentId)) continue;
|
||||
composer.extmarks.delete(chip.id);
|
||||
removeRange(composer, chip.start, chip.end);
|
||||
}
|
||||
let images = 0;
|
||||
for (const attachment of pending) {
|
||||
if (attachment.type === "image") images++;
|
||||
if (!present.has(attachment.id)) insertChip(composer, attachment.type === "image" ? `[image ${images}]` : `[${attachment.name}]`, { attachmentId: attachment.id });
|
||||
}
|
||||
shown.current = new Set(pending.map((attachment) => attachment.id));
|
||||
}, [composerKey, pending, replaced]);
|
||||
|
||||
return {
|
||||
/** The text changed: an attachment whose chip was deleted goes too. */
|
||||
sync: () => {
|
||||
const composer = composerRef.current;
|
||||
if (!composer) return;
|
||||
const present = new Set(attachmentChips(composer).map((chip) => (chip.data as ChipData).attachmentId));
|
||||
for (const attachment of pending) {
|
||||
if (!shown.current.has(attachment.id) || present.has(attachment.id)) continue;
|
||||
shown.current.delete(attachment.id);
|
||||
deps.remove(attachment);
|
||||
}
|
||||
},
|
||||
/** Sets the composer's text, then puts the attachment chips back. */
|
||||
replaceText: (composer: TextareaRenderable, text: string) => {
|
||||
shown.current.clear();
|
||||
composer.setText(text);
|
||||
setReplaced((count) => count + 1);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Deletes the text between two cursor offsets, and the space after it, keeping the cursor where it was. */
|
||||
function removeRange(composer: TextareaRenderable, start: number, end: number): void {
|
||||
const cursor = composer.cursorOffset;
|
||||
const stop = end + (composer.plainText[indexAtOffset(composer.plainText, end)] === " " ? 1 : 0);
|
||||
composer.cursorOffset = start;
|
||||
const from = composer.logicalCursor;
|
||||
composer.cursorOffset = stop;
|
||||
const to = composer.logicalCursor;
|
||||
composer.deleteRange(from.row, from.col, to.row, to.col);
|
||||
composer.cursorOffset = cursor >= stop ? cursor - (stop - start) : Math.min(cursor, start);
|
||||
}
|
||||
@@ -3,8 +3,9 @@ import type { ComposerContextRecord, EnvironmentId, OrchestrationMessageContext,
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
|
||||
import type { T3Session } from "../client/session.ts";
|
||||
import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
|
||||
import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
|
||||
import { keys, type Binding } from "../model/keymap.ts";
|
||||
import { markChip } from "./useComposerChips.ts";
|
||||
import { useComposerPullRequests } from "./usePullRequests.ts";
|
||||
|
||||
/**
|
||||
@@ -96,10 +97,17 @@ export function useComposerMenu(deps: {
|
||||
const choose = (item: ComposerItem | undefined) => {
|
||||
const composer = composerRef.current;
|
||||
if (!item || !trigger || !composer) return;
|
||||
const next = applyComposerItem(state.text, trigger, item.replacement ?? "");
|
||||
composer.setText(next.text);
|
||||
const at = cursorAtIndex(next.text, next.cursor);
|
||||
composer.setCursor(at.row, at.col);
|
||||
// An edit in place rather than new text, which would take the chips already there with it.
|
||||
const replacement = item.replacement ?? "";
|
||||
const from = cursorAtIndex(state.text, trigger.rangeStart);
|
||||
const to = cursorAtIndex(state.text, composerItemEnd(state.text, trigger, replacement));
|
||||
composer.deleteRange(from.row, from.col, to.row, to.col);
|
||||
composer.setCursor(from.row, from.col);
|
||||
const sent = replacement.trimEnd();
|
||||
const start = composer.cursorOffset;
|
||||
composer.insertText(item.chip ?? sent);
|
||||
if (item.chip) markChip(composer, start, composer.cursorOffset, { sent });
|
||||
composer.insertText(replacement.slice(sent.length));
|
||||
if (item.record) {
|
||||
const records = mentions.current.get(composerKey) ?? new Map<string, ComposerContextRecord>();
|
||||
records.set(item.record.contextId, item.record);
|
||||
|
||||
@@ -42,6 +42,8 @@ export function useDetails(deps: {
|
||||
/** A step of a running git action, shown until the next. */
|
||||
readonly progress: (text: string) => void;
|
||||
readonly openThread: (id: ThreadId) => void;
|
||||
/** A changed file in $EDITOR, in the terminal pane. */
|
||||
readonly editFile: (path: string, cwd: string | null) => void;
|
||||
/** The panel takes the keys, or gives them back. */
|
||||
readonly focus: (focused: boolean) => void;
|
||||
}) {
|
||||
@@ -193,6 +195,11 @@ export function useDetails(deps: {
|
||||
deps.focus(false);
|
||||
};
|
||||
const selectedAction = () => actions.find((candidate) => candidate.id === selected);
|
||||
const selectedFile = (() => {
|
||||
const action = selectedAction();
|
||||
return action?.kind === "diff" && action.path && !action.path.endsWith("/") ? action.path : null;
|
||||
})();
|
||||
const edit = (path: string) => deps.editFile(path, cwd);
|
||||
|
||||
const focusKey: Binding = { keys: ["l", "→"], run: focus, hint: "details", ...(thread ? { command: { id: "focus-details", title: "Focus thread details" } } : {}) };
|
||||
const toggleKey: Binding = { keys: ["d"], run: () => setPref(!show), command: { id: "details", title: show ? "Hide thread details" : "Show thread details", keywords: ["panel", "info"] } };
|
||||
@@ -232,11 +239,12 @@ export function useDetails(deps: {
|
||||
},
|
||||
hint: "toggle automation",
|
||||
},
|
||||
selectedFile && { keys: ["o"], run: () => edit(selectedFile), hint: "edit file" },
|
||||
{ keys: ["esc"], run: () => (deps.diff ? setDiff(null) : leave()), hint: "back" },
|
||||
{ keys: ["h", "←"], run: leave },
|
||||
);
|
||||
|
||||
return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, unfolded, activateById, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } };
|
||||
return { show, setPref, cwd, details, loading: vcsState?.status !== "live", selected, unfolded, activateById, edit, leave, keys: { focus: focusKey, toggle: toggleKey, commands, focused } };
|
||||
}
|
||||
|
||||
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
||||
@@ -39,13 +39,15 @@ import {
|
||||
} from "../model/pullRequests.ts";
|
||||
import type { Confirmation } from "./ConfirmBar.tsx";
|
||||
import { editInEditor } from "./editor.ts";
|
||||
import { copyText } from "./terminalOut.ts";
|
||||
import type { Clipboard } from "./clipboard.ts";
|
||||
import { openInBrowser } from "./links.ts";
|
||||
import { firstLine } from "./text.ts";
|
||||
import type { PullRequestViewState } from "./PullRequestView.tsx";
|
||||
|
||||
export interface PullRequestDeps {
|
||||
readonly session: T3Session;
|
||||
readonly renderer: CliRenderer;
|
||||
readonly clipboard: Clipboard;
|
||||
readonly threadShell: OrchestrationV2ThreadShell | undefined;
|
||||
readonly project: OrchestrationProjectShell | undefined;
|
||||
readonly projects: readonly OrchestrationProjectShell[];
|
||||
@@ -157,23 +159,15 @@ export function usePullRequests(deps: PullRequestDeps) {
|
||||
})();
|
||||
};
|
||||
|
||||
const openInBrowser = () => {
|
||||
const openPullRequest = () => {
|
||||
const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
|
||||
if (!url) return;
|
||||
// Over SSH or without a desktop there may be no browser to open: copy the link instead.
|
||||
const fallBack = (reason: string) => {
|
||||
copyText(deps.renderer, url);
|
||||
void deps.clipboard.copy(url);
|
||||
deps.say(`Could not open the browser (${reason}); link copied: ${url}`, true);
|
||||
};
|
||||
try {
|
||||
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
||||
const child = Bun.spawn([opener, url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
void child.exited.then((code) => {
|
||||
if (code !== 0) fallBack(`${opener} exited with ${code}`);
|
||||
});
|
||||
} catch (error) {
|
||||
fallBack(messageOf(error));
|
||||
}
|
||||
openInBrowser(url, fallBack);
|
||||
};
|
||||
|
||||
const reloadQuietly = () => {
|
||||
@@ -432,7 +426,7 @@ export function usePullRequests(deps: PullRequestDeps) {
|
||||
const current = loaded;
|
||||
const viewKeys: Binding[] = current
|
||||
? keys(
|
||||
{ keys: ["o"], run: openInBrowser, hint: "open" },
|
||||
{ keys: ["o"], run: openPullRequest, hint: "open" },
|
||||
{ keys: ["r"], run: refresh, hint: "refresh" },
|
||||
current.detail && [
|
||||
{ keys: ["c"], run: comment, hint: "comment" },
|
||||
@@ -478,7 +472,7 @@ export function usePullRequests(deps: PullRequestDeps) {
|
||||
commands.push({ id: "pr-comment", title: `Comment on pull request #${number}`, shortcut: "c", keywords: ["comment", "pull request"], run: comment });
|
||||
commands.push({ id: "pr-review", title: `Review pull request #${number}…`, shortcut: "R", keywords: ["review", "approve", "request changes"], run: review });
|
||||
commands.push({ id: "pr-actions", title: `Pull request #${number} actions…`, shortcut: "a", keywords: ["merge", "close", "ready", "draft"], run: actions });
|
||||
commands.push({ id: "pr-open", title: `Open pull request #${number} in browser`, shortcut: "o", keywords: ["open", "browser"], run: openInBrowser });
|
||||
commands.push({ id: "pr-open", title: `Open pull request #${number} in browser`, shortcut: "o", keywords: ["open", "browser"], run: openPullRequest });
|
||||
commands.push({ id: "pr-refresh", title: "Refresh pull request", shortcut: "r", keywords: ["refresh", "reload"], run: refresh });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { CliRenderer } from "@opentui/core";
|
||||
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
|
||||
import type { ContextMenuItem, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
@@ -8,14 +7,14 @@ import type { Binding } from "../model/keymap.ts";
|
||||
import type { Picker, PickerItem } from "../model/palette.ts";
|
||||
import { parseSnooze, pickSnooze, threadHasRuntime, threadMenu, topPinOrderKey, type ThreadActionMenuId } from "../model/threadMenu.ts";
|
||||
import type { Confirmation } from "./ConfirmBar.tsx";
|
||||
import { copyText } from "./terminalOut.ts";
|
||||
import type { Clipboard } from "./clipboard.ts";
|
||||
|
||||
type SnoozePresets = ReturnType<typeof threadMenu>["snoozePresets"];
|
||||
|
||||
/** The web sidebar's thread menu as a picker: separators become groups, submenus open their own picker. */
|
||||
export function useThreadMenu(deps: {
|
||||
readonly session: T3Session;
|
||||
readonly renderer: CliRenderer;
|
||||
readonly clipboard: Clipboard;
|
||||
readonly snapshot: OrchestrationV2ShellSnapshot | null;
|
||||
readonly config: ServerConfig | null;
|
||||
readonly timestampFormat: T3tuiConfig["timestampFormat"];
|
||||
@@ -34,10 +33,10 @@ export function useThreadMenu(deps: {
|
||||
readonly keepUnread: (id: ThreadId) => void;
|
||||
readonly startDraftOn: (target: OrchestrationV2ThreadShell) => void;
|
||||
}) {
|
||||
const { session, renderer, config, run, say } = deps;
|
||||
const { session, clipboard, config, run, say } = deps;
|
||||
|
||||
const copy = (text: string, message: string) => {
|
||||
copyText(renderer, text);
|
||||
void clipboard.copy(text);
|
||||
say(message);
|
||||
};
|
||||
|
||||
|
||||
+24
-6
@@ -10,7 +10,7 @@ import type { PaletteCommand, Picker, PickerItem } from "../model/palette.ts";
|
||||
import { newTerminalInput, preferredEditor, resolveBranchSelectionTarget, worktreeSetupNote } from "../model/workspace.ts";
|
||||
import type { Confirmation } from "./ConfirmBar.tsx";
|
||||
import { splitPatch, type DiffState } from "./DiffView.tsx";
|
||||
import { attachTerminal } from "./terminalAttach.ts";
|
||||
import { attachTerminal, type TerminalTarget } from "./terminalAttach.ts";
|
||||
|
||||
type Command = PaletteCommand & { readonly run: () => void };
|
||||
|
||||
@@ -25,6 +25,8 @@ export function useWorkspace(input: {
|
||||
readonly draft: boolean;
|
||||
readonly diff: DiffState | null;
|
||||
readonly openPicker: (picker: Picker) => void;
|
||||
/** Shows a terminal in the pane beside the conversation. */
|
||||
readonly openPane: (target: TerminalTarget) => void;
|
||||
readonly confirm: (confirmation: Confirmation) => void;
|
||||
readonly run: (label: string, action: () => Promise<unknown>) => void;
|
||||
readonly say: (message: string, bad?: boolean) => void;
|
||||
@@ -76,23 +78,35 @@ export function useWorkspace(input: {
|
||||
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
|
||||
const cwd = thread?.worktreePath ?? project?.workspaceRoot;
|
||||
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
|
||||
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
|
||||
/** In the pane, or with the whole screen. */
|
||||
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">, fullScreen = false) => {
|
||||
if (!thread) return;
|
||||
const target = {
|
||||
threadId: thread.id,
|
||||
...terminal,
|
||||
label: resolveTerminalSessionLabel(terminal.terminalId, terminal),
|
||||
};
|
||||
if (!fullScreen) return input.openPane(target);
|
||||
void attachTerminal(renderer, session, target, (message) => {
|
||||
if (message) say(message);
|
||||
});
|
||||
};
|
||||
const newTerminal = () => {
|
||||
const newTerminal = (fullScreen = false) => {
|
||||
if (!thread || !project) return say("Open a thread with a project folder first.", true);
|
||||
const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live");
|
||||
run("Terminal opened", async () => {
|
||||
await session.openTerminal(request);
|
||||
enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" });
|
||||
enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" }, fullScreen);
|
||||
});
|
||||
};
|
||||
/** The old way in: the terminal takes the screen until ctrl+j. */
|
||||
const attachFullScreen = () => {
|
||||
if (!thread || input.draft) return say("Open a thread first.", true);
|
||||
if (threadTerminals.length === 0) return newTerminal(true);
|
||||
if (threadTerminals.length === 1) return enterTerminal(threadTerminals[0]!, true);
|
||||
openPicker({
|
||||
placeholder: "Attach full screen",
|
||||
groups: [{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:full:${terminal.terminalId}`, title: label(terminal), run: () => enterTerminal(terminal, true) })) }],
|
||||
});
|
||||
};
|
||||
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
|
||||
@@ -114,7 +128,10 @@ export function useWorkspace(input: {
|
||||
};
|
||||
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
|
||||
const terminalActionItems = (): PickerItem[] => {
|
||||
const items: PickerItem[] = [{ id: "terminal:new", title: "New terminal", run: newTerminal }];
|
||||
const items: PickerItem[] = [
|
||||
{ id: "terminal:new", title: "New terminal", run: () => newTerminal() },
|
||||
{ id: "terminal:full-screen", title: "Attach full screen", hint: "ctrl+j returns", run: attachFullScreen },
|
||||
];
|
||||
for (const action of ["close", "clear"] as const) {
|
||||
const targets = terminalItems(action);
|
||||
if (targets.length === 0) continue;
|
||||
@@ -269,7 +286,8 @@ export function useWorkspace(input: {
|
||||
const commands: Command[] = thread && !input.draft ? [
|
||||
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
|
||||
{ id: "terminal-picker", title: "Terminals…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker },
|
||||
{ id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: newTerminal },
|
||||
{ id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: () => newTerminal() },
|
||||
{ id: "terminal-full-screen", title: "Attach terminal full screen", keywords: ["shell", "console", "attach"], run: attachFullScreen },
|
||||
...terminalItems("close"), ...terminalItems("clear"),
|
||||
{ id: "branches", title: "Branches and worktrees…", shortcut: "b", keywords: ["git", "switch", "ref", "create", "remove", "pull"], run: branchPicker },
|
||||
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
|
||||
|
||||
Reference in new issue
Block a user