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

+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);
});
});