Paste and drop images into the composer, and show sent images inline

Clipboard images come through OpenTUI's clipboard service, with wl-paste, xclip,
pngpaste and osascript behind it for any image type. ctrl+v or an empty bracketed
paste attaches the image; a pasted image path attaches the file. Over SSH it points
at a instead. User messages draw their image attachments with <image>.
This commit is contained in:
Callum Alpass committed 2026-11-03 03:04:00 +11:00
1 parent 4ef243875f
commit 4e3717d171
11 files changed
+461 -45

No files matched your search

+18
View File
@@ -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 }));
+68 -4
View File
@@ -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 };
+16 -2
View File
@@ -1,4 +1,4 @@
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";
@@ -11,6 +11,7 @@ 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 { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts";
import { saveLayout, type Layout } from "../layout.ts";
@@ -45,6 +46,7 @@ import { PullRequestView } from "./PullRequestView.tsx";
import { SettingsView } from "./SettingsView.tsx";
import { useWorkspace } from "./useWorkspace.ts";
import { usePullRequests } from "./usePullRequests.ts";
import { rendererClipboard, type Clipboard } from "./clipboard.ts";
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
import { colors, statusColor } from "./theme.ts";
import { BAR, NO_BORDER } from "./edges.ts";
@@ -103,10 +105,11 @@ 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 { width, height } = useTerminalDimensions();
const [shell, setShell] = useState<ShellState>(session.getShell());
// Any thread, listed or not: subagents open here too.
@@ -419,6 +422,7 @@ 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,
@@ -894,6 +898,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"),
);
@@ -1308,6 +1313,15 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
wrapMode="word"
keyBindings={[...COMPOSER_KEYS[config.sendShortcut]]}
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();
+44 -5
View File
@@ -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";
@@ -175,7 +175,7 @@ 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)}>
@@ -308,7 +308,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 +319,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>
);
}
+54
View File
@@ -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";
}
+31 -25
View File
@@ -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) ?? [];