Merge features-08: terminal and editor pane, images, split diffs, selection, links, terminal themes, composer chips

This commit is contained in:
Callum Alpass committed 2026-11-03 03:39:51 +11:00
commit b6470966cf
40 files changed
+1845 -204

No files matched your search

+11
View File
@@ -128,6 +128,17 @@ describe("palette and pickers", () => {
expect(app.hints()).toStartWith("j/k threads");
});
test("settings offer the terminal's own colours", async () => {
const app = await open({ config: { theme: "light" } });
await app.press("k", { ctrl: true });
await app.type("settings");
await app.press("return");
const row = app.find("Colours");
expect(app.frame()).toMatch(/Colours\s+light/);
await app.click(row.x, row.y);
expect(app.frame()).toMatch(/Colours\s+the terminal's own colours/);
});
test(". opens the thread's actions, and choosing one runs it", async () => {
const app = await open();
await app.press(".");
+123
View File
@@ -0,0 +1,123 @@
import { afterEach, describe, expect, test } from "bun:test";
import { fakeSession, renderApp, v2ThreadId } 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;
});
const PNG = Uint8Array.from([0x89, 0x50, 0x4e, 0x47]);
const uploads = (...names: string[]) => {
let count = 0;
const session = fakeSession({ serverConfig: { providers: [], settings: {}, environment: { capabilities: { fileAttachments: { maxUploadBytes: 1 << 20 } } } } });
// Each upload is a new attachment, as the server makes them.
const uploadAttachment = async (upload: { name: string; mimeType: string; sizeBytes: number }) => {
session.calls.push({ method: "uploadAttachment", args: [upload] });
const name = names[count] ?? upload.name;
return { type: "image", id: `att-${++count}`, name, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes };
};
return { ...session, session: new Proxy(session.session, { get: (target, key) => (key === "uploadAttachment" ? uploadAttachment : Reflect.get(target, key)) }) };
};
/** The composer's text line: the row under the attachments line. */
const composerLine = (frame: string) => frame.split("\n").find((line) => line.includes("┃ ") && /\[image|@src|look|draft/.test(line)) ?? "";
const spanAt = (app: Awaited<ReturnType<typeof renderApp>>, text: string) => {
const at = app.find(text);
const line = app.renderer.currentRenderBuffer.getSpanLines()[at.y] as unknown as { spans: { text: string; fg: { toString(): string }; bg: { toString(): string } }[] };
return line.spans.find((span) => span.text.includes(text));
};
describe("composer chips", () => {
test("a pasted image becomes an [image 1] chip, left out of the text that's sent", async () => {
const fake = uploads();
const app = await open({ session: fake, clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.type("look at ");
await app.press("v", { ctrl: true });
await app.type("this");
expect(composerLine(app.frame())).toContain("look at [image 1] this");
await app.press("return");
const [call] = app.calls("sendMessage");
expect([call?.args[0], call?.args[1]]).toEqual([v2ThreadId, "look at this"]);
expect(call?.args[5]).toMatchObject([{ id: "att-1" }]);
});
test("the chip is drawn in the accent colour on the raised background", async () => {
const app = await open({ session: uploads(), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.press("v", { ctrl: true });
const { colors } = await import("../../src/ui/theme.ts");
const span = spanAt(app, "[image 1]");
const hex = (color: { toString(): string } | undefined) => color?.toString();
const { RGBA } = await import("@opentui/core");
expect(hex(span?.fg)).toBe(RGBA.fromHex(colors.accent).toString());
expect(hex(span?.bg)).toBe(RGBA.fromHex(colors.element).toString());
});
test("backspace deletes a chip whole, and its attachment with it", async () => {
const app = await open({ session: uploads(), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.press("v", { ctrl: true });
expect(app.frame()).toContain("pasted-image.png ✕");
await app.press("backspace");
await app.press("backspace");
expect(app.frame()).not.toContain("[image");
expect(app.frame()).not.toContain("pasted-image.png ✕");
expect(app.calls("deleteAttachment").map((call) => call.args[0])).toEqual(["att-1"]);
});
test("removing an attachment takes its chip out, and the others keep theirs", async () => {
const app = await open({ session: uploads("one.png", "two.png"), clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.press("v", { ctrl: true });
await app.press("v", { ctrl: true });
expect(composerLine(app.frame())).toContain("[image 1] [image 2]");
const remove = app.find("one.png ✕");
await app.click(remove.x + "one.png ".length, remove.y);
expect(app.frame()).not.toContain("[image 1]");
expect(composerLine(app.frame())).toContain("[image 2]");
});
test("a message that fails to send comes back with its chip, and isn't sent with the chip's text", async () => {
const fake = uploads();
const failing = fakeSession({ failures: { sendMessage: "socket closed" } });
const session = new Proxy(failing.session, { get: (target, key) => (key === "uploadAttachment" || key === "watchServerConfig" ? Reflect.get(fake.session, key) : Reflect.get(target, key)) });
const app = await open({ session: { ...failing, session }, clipboard: { image: { bytes: PNG, mimeType: "image/png" } } });
await app.press("i");
await app.type("look");
await app.press("v", { ctrl: true });
await app.press("return");
await app.settle(50);
expect(app.calls("sendMessage")[0]?.args[1]).toBe("look");
expect(composerLine(app.frame())).toContain("look [image 1]");
expect(app.frame()).toContain("pasted-image.png ✕");
});
test("an @ file is a chip showing its path, and is sent as the link the web sends", async () => {
const app = await open({ session: fakeSession({ results: { searchEntries: [{ kind: "file", path: "src/ui/App.tsx" }] } }) });
await app.press("i");
await app.type("see @App");
await app.settle(200);
expect(app.frame()).toContain("App.tsx");
await app.press("tab");
expect(composerLine(app.frame())).toContain("see @src/ui/App.tsx");
await app.type("now");
await app.press("return");
expect(app.calls("sendMessage")[0]?.args[1]).toBe("see [App.tsx](src/ui/App.tsx) now");
});
test("backspace over an @ chip deletes it whole", async () => {
const app = await open({ session: fakeSession({ results: { searchEntries: [{ kind: "file", path: "src/ui/App.tsx" }] } }) });
await app.press("i");
await app.type("see @App");
await app.settle(200);
await app.press("tab");
await app.press("backspace");
await app.press("backspace");
expect(composerLine(app.frame())).not.toContain("@src");
await app.type("draft");
expect(composerLine(app.frame())).toContain("see draft");
});
});
+49
View File
@@ -0,0 +1,49 @@
import { afterEach, describe, expect, test } from "bun:test";
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;
});
const patch = "diff --git a/src/index.ts b/src/index.ts\n--- a/src/index.ts\n+++ b/src/index.ts\n@@ -1,2 +1,2 @@\n const kept = 1;\n-const before = 2;\n+const after = 3;\n";
const withDiff = () => fakeSession({ projection: withCompletedTurn(), results: { turnDiff: { diff: patch } } });
/** The removed and added lines share a row side by side, and stack when unified. */
const sideBySide = (frame: string) => frame.split("\n").some((line) => line.includes("before") && line.includes("after"));
describe("diffs", () => {
test("a wide conversation shows them side by side", async () => {
const app = await open({ width: 260, session: withDiff() });
await app.press("D");
await app.settle(50);
expect(app.frame()).toContain("const before = 2;");
expect(sideBySide(app.frame())).toBe(true);
});
test("a narrower one shows them unified", async () => {
const app = await open({ width: 140, session: withDiff() });
await app.press("D");
await app.settle(50);
expect(app.frame()).toContain("const after = 3;");
expect(sideBySide(app.frame())).toBe(false);
});
test("Toggle split diff overrides the width for the session", async () => {
const app = await open({ width: 140, session: withDiff() });
await app.press("k", { ctrl: true });
await app.type("split diff");
await app.press("return");
await app.press("D");
await app.settle(50);
expect(sideBySide(app.frame())).toBe(true);
await app.press("k", { ctrl: true });
await app.type("split diff");
await app.press("return");
await app.settle(50);
expect(sideBySide(app.frame())).toBe(false);
});
});
+8
View File
@@ -166,3 +166,11 @@ export function withOmittedOutput(): OrchestrationV2ThreadProjection {
visibleTurnItems: [{ position: 0, visibility: "local", sourceThreadId: omittedCommand.threadId, sourceItemId: omittedCommand.id, item: omittedCommand }],
} as unknown as OrchestrationV2ThreadProjection;
}
/** The finished turn, its reply replaced by `text`, still streaming in if `streaming`. */
export function withReply(text: string, streaming: boolean): OrchestrationV2ThreadProjection {
const turn = structuredClone(withCompletedTurn()) as unknown as { turnItems: Record<string, unknown>[]; visibleTurnItems: { item: Record<string, unknown> }[] };
for (const item of turn.turnItems) if (item.type === "assistant_message") Object.assign(item, { text, streaming, status: streaming ? "running" : "completed" });
for (const visible of turn.visibleTurnItems) visible.item = turn.turnItems.find((item) => item.id === visible.item.id)!;
return turn as unknown as OrchestrationV2ThreadProjection;
}
+50 -7
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 };
@@ -41,10 +42,16 @@ export function fakeSession(
/** Git status for every folder; loading by default. */
readonly vcs?: unknown;
readonly results?: Record<string, unknown>;
/** The thread's terminals on the server, and what attaching to one streams. */
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[] = [];
const threadListeners = new Set<(value: unknown) => void>();
const snapshot = state.snapshot ?? v2ShellSnapshot;
const projection = state.projection ?? v2Projection;
const live = <T,>(value: T) => (listener: (value: T) => void) => {
@@ -54,11 +61,20 @@ export function fakeSession(
const known: Record<string, unknown> = {
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 }),
watchThread: (_id: ThreadId, listener: (value: unknown) => void) => {
threadListeners.add(listener);
listener({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } });
return () => threadListeners.delete(listener);
},
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: [] }),
watchTerminals: live({ status: "live", items: state.terminals ?? [] }),
attachTerminal: (input: unknown, onEvent: (event: unknown) => void) => {
calls.push({ method: "attachTerminal", args: [input] });
for (const event of state.terminalEvents ?? []) onEvent(event);
return () => calls.push({ method: "detachTerminal", args: [] });
},
watchVcs: (_cwd: string, listener: (value: unknown) => void) => live(state.vcs ?? { status: "loading", local: null, remote: null })(listener),
};
const session = new Proxy(known, {
@@ -74,14 +90,36 @@ export function fakeSession(
};
},
}) as unknown as T3Session;
return { session, calls };
/** Sends watchers of the thread a new projection, as the server does when it changes. */
const updateThread = (next: OrchestrationV2ThreadProjection) => {
for (const listener of threadListeners) listener({ status: "live", projection: next, history: { cursor: null, hasMore: false, loading: false } });
};
return { session, calls, updateThread };
}
/** 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);
@@ -113,6 +151,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();
@@ -131,5 +174,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);
});
});
+89
View File
@@ -0,0 +1,89 @@
import { afterEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { v2ShellSnapshot } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
import { withReply } 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));
const saved = { path: process.env.PATH, visual: process.env.VISUAL, editor: process.env.EDITOR };
afterEach(() => {
app?.destroy();
app = null;
process.env.PATH = saved.path;
for (const [key, value] of [["VISUAL", saved.visual], ["EDITOR", saved.editor]] as const) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
/** A workspace on this machine holding src/a.ts, as the thread's worktree. */
function workspace() {
const root = mkdtempSync(join(tmpdir(), "t3tui-links-"));
mkdirSync(join(root, "src"));
writeFileSync(join(root, "src/a.ts"), "export const a = 1;\n");
const snapshot = { ...v2ShellSnapshot, threads: v2ShellSnapshot.threads.map((thread) => ({ ...thread, worktreePath: root })) };
return { root, snapshot };
}
/** xdg-open and open, replaced by a script that writes down what it was asked to open. */
function fakeOpener() {
const bin = mkdtempSync(join(tmpdir(), "t3tui-opener-"));
const log = join(bin, "opened");
for (const name of ["xdg-open", "open"]) {
writeFileSync(join(bin, name), `#!/bin/sh\nprintf '%s\\n' "$1" >> '${log}'\n`);
chmodSync(join(bin, name), 0o755);
}
process.env.PATH = `${bin}:${process.env.PATH}`;
return () => {
try {
return readFileSync(log, "utf8").trim().split("\n");
} catch {
return [];
}
};
}
const waitFor = async (check: () => boolean) => {
for (let tries = 0; tries < 40 && !check(); tries++) await app?.settle(25);
};
describe("links and paths in replies", () => {
test("a click on a link opens it in the browser, whether written as a link or bare", async () => {
const opened = fakeOpener();
const app = await open({ session: fakeSession({ projection: withReply("See [the docs](https://example.com/docs) or https://bare.example.org/x now.", false) }) });
const label = app.find("the docs");
await app.click(label.x + 2, label.y);
const bare = app.find("bare.example");
await app.click(bare.x, bare.y);
await waitFor(() => opened().length === 2);
expect(opened()).toEqual(["https://example.com/docs", "https://bare.example.org/x"]);
});
test("a click on a workspace file's path opens it in the editor pane", async () => {
delete process.env.VISUAL;
process.env.EDITOR = "sleep 3; :";
const { snapshot } = workspace();
const app = await open({ width: 200, session: fakeSession({ snapshot, projection: withReply("I changed `src/a.ts:3` and left src/missing.ts alone.", false) }) });
const missing = app.find("missing.ts");
await app.click(missing.x, missing.y);
expect(app.frame()).not.toContain("Editing");
const path = app.find("a.ts:3");
await app.click(path.x, path.y);
expect(app.frame()).toContain("Editing ");
expect(app.frame()).toContain("src/a.ts");
});
test("a drag over a link selects it rather than opening it", async () => {
const opened = fakeOpener();
const app = await open({ session: fakeSession({ projection: withReply("Go to https://example.com/page please.", false) }) });
const link = app.find("https://example.com/page");
await app.mockMouse.drag(link.x, link.y, link.x + 10, link.y);
await app.settle(100);
expect(opened()).toEqual([]);
expect(app.calls("copy")).toHaveLength(1);
});
});
+111
View File
@@ -0,0 +1,111 @@
import { afterEach, describe, expect, test } from "bun:test";
import { fakeSession, renderApp, v2ThreadId } 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;
});
const terminal = { threadId: v2ThreadId, terminalId: "term-1", cwd: "/workspace/project", worktreePath: null, status: "running", pid: 42, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "", updatedAt: "2026-06-20T00:00:00.000Z" };
const snapshot = { type: "snapshot", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z", snapshot: { history: "earlier output\r\nuser@host:~$ " } };
const withTerminal = (events: readonly unknown[] = [snapshot]) => fakeSession({ terminals: [terminal], terminalEvents: events });
describe("terminal pane", () => {
test("ctrl+j opens the thread's terminal in the pane, with its scrollback, and takes every key", async () => {
const app = await open({ session: withTerminal() });
await app.press("j", { ctrl: true });
expect(app.frame()).toContain("Terminal · Terminal 1");
expect(app.frame()).toContain("user@host:~$");
expect(app.calls("attachTerminal")).toHaveLength(1);
expect(app.hints()).toBe("ctrl+\\ leave pane");
await app.press("q");
await app.press("escape");
expect(app.calls("writeTerminal").map((call) => call.args[2])).toEqual(["q", "\x1b"]);
// q went to the shell rather than quitting.
expect(app.frame()).toContain("user@host:~$");
});
test("ctrl+\\ leaves the pane and comes back to it; a click focuses it too", async () => {
const app = await open({ session: withTerminal() });
await app.press("j", { ctrl: true });
await app.press("\\", { ctrl: true });
expect(app.hints()).toStartWith("ctrl+\\ pane · j/k threads");
await app.press("j");
expect(app.calls("writeTerminal")).toHaveLength(0);
await app.press("\\", { ctrl: true });
expect(app.hints()).toBe("ctrl+\\ leave pane");
await app.press("\\", { ctrl: true });
const shell = app.find("user@host");
await app.click(shell.x, shell.y);
expect(app.hints()).toBe("ctrl+\\ leave pane");
});
test("it takes the details column's place, and the conversation's when the window is narrow", async () => {
const wide = await open({ width: 200, session: withTerminal() });
await wide.press("j", { ctrl: true });
const title = wide.find("Terminal · Terminal 1");
expect(title.x).toBeGreaterThan(200 - 38 - 1);
expect(wide.frame()).not.toContain("/workspace/project ·");
wide.destroy();
const narrow = await open({ width: 100, session: withTerminal() });
await narrow.press("j", { ctrl: true });
expect(narrow.find("Terminal · Terminal 1").x).toBeLessThan(50);
});
test("the pane closes when the terminal does", async () => {
const app = await open({ session: withTerminal([snapshot, { type: "closed", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z" }]) });
await app.press("j", { ctrl: true });
expect(app.frame()).not.toContain("Terminal · Terminal 1");
expect(app.hints()).toBe("Terminal closed");
});
test("the T picker can still attach full screen", async () => {
const app = await open({ session: withTerminal() });
await app.press("T");
expect(app.frame()).toContain("Attach full screen");
});
test("ctrl+g writes the message in $EDITOR in the pane, and what's saved comes back", async () => {
const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR };
delete process.env.VISUAL;
// Run as `$EDITOR "$1"`: this one waits a moment, overwrites the file and exits.
process.env.EDITOR = "sleep 0.5; printf 'from the editor' >";
try {
const app = await open();
await app.press("i");
await app.type("draft");
await app.press("g", { ctrl: true });
expect(app.frame()).toContain("Message · save and quit");
expect(app.hints()).toBe("ctrl+\\ leave pane");
for (let tries = 0; tries < 40 && app.frame().includes("Message · save and quit"); tries++) await app.settle(50);
expect(app.frame()).not.toContain("Message · save and quit");
expect(app.frame()).toContain("from the editor");
expect(app.hints()).toStartWith("enter send");
} finally {
if (previous.visual !== undefined) process.env.VISUAL = previous.visual;
if (previous.editor === undefined) delete process.env.EDITOR;
else process.env.EDITOR = previous.editor;
}
});
});
describe("editing a changed file", () => {
const vcs = {
status: "live",
local: { isRepo: true, hasPrimaryRemote: true, isDefaultRef: true, refName: "main", hasWorkingTreeChanges: true, workingTree: { files: [{ path: "README.md", insertions: 2, deletions: 1 }], insertions: 2, deletions: 1 } },
remote: { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null },
};
test("o on a file in Changes, or its ▸ Edit, opens it in the pane when it's on this machine", async () => {
const app = await open({ width: 200, session: fakeSession({ vcs }) });
await app.press("l");
expect(app.hints()).toContain("o edit file");
expect(app.frame()).toContain("▸ Edit o");
await app.press("o");
// The fixture's workspace isn't on this machine.
expect(app.hints()).toBe("README.md isn't on this machine.");
});
});
+43
View File
@@ -0,0 +1,43 @@
import { afterEach, describe, expect, test } from "bun:test";
import { withCompletedTurn } from "./fixtures.ts";
import { fakeSession, renderApp, v2ThreadId } 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;
});
describe("select and copy", () => {
test("dragging across the conversation copies what it covers on release", async () => {
const app = await open({ session: fakeSession({ projection: withCompletedTurn() }) });
const reply = app.find("Done — the thing");
await app.mockMouse.drag(reply.x, reply.y, reply.x + 8, reply.y);
await app.settle();
expect(app.calls("copy").map((call) => call.args[0])).toEqual(["Done — th"]);
expect(app.hints()).toBe("Copied");
});
test("a single click copies nothing and still selects the turn", async () => {
const app = await open({ session: fakeSession({ projection: withCompletedTurn() }) });
const prompt = app.find("Do the thing");
await app.click(prompt.x, prompt.y);
expect(app.calls("copy")).toHaveLength(0);
expect(app.hints()).not.toBe("Copied");
});
test("the terminal pane's text can be selected and copied too", async () => {
const terminal = { threadId: v2ThreadId, terminalId: "term-1", cwd: "/workspace/project", worktreePath: null, status: "running", pid: 42, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "", updatedAt: "2026-06-20T00:00:00.000Z" };
const snapshot = { type: "snapshot", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z", snapshot: { history: "build finished in 3s\r\n$ " } };
const app = await open({ width: 200, session: fakeSession({ terminals: [terminal], terminalEvents: [snapshot] }) });
await app.press("j", { ctrl: true });
const line = app.find("build finished");
await app.mockMouse.drag(line.x, line.y, line.x + 13, line.y);
await app.settle();
expect(app.calls("copy").map((call) => call.args[0])).toEqual(["build finished"]);
// Dragging isn't typing: nothing went to the shell.
expect(app.calls("writeTerminal")).toHaveLength(0);
});
});
+71
View File
@@ -0,0 +1,71 @@
import { afterEach, describe, expect, test } from "bun:test";
import { RGBA } from "@opentui/core";
import { applyTheme, colors } from "../../src/ui/theme.ts";
import { withReply } 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;
applyTheme("dark");
});
const table = "| Name | Value |\n| --- | --- |\n| alpha | 1 |\n| beta | a longer cell |\n";
const paragraphs = (from: number, to: number) => Array.from({ length: to - from }, (_, index) => `Paragraph ${from + index} of the answer.\n\n`).join("");
/** The frame without its scrollbar column, which moves as the content grows. */
const content = (frame: string) => frame.split("\n").map((line) => line.slice(0, -3)).join("\n");
describe("streaming replies", () => {
test("tables render as tables, while streaming and once settled", async () => {
const fake = fakeSession({ projection: withReply(`Here:\n\n${table.slice(0, 40)}`, true) });
const app = await open({ session: fake });
expect(app.frame()).toContain("│ Name │ Value │");
fake.updateThread(withReply(`Here:\n\n${table}\nAfter.`, false));
await app.settle(50);
expect(app.frame()).toContain("│ beta │ a longer cell │");
expect(app.frame()).not.toContain("| --- |");
});
test("at the bottom, a long answer keeps its newest line in view", async () => {
const fake = fakeSession({ projection: withReply("", true) });
const app = await open({ session: fake, height: 30 });
for (let count = 10; count <= 60; count += 10) {
fake.updateThread(withReply(paragraphs(0, count), true));
await app.settle();
expect(app.frame()).toContain(`Paragraph ${count - 1} of the answer.`);
}
});
test("scrolled up, the text in view stays put as the answer grows and settles", async () => {
let text = paragraphs(0, 40);
const fake = fakeSession({ projection: withReply(text, true) });
const app = await open({ session: fake, height: 30 });
await app.mockMouse.scroll(60, 10, "up");
await app.mockMouse.scroll(60, 10, "up");
await app.settle(30);
const before = content(app.frame());
for (let more = 40; more < 50; more++) {
text += `Paragraph ${more} of the answer.\n\n`;
fake.updateThread(withReply(text, true));
await app.settle();
expect(content(app.frame())).toBe(before);
}
fake.updateThread(withReply(`${text}${table}`, false));
await app.settle(30);
expect(content(app.frame())).toBe(before);
});
});
test("a long answer's scrollbar takes the palette's colours, in the light theme too", async () => {
applyTheme("light");
const app = await open({ session: fakeSession({ projection: withReply(paragraphs(0, 60), false) }) });
const backgrounds = new Set<string>();
for (const line of app.renderer.currentRenderBuffer.getSpanLines() as unknown as { spans: { bg: RGBA }[] }[]) for (const span of line.spans) backgrounds.add(span.bg.toString());
// OpenTUI's own track is a dark grey.
expect(backgrounds.has(RGBA.fromHex("#252527").toString())).toBe(false);
expect(backgrounds.has(RGBA.fromHex(colors.element).toString())).toBe(true);
});
+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();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { isWebUrl, pathAt } from "../src/model/links.ts";
const at = (text: string, word: string) => pathAt(text, text.indexOf(word));
describe("paths in text", () => {
test("a click anywhere in a path finds the whole path", () => {
const text = "I changed src/ui/App.tsx and test/app.test.tsx.";
expect(at(text, "src")).toBe("src/ui/App.tsx");
expect(at(text, "App")).toBe("src/ui/App.tsx");
expect(at(text, "app.test")).toBe("test/app.test.tsx");
});
test("line numbers and leading dots are path syntax", () => {
expect(at("see ./bin.ts:12:4 for it", "bin")).toBe("./bin.ts");
expect(at("in ../shared/x.ts, line 3", "shared")).toBe("../shared/x.ts");
expect(at("open ~/notes.md now", "notes")).toBe("~/notes.md");
expect(at("(README.md)", "README")).toBe("README.md");
});
test("words, URLs and punctuation are not paths", () => {
expect(at("the build is done", "build")).toBeNull();
expect(at("see https://example.com/a.html", "example")).toBeNull();
expect(at("see https://example.com/a.html", "https")).toBeNull();
expect(at("a, b", ",")).toBeNull();
expect(at("version 1.2", "1.2")).toBeNull();
});
test("web links open in the browser; file: links and bare targets are files", () => {
expect(isWebUrl("https://example.com")).toBe(true);
expect(isWebUrl("mailto:me@example.com")).toBe(true);
expect(isWebUrl("file:///tmp/a.ts")).toBe(false);
expect(isWebUrl("src/ui/App.tsx")).toBe(false);
});
});
+44 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, expect, test } from "bun:test";
import { applyTheme, colors, statusColor, toneColor } from "../src/ui/theme.ts";
import { applyTheme, colors, statusColor, terminalPalette, themeModeOf, toneColor } from "../src/ui/theme.ts";
afterEach(() => applyTheme("dark"));
@@ -13,3 +13,46 @@ test("the light palette replaces every colour, and the tone maps follow it", ()
applyTheme("dark");
expect(colors).toEqual(dark);
});
const terminal = (background: string | null, foreground: string | null, palette: (string | null)[] = []) =>
({ palette, defaultForeground: foreground, defaultBackground: background, cursorColor: null, mouseForeground: null, mouseBackground: null, tekForeground: null, tekBackground: null, highlightBackground: null, highlightForeground: null }) as const;
const ansi = ["#000000", "#cc0000", "#00aa00", "#aaaa00", "#0000cc", "#aa00aa", "#00aaaa", "#cccccc", "#555555", "#ff5555", "#55ff55", "#ffff55", "#5555ff", "#ff55ff", "#55ffff", "#ffffff"];
test("auto reads dark or light from the terminal's background, and nothing without one", () => {
expect(themeModeOf(terminal("#1d1f21", "#c5c8c6"))).toBe("dark");
expect(themeModeOf(terminal("#fdf6e3", "#657b83"))).toBe("light");
expect(themeModeOf(terminal(null, null))).toBeNull();
expect(themeModeOf(null)).toBeNull();
});
test("the terminal palette steps off the terminal's background and takes its ANSI hues", () => {
const palette = terminalPalette(terminal("#202020", "#d0d0d0", ansi))!;
expect(palette.bg).toBe("#202020");
expect(palette.text).toBe("#d0d0d0");
// Small steps lighter, in order.
const lightness = (hex: string) => Number.parseInt(hex.slice(1, 3), 16);
expect(lightness(palette.panel)).toBeGreaterThan(lightness(palette.bg));
expect(lightness(palette.element)).toBeGreaterThan(lightness(palette.panel));
expect(lightness(palette.element) - lightness(palette.bg)).toBeLessThan(30);
expect(palette.bad).toBe("#cc0000");
expect(palette.good).toBe("#00aa00");
expect(palette.warn).toBe("#aaaa00");
expect(palette.accent).toBe("#5555ff");
expect(palette.info).toBe("#00aaaa");
for (const value of Object.values(palette)) expect(value).toMatch(/^#[0-9a-f]{6}$/);
});
test("on a light terminal the steps go darker, and missing ANSI colours come from the light palette", () => {
const palette = terminalPalette(terminal("#fafafa", "#202020"))!;
expect(palette.panel < palette.bg).toBe(true);
applyTheme("light");
expect(palette.good).toBe(colors.good);
applyTheme(palette);
expect(colors.bg).toBe("#fafafa");
expect(statusColor("good")).toBe(palette.good);
});
test("without the terminal's colours there is no terminal palette", () => {
expect(terminalPalette(terminal("#202020", null, ansi))).toBeNull();
expect(terminalPalette(null)).toBeNull();
});