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

+1
View File
@@ -51,6 +51,7 @@ The keys you'll use most:
| `ctrl+j` | the thread's terminal on the server, in a pane beside the conversation |
| `ctrl+\` | move the keys between the pane and the conversation |
| `ctrl+g` | write the message in `$EDITOR`, in the pane |
| `ctrl+v` | in the message box: attach the clipboard's image (or paste its text) |
| `ctrl+c` | quit |
In the message box, `/`, `$`, `@` and `#` suggest commands, skills, files and threads, and pull requests. Most things also work with the mouse.
+5 -1
View File
@@ -76,6 +76,8 @@ Navigation:
`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`) in the terminal pane; save and quit to bring it back.
`ctrl+v` attaches the clipboard's image, or pastes its text when there is no image. Pasting or dropping the path of an image file (quoted, as a `file://` URL, or with `\ ` before spaces) attaches the file rather than typing the path. See [Attachments](#attachments).
With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off and releases messages held in the queue.
Typing a trigger opens a list of suggestions above the box:
@@ -137,7 +139,9 @@ Submenus open as their own list, and typing finds their items from the top (`thr
## Attachments
`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `Paste image from clipboard` in the palette takes a clipboard image instead (`wl-paste`, `xclip`, or `pngpaste` on macOS). Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone.
`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `ctrl+v` in the message box, or `Paste image from clipboard` in the palette, takes the clipboard's image instead (PNG, JPEG, WebP or GIF), as does a paste that comes through empty, which is how many terminals pass on a copied image. The clipboard is read through OpenTUI, then `wl-paste` or `xclip` (or `pngpaste` or `osascript` on macOS) when that finds nothing it can read. Over SSH the clipboard is on the other machine, so use `a` there. Pasting an image file's path attaches the file. Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone.
Sent images show in their message, up to 12 rows tall, through kitty or sixel graphics where the terminal has them and as coloured blocks elsewhere; the file's name is under each.
Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other files up to the server's limit (50 MB at most), and 100 attachments per message.
+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) ?? [];
+30 -4
View File
@@ -9,6 +9,7 @@ import type { ConnectionStatus, T3Session } from "../../src/client/session.ts";
import { DEFAULT_CONFIG, type T3tuiConfig } from "../../src/config.ts";
import type { Layout } from "../../src/layout.ts";
import { App } from "../../src/ui/App.tsx";
import type { Clipboard, ClipboardImage } from "../../src/ui/clipboard.ts";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
export { v2Projection, v2ShellSnapshot, v2ThreadId };
@@ -45,6 +46,8 @@ export function fakeSession(
readonly terminals?: readonly unknown[];
readonly terminalEvents?: readonly unknown[];
readonly failures?: Record<string, string>;
/** The server's config; loading by default. */
readonly serverConfig?: unknown;
} = {},
) {
const calls: Call[] = [];
@@ -58,7 +61,7 @@ export function fakeSession(
getShell: () => ({ status: state.status ?? { type: "live" }, snapshot, serverUrl: "ws://test" }),
onShell: () => () => {},
watchThread: (_id: ThreadId, listener: (value: unknown) => void) => live({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } })(listener),
watchServerConfig: live({ status: "loading", config: null }),
watchServerConfig: live(state.serverConfig ? { status: "live", config: state.serverConfig } : { status: "loading", config: null }),
watchServers: live({ status: "live", items: [] }),
watchAutomations: live({ status: "live", items: [] }),
watchTerminals: live({ status: "live", items: state.terminals ?? [] }),
@@ -86,10 +89,28 @@ export function fakeSession(
}
/** Renders the whole app against a fake session, with helpers to drive it by key and mouse. */
export async function renderApp(options: { readonly session?: ReturnType<typeof fakeSession>; readonly config?: Partial<T3tuiConfig>; readonly layout?: Layout; readonly width?: number; readonly height?: number } = {}) {
export async function renderApp(
options: {
readonly session?: ReturnType<typeof fakeSession>;
readonly config?: Partial<T3tuiConfig>;
readonly layout?: Layout;
readonly width?: number;
readonly height?: number;
/** What the clipboard holds; copies to it are recorded as "copy" calls. */
readonly clipboard?: { readonly image?: ClipboardImage; readonly text?: string };
} = {},
) {
const fake = options.session ?? fakeSession();
const config = { ...DEFAULT_CONFIG, ...options.config };
const rig = await testRender(<App session={fake.session} config={config} {...(options.layout ? { layout: options.layout } : {})} />, { width: options.width ?? 140, height: options.height ?? 40 });
const clipboard: Clipboard = {
readImage: async () => options.clipboard?.image ?? "empty",
readText: async () => options.clipboard?.text ?? null,
copy: async (text) => {
fake.calls.push({ method: "copy", args: [text] });
return true;
},
};
const rig = await testRender(<App session={fake.session} config={config} clipboard={clipboard} {...(options.layout ? { layout: options.layout } : {})} />, { width: options.width ?? 140, height: options.height ?? 40 });
// The app runs on timers and subscriptions, as it does live: tests wait for frames rather than wrap each update in act().
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;
const keys = createMockKeys(rig.renderer);
@@ -121,6 +142,11 @@ export async function renderApp(options: { readonly session?: ReturnType<typeof
await keys.typeText(text);
await settle();
};
/** A bracketed paste, as a terminal sends one. */
const paste = async (text: string) => {
await keys.pasteBracketedText(text);
await settle();
};
const click = async (x: number, y: number, button: 0 | 2 = 0) => {
await rig.mockMouse.click(x, y, button);
await settle();
@@ -139,5 +165,5 @@ export async function renderApp(options: { readonly session?: ReturnType<typeof
};
const calls = (method: string) => fake.calls.filter((call) => call.method === method);
const destroy = () => rig.renderer.destroy();
return { ...rig, session: fake.session, press, type, click, settle, frame, hints, find, calls, destroy };
return { ...rig, session: fake.session, press, type, paste, click, settle, frame, hints, find, calls, destroy };
}
+129
View File
@@ -0,0 +1,129 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { withCompletedTurn } from "./fixtures.ts";
import { fakeSession, renderApp } from "./harness.tsx";
let app: Awaited<ReturnType<typeof renderApp>> | null = null;
const open = async (...args: Parameters<typeof renderApp>) => (app = await renderApp(...args));
afterEach(() => {
app?.destroy();
app = null;
});
/** A 1×1 PNG. */
const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0));
const uploaded = { type: "image", id: "att-1", name: "pasted-image.jpg", mimeType: "image/jpeg", sizeBytes: PNG.length };
const withUploads = () => fakeSession({ serverConfig: { providers: [], settings: {}, environment: { capabilities: { fileAttachments: { maxUploadBytes: 1 << 20 } } } }, results: { uploadAttachment: uploaded } });
describe("pasting images", () => {
test("ctrl+v in the composer attaches the clipboard's image, whatever its type", async () => {
const app = await open({ session: withUploads(), clipboard: { image: { bytes: PNG, mimeType: "image/jpeg" } } });
await app.press("i");
await app.press("v", { ctrl: true });
const [call] = app.calls("uploadAttachment");
expect(call?.args[0]).toMatchObject({ name: "pasted-image.jpg", mimeType: "image/jpeg" });
expect(app.frame()).toContain("pasted-image.jpg ✕");
});
test("an empty bracketed paste is a copied image the terminal couldn't send", async () => {
const app = await open({ session: withUploads(), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.paste("");
expect(app.calls("uploadAttachment")[0]?.args[0]).toMatchObject({ name: "pasted-image.png", mimeType: "image/png" });
});
test("with no image, ctrl+v pastes the clipboard's text", async () => {
const app = await open({ clipboard: { text: "copied words" } });
await app.press("i");
await app.press("v", { ctrl: true });
expect(app.calls("uploadAttachment")).toHaveLength(0);
expect(app.frame()).toContain("copied words");
});
test("an empty clipboard says so", async () => {
const app = await open();
await app.press("i");
await app.press("v", { ctrl: true });
expect(app.hints()).toBe("No image on the clipboard.");
});
test("over SSH the clipboard is out of reach, so it points at a", async () => {
const previous = process.env.SSH_CONNECTION;
process.env.SSH_CONNECTION = "10.0.0.2 50000 10.0.0.1 22";
try {
const app = await open({ clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.press("v", { ctrl: true });
expect(app.hints()).toBe("Over SSH the clipboard is on the other machine; attach the file with a.");
expect(app.calls("uploadAttachment")).toHaveLength(0);
} finally {
if (previous === undefined) delete process.env.SSH_CONNECTION;
else process.env.SSH_CONNECTION = previous;
}
});
});
describe("pasting paths", () => {
const dir = mkdtempSync(join(tmpdir(), "t3tui-images-"));
const shot = join(dir, "my shot.png");
writeFileSync(shot, PNG);
test("a dropped image file is attached rather than typed", async () => {
const app = await open({ session: withUploads() });
await app.press("i");
await app.paste(`'${shot}'`);
await app.settle(50);
expect(app.calls("uploadAttachment")[0]?.args[0]).toMatchObject({ name: "my shot.png", mimeType: "image/png" });
expect(app.frame()).not.toContain("t3tui-images-");
});
test("escaped spaces and file:// URLs work too", async () => {
const app = await open({ session: withUploads() });
await app.press("i");
await app.paste(shot.replaceAll(" ", "\\ "));
await app.paste(`file://${shot.replaceAll(" ", "%20")}`);
await app.settle(50);
expect(app.calls("uploadAttachment")).toHaveLength(2);
});
test("a path to nothing, or to something that isn't an image, is text", async () => {
const app = await open({ session: withUploads() });
await app.press("i");
await app.paste(join(dir, "missing.png"));
expect(app.calls("uploadAttachment")).toHaveLength(0);
expect(app.frame()).toContain("missing.png");
});
});
describe("sent images", () => {
const shot = { type: "image", id: "att-shot", name: "shot.png", mimeType: "image/png", sizeBytes: PNG.length };
const withShot = () => {
const turn = withCompletedTurn() as unknown as { messages: { role: string; attachments: unknown[] }[]; turnItems: { type: string; attachments?: unknown[] }[] };
for (const message of turn.messages) if (message.role === "user") message.attachments = [shot];
for (const item of turn.turnItems) if (item.type === "user_message") item.attachments = [shot];
return turn as unknown as ReturnType<typeof withCompletedTurn>;
};
const rowsBetween = (frame: string, from: string, to: string) => {
const lines = frame.split("\n");
return lines.findIndex((line) => line.includes(to)) - lines.findIndex((line) => line.includes(from));
};
test("a user message's image shows inline, its name under it", async () => {
const app = await open({ session: fakeSession({ projection: withShot(), results: { attachmentImage: PNG } }) });
await app.settle(100);
expect(app.calls("attachmentImage")[0]?.args[0]).toMatchObject({ id: "att-shot" });
expect(app.frame()).toContain("▣ shot.png");
const rows = rowsBetween(app.frame(), "Do the thing", "▣ shot.png");
expect(rows).toBeGreaterThan(4);
expect(rows).toBeLessThanOrEqual(14);
});
test("an image that can't load is just its name", async () => {
const app = await open({ session: fakeSession({ projection: withShot(), failures: { attachmentImage: "gone" } }) });
await app.settle(100);
expect(rowsBetween(app.frame(), "Do the thing", "▣ shot.png")).toBe(2);
});
});
+65 -4
View File
@@ -4,7 +4,17 @@ import * as Schema from "effect/Schema";
import { homedir } from "node:os";
import { join } from "node:path";
import { attachmentLine, checkAttachment, clipboardImageCommands, expandAttachmentPath } from "../src/model/attachments.ts";
import {
attachmentLine,
checkAttachment,
clipboardImageCommands,
decodeAppleScriptData,
expandAttachmentPath,
isRemoteTerminal,
pastedImageName,
pastedImagePath,
pickClipboardImageType,
} from "../src/model/attachments.ts";
const isUpload = Schema.is(AttachmentCreateUploadUrlInput);
@@ -50,9 +60,60 @@ describe("checkAttachment", () => {
});
describe("clipboard", () => {
test("each platform's grabber comes first", () => {
expect(clipboardImageCommands("darwin")).toEqual([["pngpaste", "-"]]);
expect(clipboardImageCommands("linux")[0]).toEqual(["wl-paste", "--type", "image/png"]);
test("each platform's grabber comes first, reading whichever image type is there", () => {
const [pngpaste, osascript] = clipboardImageCommands("darwin");
expect(pngpaste?.read("image/png")).toEqual(["pngpaste", "-"]);
expect(osascript?.read("image/png")).toEqual(["osascript", "-e", "the clipboard as «class PNGf»"]);
const [wayland] = clipboardImageCommands("linux");
expect(wayland?.types).toEqual(["wl-paste", "--list-types"]);
expect(wayland?.read("image/jpeg")).toEqual(["wl-paste", "--type", "image/jpeg"]);
expect(attachmentLine([{ type: "file", id: "a", name: "a.txt", mimeType: "text/plain", sizeBytes: 1 }])).toBe("Attached: a.txt");
});
});
describe("clipboard images", () => {
test("a PNG is preferred, but any image type will do", () => {
expect(pickClipboardImageType(["text/plain", "image/jpeg", "image/png"])).toBe("image/png");
expect(pickClipboardImageType(["TARGETS", "image/webp\r"])).toBe("image/webp");
expect(pickClipboardImageType(["image/bmp"])).toBe("image/bmp");
expect(pickClipboardImageType(["text/plain", "UTF8_STRING"])).toBeNull();
});
test("osascript's «data PNGf…» output decodes to the bytes", () => {
const out = new TextEncoder().encode("«data PNGf89504E470D0A1A0A»\n");
expect([...(decodeAppleScriptData(out) ?? [])]).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
expect(decodeAppleScriptData(new TextEncoder().encode("execution error"))).toBeNull();
});
test("a pasted image is named for its type", () => {
expect(pastedImageName("image/png")).toBe("pasted-image.png");
expect(pastedImageName("image/jpeg")).toBe("pasted-image.jpg");
expect(pastedImageName("image/webp")).toBe("pasted-image.webp");
});
test("SSH means the clipboard is out of reach", () => {
expect(isRemoteTerminal({ SSH_CONNECTION: "1.2.3.4 5 6.7.8.9 22" })).toBe(true);
expect(isRemoteTerminal({ SSH_TTY: "/dev/pts/3" })).toBe(true);
expect(isRemoteTerminal({})).toBe(false);
});
});
describe("pasted paths", () => {
test("a dropped image path is read whether quoted, a file:// URL, or with escaped spaces", () => {
expect(pastedImagePath("/tmp/shot.png", null)).toBe("/tmp/shot.png");
expect(pastedImagePath("'/tmp/my shot.png' ", null)).toBe("/tmp/my shot.png");
expect(pastedImagePath('"/tmp/my shot.PNG"', null)).toBe("/tmp/my shot.PNG");
expect(pastedImagePath("/tmp/my\\ shot.jpg", null)).toBe("/tmp/my shot.jpg");
expect(pastedImagePath("file:///tmp/my%20shot.webp", null)).toBe("/tmp/my shot.webp");
expect(pastedImagePath("file://localhost/tmp/a.gif", null)).toBe("/tmp/a.gif");
expect(pastedImagePath("./shots/a.png", "/work")).toBe("/work/shots/a.png");
});
test("anything else is text", () => {
expect(pastedImagePath("/tmp/notes.txt", null)).toBeNull();
expect(pastedImagePath("look at shot.png please", null)).toBeNull();
expect(pastedImagePath("/tmp/a.png\n/tmp/b.png", null)).toBeNull();
expect(pastedImagePath("file://elsewhere/tmp/a.png", null)).toBeNull();
expect(pastedImagePath("", null)).toBeNull();
});
});