Merge branch 'main' into more-error-handling

This commit is contained in:
easong-openai
2025-04-23 21:18:38 -07:00
committed by GitHub
110 changed files with 12243 additions and 9093 deletions
@@ -0,0 +1,12 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`checkForUpdates() > renders a box when a newer version exists and no global installer 1`] = `
"
╭─────────────────────────────────────────────────╮
│ │
│ Update available! 1.0.0 → 2.0.0. │
│ To update, run bun add -g my-pkg to update. │
│ │
╰─────────────────────────────────────────────────╯
"
`;
+1 -1
View File
@@ -50,7 +50,7 @@ vi.mock("openai", () => {
// The AgentLoop pulls these helpers in order to decide whether a command can
// be auto‑approved. None of that matters for this test, so we stub the module
// with minimal no‑op implementations.
// with minimal no-op implementations.
vi.mock("../src/approvals.js", () => {
return {
__esModule: true,
+60 -2
View File
@@ -11,7 +11,13 @@ describe("canAutoApprove()", () => {
const writeablePaths: Array<string> = [];
const check = (command: ReadonlyArray<string>): SafetyAssessment =>
canAutoApprove(command, "suggest", writeablePaths, env);
canAutoApprove(
command,
/* workdir */ undefined,
"suggest",
writeablePaths,
env,
);
test("simple safe commands", () => {
expect(check(["ls"])).toEqual({
@@ -73,7 +79,7 @@ describe("canAutoApprove()", () => {
test("true command is considered safe", () => {
expect(check(["true"])).toEqual({
type: "auto-approve",
reason: "No‑op (true)",
reason: "No-op (true)",
group: "Utility",
runInSandbox: false,
});
@@ -89,4 +95,56 @@ describe("canAutoApprove()", () => {
expect(check(["cargo", "build"])).toEqual({ type: "ask-user" });
});
test("find", () => {
expect(check(["find", ".", "-name", "file.txt"])).toEqual({
type: "auto-approve",
reason: "Find files or directories",
group: "Searching",
runInSandbox: false,
});
// Options that can execute arbitrary commands.
expect(
check(["find", ".", "-name", "file.txt", "-exec", "rm", "{}", ";"]),
).toEqual({
type: "ask-user",
});
expect(
check(["find", ".", "-name", "*.py", "-execdir", "python3", "{}", ";"]),
).toEqual({
type: "ask-user",
});
expect(
check(["find", ".", "-name", "file.txt", "-ok", "rm", "{}", ";"]),
).toEqual({
type: "ask-user",
});
expect(
check(["find", ".", "-name", "*.py", "-okdir", "python3", "{}", ";"]),
).toEqual({
type: "ask-user",
});
// Option that deletes matching files.
expect(check(["find", ".", "-delete", "-name", "file.txt"])).toEqual({
type: "ask-user",
});
// Options that write pathnames to a file.
expect(check(["find", ".", "-fls", "/etc/passwd"])).toEqual({
type: "ask-user",
});
expect(check(["find", ".", "-fprint", "/etc/passwd"])).toEqual({
type: "ask-user",
});
expect(check(["find", ".", "-fprint0", "/etc/passwd"])).toEqual({
type: "ask-user",
});
expect(
check(["find", ".", "-fprintf", "/root/suid.txt", "%#m %u %p\n"]),
).toEqual({
type: "ask-user",
});
});
});
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { join } from "node:path";
import os from "node:os";
import type { UpdateOptions } from "../src/utils/check-updates";
import { getLatestVersion } from "fast-npm-meta";
import { getUserAgent } from "package-manager-detector";
import {
checkForUpdates,
renderUpdateCommand,
} from "../src/utils/check-updates";
import { detectInstallerByPath } from "../src/utils/package-manager-detector";
import { CLI_VERSION } from "../src/utils/session";
// In-memory FS mock
let memfs: Record<string, string> = {};
vi.mock("node:fs/promises", async (importOriginal) => {
return {
...(await importOriginal()),
readFile: async (path: string) => {
if (!(path in memfs)) {
const err: any = new Error(
`ENOENT: no such file or directory, open '${path}'`,
);
err.code = "ENOENT";
throw err;
}
return memfs[path];
},
writeFile: async (path: string, data: string) => {
memfs[path] = data;
},
rm: async (path: string) => {
delete memfs[path];
},
};
});
// Mock package name & CLI version
const MOCK_PKG = "my-pkg";
vi.mock("../package.json", () => ({ name: MOCK_PKG }));
vi.mock("../src/utils/session", () => ({ CLI_VERSION: "1.0.0" }));
vi.mock("../src/utils/package-manager-detector", async (importOriginal) => {
return {
...(await importOriginal()),
detectInstallerByPath: vi.fn(),
};
});
// Mock external services
vi.mock("fast-npm-meta", () => ({ getLatestVersion: vi.fn() }));
vi.mock("package-manager-detector", () => ({ getUserAgent: vi.fn() }));
describe("renderUpdateCommand()", () => {
it.each([
[{ manager: "npm", packageName: MOCK_PKG }, `npm install -g ${MOCK_PKG}`],
[{ manager: "pnpm", packageName: MOCK_PKG }, `pnpm add -g ${MOCK_PKG}`],
[{ manager: "bun", packageName: MOCK_PKG }, `bun add -g ${MOCK_PKG}`],
[{ manager: "yarn", packageName: MOCK_PKG }, `yarn global add ${MOCK_PKG}`],
[
{ manager: "deno", packageName: MOCK_PKG },
`deno install -g npm:${MOCK_PKG}`,
],
])("%s → command", async (options, cmd) => {
expect(renderUpdateCommand(options as UpdateOptions)).toBe(cmd);
});
});
describe("checkForUpdates()", () => {
// Use a stable directory under the OS temp
const TMP = join(os.tmpdir(), "update-test-memfs");
const STATE_PATH = join(TMP, "update-check.json");
beforeEach(async () => {
memfs = {};
// Mock CONFIG_DIR to our TMP
vi.doMock("../src/utils/config", () => ({ CONFIG_DIR: TMP }));
// Freeze time so the 24h logic is deterministic
vi.useFakeTimers().setSystemTime(new Date("2025-01-01T00:00:00Z"));
vi.resetAllMocks();
});
afterEach(async () => {
vi.useRealTimers();
});
it("uses global installer when detected, ignoring local agent", async () => {
// seed old timestamp
const old = new Date("2000-01-01T00:00:00Z").toUTCString();
memfs[STATE_PATH] = JSON.stringify({ lastUpdateCheck: old });
// simulate registry says update available
vi.mocked(getLatestVersion).mockResolvedValue({ version: "2.0.0" } as any);
// local agent would be npm, but global detection wins
vi.mocked(getUserAgent).mockReturnValue("npm");
vi.mocked(detectInstallerByPath).mockReturnValue(Promise.resolve("pnpm"));
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await checkForUpdates();
// should render using `pnpm` (global) rather than `npm`
expect(logSpy).toHaveBeenCalledOnce();
const output = logSpy.mock.calls.at(0)?.at(0);
expect(output).toContain("pnpm add -g"); // global branch used
// state updated
const newState = JSON.parse(memfs[STATE_PATH]!);
expect(newState.lastUpdateCheck).toBe(new Date().toUTCString());
});
it("skips when lastUpdateCheck is still fresh (<frequency)", async () => {
// seed a timestamp 12h ago
const recent = new Date(Date.now() - 1000 * 60 * 60 * 12).toUTCString();
memfs[STATE_PATH] = JSON.stringify({ lastUpdateCheck: recent });
const versionSpy = vi.mocked(getLatestVersion);
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await checkForUpdates();
expect(versionSpy).not.toHaveBeenCalled();
expect(logSpy).not.toHaveBeenCalled();
});
it("does not print when up-to-date", async () => {
vi.mocked(getLatestVersion).mockResolvedValue({
version: CLI_VERSION,
} as any);
vi.mocked(getUserAgent).mockReturnValue("npm");
vi.mocked(detectInstallerByPath).mockResolvedValue(undefined);
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await checkForUpdates();
expect(logSpy).not.toHaveBeenCalled();
// but state still written
const state = JSON.parse(memfs[STATE_PATH]!);
expect(state.lastUpdateCheck).toBe(new Date().toUTCString());
});
it("does not print when no manager detected at all", async () => {
vi.mocked(getLatestVersion).mockResolvedValue({ version: "2.0.0" } as any);
vi.mocked(detectInstallerByPath).mockResolvedValue(undefined);
vi.mocked(getUserAgent).mockReturnValue(null);
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await checkForUpdates();
expect(logSpy).not.toHaveBeenCalled();
// state still written
const state = JSON.parse(memfs[STATE_PATH]!);
expect(state.lastUpdateCheck).toBe(new Date().toUTCString());
});
it("renders a box when a newer version exists and no global installer", async () => {
// old timestamp
const old = new Date("2000-01-01T00:00:00Z").toUTCString();
memfs[STATE_PATH] = JSON.stringify({ lastUpdateCheck: old });
vi.mocked(getLatestVersion).mockResolvedValue({ version: "2.0.0" } as any);
vi.mocked(detectInstallerByPath).mockResolvedValue(undefined);
vi.mocked(getUserAgent).mockReturnValue("bun");
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
await checkForUpdates();
expect(logSpy).toHaveBeenCalledOnce();
const output = logSpy.mock.calls[0]![0] as string;
expect(output).toContain("bun add -g");
expect(output).to.matchSnapshot();
// state updated
const state = JSON.parse(memfs[STATE_PATH]!);
expect(state.lastUpdateCheck).toBe(new Date().toUTCString());
});
});
+174
View File
@@ -0,0 +1,174 @@
import React from "react";
import type { ComponentProps } from "react";
import { describe, it, expect, vi } from "vitest";
import { renderTui } from "./ui-test-helpers.js";
import TerminalChatInput from "../src/components/chat/terminal-chat-input.js";
import TerminalChatNewInput from "../src/components/chat/terminal-chat-new-input.js";
import * as TermUtils from "../src/utils/terminal.js";
// -------------------------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------------------------------
async function type(
stdin: NodeJS.WritableStream,
text: string,
flush: () => Promise<void>,
): Promise<void> {
stdin.write(text);
await flush();
}
// -------------------------------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------------------------------
describe("/clear command", () => {
it("invokes clearTerminal and resets context in TerminalChatInput", async () => {
const clearSpy = vi
.spyOn(TermUtils, "clearTerminal")
.mockImplementation(() => {});
const setItems = vi.fn();
// Minimal stub of a ResponseItem – cast to bypass exhaustive type checks in this test context
const existingItems = [
{
id: "dummy-1",
type: "message",
role: "system",
content: [{ type: "input_text", text: "Old item" }],
},
] as Array<any>;
const props: ComponentProps<typeof TerminalChatInput> = {
isNew: false,
loading: false,
submitInput: () => {},
confirmationPrompt: null,
explanation: undefined,
submitConfirmation: () => {},
setLastResponseId: () => {},
setItems,
contextLeftPercent: 100,
openOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
openDiffOverlay: () => {},
onCompact: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
items: existingItems,
};
const { stdin, flush, cleanup } = renderTui(
<TerminalChatInput {...props} />,
);
await flush();
await type(stdin, "/clear", flush);
await type(stdin, "\r", flush); // press Enter
// Allow any asynchronous state updates to propagate
await flush();
expect(clearSpy).toHaveBeenCalledTimes(2);
expect(setItems).toHaveBeenCalledTimes(2);
const stateUpdater = setItems.mock.calls[0]![0];
expect(typeof stateUpdater).toBe("function");
const newItems = stateUpdater(existingItems);
expect(Array.isArray(newItems)).toBe(true);
expect(newItems).toHaveLength(2);
expect(newItems.at(-1)).toMatchObject({
role: "system",
type: "message",
content: [{ type: "input_text", text: "Terminal cleared" }],
});
cleanup();
clearSpy.mockRestore();
});
it("invokes clearTerminal and resets context in TerminalChatNewInput", async () => {
const clearSpy = vi
.spyOn(TermUtils, "clearTerminal")
.mockImplementation(() => {});
const setItems = vi.fn();
const props: ComponentProps<typeof TerminalChatNewInput> = {
isNew: false,
loading: false,
submitInput: () => {},
confirmationPrompt: null,
explanation: undefined,
submitConfirmation: () => {},
setLastResponseId: () => {},
setItems,
contextLeftPercent: 100,
openOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
openDiffOverlay: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
};
const { stdin, flush, cleanup } = renderTui(
<TerminalChatNewInput {...props} />,
);
await flush();
await type(stdin, "/clear", flush);
await type(stdin, "\r", flush); // press Enter
await flush();
expect(clearSpy).toHaveBeenCalledTimes(1);
expect(setItems).toHaveBeenCalledTimes(1);
const firstArg = setItems.mock.calls[0]![0];
expect(Array.isArray(firstArg)).toBe(true);
expect(firstArg).toHaveLength(1);
expect(firstArg[0]).toMatchObject({
role: "system",
type: "message",
content: [{ type: "input_text", text: "Terminal cleared" }],
});
cleanup();
clearSpy.mockRestore();
});
});
describe("clearTerminal", () => {
it("writes escape sequence to stdout", () => {
const originalQuiet = process.env["CODEX_QUIET_MODE"];
delete process.env["CODEX_QUIET_MODE"];
process.env["CODEX_QUIET_MODE"] = "0";
const writeSpy = vi
.spyOn(process.stdout, "write")
.mockImplementation(() => true);
TermUtils.clearTerminal();
expect(writeSpy).toHaveBeenCalledWith("\x1b[3J\x1b[H\x1b[2J");
writeSpy.mockRestore();
if (originalQuiet !== undefined) {
process.env["CODEX_QUIET_MODE"] = originalQuiet;
} else {
delete process.env["CODEX_QUIET_MODE"];
}
});
});
+128 -1
View File
@@ -1,9 +1,11 @@
import type * as fsType from "fs";
import { loadConfig, saveConfig } from "../src/utils/config.js"; // parent import first
import { AutoApprovalMode } from "../src/utils/auto-approval-mode.js";
import { tmpdir } from "os";
import { join } from "path";
import { test, expect, beforeEach, afterEach, vi } from "vitest";
import { providers as defaultProviders } from "../src/utils/providers";
// In‑memory FS store
let memfs: Record<string, string> = {};
@@ -25,7 +27,7 @@ vi.mock("fs", async () => {
memfs[path] = data;
},
mkdirSync: () => {
// no‑op in in‑memory store
// no-op in in‑memory store
},
rmSync: (path: string) => {
// recursively delete any key under this prefix
@@ -107,3 +109,128 @@ test("loads user instructions + project doc when codex.md is present", () => {
userInstr + "\n\n--- project-doc ---\n\n" + projectDoc,
);
});
test("loads and saves approvalMode correctly", () => {
// Setup config with approvalMode
memfs[testConfigPath] = JSON.stringify(
{
model: "mymodel",
approvalMode: AutoApprovalMode.AUTO_EDIT,
},
null,
2,
);
memfs[testInstructionsPath] = "test instructions";
// Load config and verify approvalMode
const loadedConfig = loadConfig(testConfigPath, testInstructionsPath, {
disableProjectDoc: true,
});
// Check approvalMode was loaded correctly
expect(loadedConfig.approvalMode).toBe(AutoApprovalMode.AUTO_EDIT);
// Modify approvalMode and save
const updatedConfig = {
...loadedConfig,
approvalMode: AutoApprovalMode.FULL_AUTO,
};
saveConfig(updatedConfig, testConfigPath, testInstructionsPath);
// Verify saved config contains updated approvalMode
expect(memfs[testConfigPath]).toContain(
`"approvalMode": "${AutoApprovalMode.FULL_AUTO}"`,
);
// Load again and verify updated value
const reloadedConfig = loadConfig(testConfigPath, testInstructionsPath, {
disableProjectDoc: true,
});
expect(reloadedConfig.approvalMode).toBe(AutoApprovalMode.FULL_AUTO);
});
test("loads and saves providers correctly", () => {
// Setup custom providers configuration
const customProviders = {
openai: {
name: "Custom OpenAI",
baseURL: "https://custom-api.openai.com/v1",
envKey: "CUSTOM_OPENAI_API_KEY",
},
anthropic: {
name: "Anthropic",
baseURL: "https://api.anthropic.com",
envKey: "ANTHROPIC_API_KEY",
},
};
// Create config with providers
const testConfig = {
model: "test-model",
provider: "anthropic",
providers: customProviders,
instructions: "test instructions",
notify: false,
};
// Save the config
saveConfig(testConfig, testConfigPath, testInstructionsPath);
// Verify saved config contains providers
expect(memfs[testConfigPath]).toContain(`"providers"`);
expect(memfs[testConfigPath]).toContain(`"Custom OpenAI"`);
expect(memfs[testConfigPath]).toContain(`"Anthropic"`);
expect(memfs[testConfigPath]).toContain(`"provider": "anthropic"`);
// Load config and verify providers were loaded correctly
const loadedConfig = loadConfig(testConfigPath, testInstructionsPath, {
disableProjectDoc: true,
});
// Check providers were loaded correctly
expect(loadedConfig.provider).toBe("anthropic");
expect(loadedConfig.providers).toEqual({
...defaultProviders,
...customProviders,
});
// Test merging with built-in providers
// Create a config with only one custom provider
const partialProviders = {
customProvider: {
name: "Custom Provider",
baseURL: "https://custom-api.example.com",
envKey: "CUSTOM_API_KEY",
},
};
const partialConfig = {
model: "test-model",
provider: "customProvider",
providers: partialProviders,
instructions: "test instructions",
notify: false,
};
// Save the partial config
saveConfig(partialConfig, testConfigPath, testInstructionsPath);
// Load config and verify providers were merged with built-in providers
const mergedConfig = loadConfig(testConfigPath, testInstructionsPath, {
disableProjectDoc: true,
});
// Check providers is defined
expect(mergedConfig.providers).toBeDefined();
// Use bracket notation to access properties
if (mergedConfig.providers) {
expect(mergedConfig.providers["customProvider"]).toBeDefined();
expect(mergedConfig.providers["customProvider"]).toEqual(
partialProviders.customProvider,
);
// Built-in providers should still be there (like openai)
expect(mergedConfig.providers["openai"]).toBeDefined();
}
});
@@ -0,0 +1,55 @@
import { PassThrough } from "stream";
import { once } from "events";
import { describe, it, expect } from "vitest";
import { createTruncatingCollector } from "../src/utils/agent/sandbox/create-truncating-collector.js";
describe("createTruncatingCollector", () => {
it("collects data under limits without truncation", async () => {
const stream = new PassThrough();
const collector = createTruncatingCollector(stream, 100, 10);
const data = "line1\nline2\n";
stream.end(Buffer.from(data));
await once(stream, "end");
expect(collector.getString()).toBe(data);
expect(collector.hit).toBe(false);
});
it("truncates data over byte limit", async () => {
const stream = new PassThrough();
const collector = createTruncatingCollector(stream, 5, 100);
stream.end(Buffer.from("hello world"));
await once(stream, "end");
expect(collector.getString()).toBe("hello");
expect(collector.hit).toBe(true);
});
it("truncates data over line limit", async () => {
const stream = new PassThrough();
const collector = createTruncatingCollector(stream, 1000, 2);
const data = "a\nb\nc\nd\n";
stream.end(Buffer.from(data));
await once(stream, "end");
expect(collector.getString()).toBe("a\nb\n");
expect(collector.hit).toBe(true);
});
it("stops collecting after limit is hit across multiple writes", async () => {
const stream = new PassThrough();
const collector = createTruncatingCollector(stream, 10, 2);
stream.write(Buffer.from("1\n"));
stream.write(Buffer.from("2\n3\n4\n"));
stream.end();
await once(stream, "end");
expect(collector.getString()).toBe("1\n2\n");
expect(collector.hit).toBe(true);
});
it("handles zero limits", async () => {
const stream = new PassThrough();
const collector = createTruncatingCollector(stream, 0, 0);
stream.end(Buffer.from("anything\n"));
await once(stream, "end");
expect(collector.getString()).toBe("");
expect(collector.hit).toBe(true);
});
});
+44
View File
@@ -0,0 +1,44 @@
import { execApplyPatch } from "../src/utils/agent/exec.js";
import fs from "fs";
import os from "os";
import path from "path";
import { test, expect } from "vitest";
/**
* This test verifies that `execApplyPatch()` is able to add a new file whose
* parent directory does not yet exist. Prior to the fix, the call would throw
* because `fs.writeFileSync()` could not create intermediate directories. The
* test creates an isolated temporary directory to avoid polluting the project
* workspace.
*/
test("execApplyPatch creates missing directories when adding a file", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "apply-patch-test-"));
// Ensure we start from a clean slate.
const nestedFileRel = path.join("foo", "bar", "baz.txt");
const nestedFileAbs = path.join(tmpDir, nestedFileRel);
expect(fs.existsSync(nestedFileAbs)).toBe(false);
const patch = `*** Begin Patch\n*** Add File: ${nestedFileRel}\n+hello new world\n*** End Patch`;
// Run execApplyPatch() with cwd switched to tmpDir so that the relative
// path in the patch is resolved inside the temporary location.
const prevCwd = process.cwd();
try {
process.chdir(tmpDir);
const result = execApplyPatch(patch);
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
} finally {
process.chdir(prevCwd);
}
// The file (and its parent directories) should have been created with the
// expected contents.
const fileContents = fs.readFileSync(nestedFileAbs, "utf8");
expect(fileContents).toBe("hello new world");
// Cleanup to keep tmpdir tidy.
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -0,0 +1,73 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { getFileSystemSuggestions } from "../src/utils/file-system-suggestions";
vi.mock("fs");
vi.mock("os");
describe("getFileSystemSuggestions", () => {
const mockFs = fs as unknown as {
readdirSync: ReturnType<typeof vi.fn>;
statSync: ReturnType<typeof vi.fn>;
};
const mockOs = os as unknown as {
homedir: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.clearAllMocks();
});
it("returns empty array for empty prefix", () => {
expect(getFileSystemSuggestions("")).toEqual([]);
});
it("expands ~ to home directory", () => {
mockOs.homedir = vi.fn(() => "/home/testuser");
mockFs.readdirSync = vi.fn(() => ["file1.txt", "docs"]);
mockFs.statSync = vi.fn((p) => ({
isDirectory: () => path.basename(p) === "docs",
}));
const result = getFileSystemSuggestions("~/");
expect(mockFs.readdirSync).toHaveBeenCalledWith("/home/testuser");
expect(result).toEqual([
path.join("/home/testuser", "file1.txt"),
path.join("/home/testuser", "docs" + path.sep),
]);
});
it("filters by prefix if not a directory", () => {
mockFs.readdirSync = vi.fn(() => ["abc.txt", "abd.txt", "xyz.txt"]);
mockFs.statSync = vi.fn((p) => ({
isDirectory: () => p.includes("abd"),
}));
const result = getFileSystemSuggestions("a");
expect(result).toEqual(["abc.txt", "abd.txt/"]);
});
it("handles errors gracefully", () => {
mockFs.readdirSync = vi.fn(() => {
throw new Error("failed");
});
const result = getFileSystemSuggestions("some/path");
expect(result).toEqual([]);
});
it("normalizes relative path", () => {
mockFs.readdirSync = vi.fn(() => ["foo", "bar"]);
mockFs.statSync = vi.fn((_p) => ({
isDirectory: () => true,
}));
const result = getFileSystemSuggestions("./");
expect(result).toContain("foo/");
expect(result).toContain("bar/");
});
});
@@ -0,0 +1,38 @@
import { describe, it, expect } from "vitest";
import { parse } from "shell-quote";
// The fixed requiresShell function
function requiresShell(cmd: Array<string>): boolean {
// If the command is a single string that contains shell operators,
// it needs to be run with shell: true
if (cmd.length === 1 && cmd[0] !== undefined) {
const tokens = parse(cmd[0]) as Array<any>;
return tokens.some((token) => typeof token === "object" && "op" in token);
}
// If the command is split into multiple arguments, we don't need shell: true
// even if one of the arguments is a shell operator like '|'
return false;
}
describe("fixed requiresShell function", () => {
it("should detect pipe in a single argument", () => {
const cmd = ['grep -n "finally:" some-file | head'];
expect(requiresShell(cmd)).toBe(true);
});
it("should not detect pipe in separate arguments", () => {
const cmd = ["grep", "-n", "finally:", "some-file", "|", "head"];
expect(requiresShell(cmd)).toBe(false);
});
it("should handle other shell operators in a single argument", () => {
const cmd = ["echo hello && echo world"];
expect(requiresShell(cmd)).toBe(true);
});
it("should not enable shell for normal commands", () => {
const cmd = ["ls", "-la"];
expect(requiresShell(cmd)).toBe(false);
});
});
+350
View File
@@ -0,0 +1,350 @@
/* -------------------------------------------------------------------------- *
* Tests for the HistoryOverlay component and its formatHistoryForDisplay utility function
*
* The component displays a list of commands and files from the chat history.
* It supports two modes:
* - Command mode: shows all commands and user messages
* - File mode: shows all files that were touched
*
* The formatHistoryForDisplay function processes ResponseItems to extract:
* - Commands: User messages and function calls
* - Files: Paths referenced in commands or function calls
* -------------------------------------------------------------------------- */
import { describe, it, expect, vi } from "vitest";
import { render } from "ink-testing-library";
import React from "react";
import type {
ResponseInputMessageItem,
ResponseFunctionToolCallItem,
} from "openai/resources/responses/responses.mjs";
import HistoryOverlay from "../src/components/history-overlay";
// ---------------------------------------------------------------------------
// Module mocks *must* be registered *before* the module under test is imported
// so that Vitest can replace the dependency during evaluation.
// ---------------------------------------------------------------------------
// Mock ink's useInput to capture keyboard handlers
let keyboardHandler: ((input: string, key: any) => void) | undefined;
vi.mock("ink", async () => {
const actual = await vi.importActual("ink");
return {
...actual,
useInput: (handler: (input: string, key: any) => void) => {
keyboardHandler = handler;
},
};
});
// ---------------------------------------------------------------------------
// Test Helpers
// ---------------------------------------------------------------------------
function createUserMessage(content: string): ResponseInputMessageItem {
return {
type: "message",
role: "user",
id: `msg_${Math.random().toString(36).slice(2)}`,
content: [{ type: "input_text", text: content }],
};
}
function createFunctionCall(
name: string,
args: unknown,
): ResponseFunctionToolCallItem {
return {
type: "function_call",
name,
id: `fn_${Math.random().toString(36).slice(2)}`,
call_id: `call_${Math.random().toString(36).slice(2)}`,
arguments: JSON.stringify(args),
};
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("HistoryOverlay", () => {
describe("command mode", () => {
it("displays user messages", () => {
const items = [createUserMessage("hello"), createUserMessage("world")];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
const frame = lastFrame();
expect(frame).toContain("hello");
expect(frame).toContain("world");
});
it("displays shell commands", () => {
const items = [
createFunctionCall("shell", { cmd: ["ls", "-la"] }),
createFunctionCall("shell", { cmd: ["pwd"] }),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
const frame = lastFrame();
expect(frame).toContain("ls -la");
expect(frame).toContain("pwd");
});
it("displays file operations", () => {
const items = [createFunctionCall("read_file", { path: "test.txt" })];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
const frame = lastFrame();
expect(frame).toContain("read_file test.txt");
});
it("displays patch operations", () => {
const items = [
createFunctionCall("shell", {
cmd: [
"apply_patch",
"*** Begin Patch\n--- a/src/file1.txt\n+++ b/src/file1.txt\n@@ -1,5 +1,5 @@\n-const x = 1;\n+const x = 2;\n",
],
}),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Verify patch is displayed in command mode
let frame = lastFrame();
expect(frame).toContain("apply_patch");
expect(frame).toContain("src/file1.txt");
// Verify file is extracted in file mode
keyboardHandler?.("f", {});
frame = lastFrame();
expect(frame).toContain("src/file1.txt");
});
it("displays mixed content in chronological order", () => {
const items = [
createUserMessage("first message"),
createFunctionCall("shell", { cmd: ["echo", "hello"] }),
createUserMessage("second message"),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
const frame = lastFrame();
expect(frame).toContain("first message");
expect(frame).toContain("echo hello");
expect(frame).toContain("second message");
});
it("truncates long user messages", () => {
const shortMessage = "Hello";
const longMessage =
"This is a very long message that should be truncated because it exceeds the maximum length of 120 characters. We need to make sure it gets properly truncated with the right prefix and ellipsis.";
const items = [
createUserMessage(shortMessage),
createUserMessage(longMessage),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
const frame = lastFrame()!;
// Short message should have the > prefix
expect(frame).toContain(`> ${shortMessage}`);
// Long message should be truncated and contain:
// 1. The > prefix
expect(frame).toContain("> This is a very long message");
// 2. An ellipsis indicating truncation
expect(frame).toContain("…");
// 3. Not contain the full message
expect(frame).not.toContain(longMessage);
// Find the truncated message line
const lines = frame.split("\n");
const truncatedLine = lines.find((line) =>
line.includes("This is a very long message"),
)!;
// Verify it's not too long (allowing for some UI elements)
expect(truncatedLine.trim().length).toBeLessThan(150);
});
});
describe("file mode", () => {
it("displays files from shell commands", () => {
const items = [
createFunctionCall("shell", { cmd: ["cat", "/path/to/file"] }),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Switch to file mode
keyboardHandler?.("f", {});
const frame = lastFrame();
expect(frame).toContain("Files touched");
expect(frame).toContain("/path/to/file");
});
it("displays files from read operations", () => {
const items = [
createFunctionCall("read_file", { path: "/path/to/file" }),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Switch to file mode
keyboardHandler?.("f", {});
const frame = lastFrame();
expect(frame).toContain("Files touched");
expect(frame).toContain("/path/to/file");
});
it("displays files from patches", () => {
const items = [
createFunctionCall("shell", {
cmd: [
"apply_patch",
"*** Begin Patch\n--- a/src/file1.txt\n+++ b/src/file1.txt\n@@ -1,5 +1,5 @@\n-const x = 1;\n+const x = 2;\n",
],
}),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Switch to file mode
keyboardHandler?.("f", {});
const frame = lastFrame();
expect(frame).toContain("Files touched");
expect(frame).toContain("src/file1.txt");
});
});
describe("keyboard interaction", () => {
it("handles mode switching with 'c' and 'f' keys", () => {
const items = [
createUserMessage("hello"),
createFunctionCall("shell", { cmd: ["cat", "src/test.txt"] }),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Initial state (command mode)
let frame = lastFrame();
expect(frame).toContain("Commands run");
expect(frame).toContain("hello");
expect(frame).toContain("cat src/test.txt");
// Switch to files mode
keyboardHandler?.("f", {});
frame = lastFrame();
expect(frame).toContain("Files touched");
expect(frame).toContain("src/test.txt");
// Switch back to commands mode
keyboardHandler?.("c", {});
frame = lastFrame();
expect(frame).toContain("Commands run");
expect(frame).toContain("hello");
expect(frame).toContain("cat src/test.txt");
});
it("handles escape key", () => {
const onExit = vi.fn();
render(<HistoryOverlay items={[]} onExit={onExit} />);
keyboardHandler?.("", { escape: true });
expect(onExit).toHaveBeenCalled();
});
it("handles arrow keys for navigation", () => {
const items = [createUserMessage("first"), createUserMessage("second")];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Initial state shows first item selected
let frame = lastFrame();
expect(frame).toContain("› > first");
expect(frame).not.toContain("› > second");
// Move down - second item should be selected
keyboardHandler?.("", { downArrow: true });
frame = lastFrame();
expect(frame).toContain("› > second");
expect(frame).not.toContain("› > first");
// Move up - first item should be selected again
keyboardHandler?.("", { upArrow: true });
frame = lastFrame();
expect(frame).toContain("› > first");
expect(frame).not.toContain("› > second");
});
it("handles page up/down navigation", () => {
const items = Array.from({ length: 12 }, (_, i) =>
createUserMessage(`message ${i + 1}`),
);
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Initial position - first message selected
let frame = lastFrame();
expect(frame).toMatch(/│ › > message 1\s+│/); // message 1 should be selected
expect(frame).toMatch(/│ {3}> message 11\s+│/); // message 11 should be visible but not selected
// Page down moves by 10 - message 11 should be selected
keyboardHandler?.("", { pageDown: true });
frame = lastFrame();
expect(frame).toMatch(/│ {3}> message 1\s+│/); // message 1 should be visible but not selected
expect(frame).toMatch(/│ › > message 11\s+│/); // message 11 should be selected
});
it("handles vim-style navigation", () => {
const items = [
createUserMessage("first"),
createUserMessage("second"),
createUserMessage("third"),
];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Initial state should show first item selected
let frame = lastFrame();
expect(frame).toContain("› > first");
expect(frame).not.toContain("› > third"); // Make sure third is not selected initially
// Test G to jump to end - third should be selected
keyboardHandler?.("G", {});
frame = lastFrame();
expect(frame).toContain("› > third");
// Test g to jump to beginning - first should be selected again
keyboardHandler?.("g", {});
frame = lastFrame();
expect(frame).toContain("› > first");
});
});
describe("error handling", () => {
it("handles empty or invalid items", () => {
const items = [{ type: "invalid" } as any, null as any, undefined as any];
const { lastFrame } = render(
<HistoryOverlay items={items} onExit={vi.fn()} />,
);
// Should render without errors
expect(lastFrame()).toBeTruthy();
});
});
});
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect, vi } from "vitest";
import fs from "fs/promises";
import { createInputItem } from "../src/utils/input-utils.js";
describe("createInputItem", () => {
it("returns only text when no images provided", async () => {
const result = await createInputItem("hello", []);
expect(result).toEqual({
role: "user",
type: "message",
content: [{ type: "input_text", text: "hello" }],
});
});
it("includes image content for existing file", async () => {
const fakeBuffer = Buffer.from("fake image content");
const readSpy = vi
.spyOn(fs, "readFile")
.mockResolvedValue(fakeBuffer as any);
const result = await createInputItem("hello", ["dummy-path"]);
const expectedUrl = `data:application/octet-stream;base64,${fakeBuffer.toString(
"base64",
)}`;
expect(result.role).toBe("user");
expect(result.type).toBe("message");
expect(result.content.length).toBe(2);
const [textItem, imageItem] = result.content;
expect(textItem).toEqual({ type: "input_text", text: "hello" });
expect(imageItem).toEqual({
type: "input_image",
detail: "auto",
image_url: expectedUrl,
});
readSpy.mockRestore();
});
it("falls back to missing image text for non-existent file", async () => {
const filePath = "tests/__fixtures__/does-not-exist.png";
const result = await createInputItem("hello", [filePath]);
expect(result.content.length).toBe(2);
const fallbackItem = result.content[1];
expect(fallbackItem).toEqual({
type: "input_text",
text: "[missing image: does-not-exist.png]",
});
});
});
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, test } from "vitest";
import { openAiModelInfo } from "../src/utils/model-info";
describe("Model Info", () => {
test("supportedModelInfo contains expected models", () => {
expect(openAiModelInfo).toHaveProperty("gpt-4o");
expect(openAiModelInfo).toHaveProperty("gpt-4.1");
expect(openAiModelInfo).toHaveProperty("o3");
});
test("model info entries have required properties", () => {
Object.entries(openAiModelInfo).forEach(([_, info]) => {
expect(info).toHaveProperty("label");
expect(info).toHaveProperty("maxContextLength");
expect(typeof info.label).toBe("string");
expect(typeof info.maxContextLength).toBe("number");
});
});
});
@@ -44,7 +44,7 @@ describe("model-utils – offline resilience", () => {
"../src/utils/model-utils.js"
);
const supported = await isModelSupportedForResponses("o4-mini");
const supported = await isModelSupportedForResponses("openai", "o4-mini");
expect(supported).toBe(true);
});
@@ -63,8 +63,11 @@ describe("model-utils – offline resilience", () => {
"../src/utils/model-utils.js"
);
// Should resolve true despite the network failure
const supported = await isModelSupportedForResponses("some-model");
// Should resolve true despite the network failure.
const supported = await isModelSupportedForResponses(
"openai",
"some-model",
);
expect(supported).toBe(true);
});
});
+78
View File
@@ -0,0 +1,78 @@
import { describe, test, expect } from "vitest";
import {
calculateContextPercentRemaining,
maxTokensForModel,
} from "../src/utils/model-utils";
import { openAiModelInfo } from "../src/utils/model-info";
import type { ResponseItem } from "openai/resources/responses/responses.mjs";
describe("Model Utils", () => {
describe("openAiModelInfo", () => {
test("model info entries have required properties", () => {
Object.entries(openAiModelInfo).forEach(([_, info]) => {
expect(info).toHaveProperty("label");
expect(info).toHaveProperty("maxContextLength");
expect(typeof info.label).toBe("string");
expect(typeof info.maxContextLength).toBe("number");
});
});
});
describe("maxTokensForModel", () => {
test("returns correct token limit for known models", () => {
const knownModel = "gpt-4o";
const expectedTokens = openAiModelInfo[knownModel].maxContextLength;
expect(maxTokensForModel(knownModel)).toBe(expectedTokens);
});
test("handles models with size indicators in their names", () => {
expect(maxTokensForModel("some-model-32k")).toBe(32000);
expect(maxTokensForModel("some-model-16k")).toBe(16000);
expect(maxTokensForModel("some-model-8k")).toBe(8000);
expect(maxTokensForModel("some-model-4k")).toBe(4000);
});
test("defaults to 128k for unknown models not in the registry", () => {
expect(maxTokensForModel("completely-unknown-model")).toBe(128000);
});
});
describe("calculateContextPercentRemaining", () => {
test("returns 100% for empty items", () => {
const result = calculateContextPercentRemaining([], "gpt-4o");
expect(result).toBe(100);
});
test("calculates percentage correctly for non-empty items", () => {
const mockItems: Array<ResponseItem> = [
{
id: "test-id",
type: "message",
role: "user",
status: "completed",
content: [
{
type: "input_text",
text: "A".repeat(
openAiModelInfo["gpt-4o"].maxContextLength * 0.25 * 4,
),
},
],
} as ResponseItem,
];
const result = calculateContextPercentRemaining(mockItems, "gpt-4o");
expect(result).toBeCloseTo(75, 0);
});
test("handles models that are not in the registry", () => {
const mockItems: Array<ResponseItem> = [];
const result = calculateContextPercentRemaining(
mockItems,
"unknown-model",
);
expect(result).toBe(100);
});
});
});
@@ -57,7 +57,7 @@ async function type(
await flush();
}
/** Build a set of no‑op callbacks so <TerminalChatInput> renders with minimal
/** Build a set of no-op callbacks so <TerminalChatInput> renders with minimal
* scaffolding.
*/
function stubProps(): any {
@@ -0,0 +1,49 @@
// Regression test: Terminals with modifyOtherKeys=1 emit CSI~ sequence for
// Shift+Enter: ESC [ 27 ; mod ; 13 ~. The editor must treat Shift+Enter as
// newline (without submitting) and Ctrl+Enter as submit.
import { renderTui } from "./ui-test-helpers.js";
import MultilineTextEditor from "../src/components/chat/multiline-editor.js";
import * as React from "react";
import { describe, it, expect, vi } from "vitest";
async function type(
stdin: NodeJS.WritableStream,
text: string,
flush: () => Promise<void>,
) {
stdin.write(text);
await flush();
}
describe("MultilineTextEditor – Shift+Enter with modifyOtherKeys=1", () => {
it("inserts newline, does NOT submit", async () => {
const onSubmit = vi.fn();
const { stdin, lastFrameStripped, flush, cleanup } = renderTui(
React.createElement(MultilineTextEditor, {
height: 5,
width: 20,
initialText: "",
onSubmit,
}),
);
await flush();
await type(stdin, "abc", flush);
// Shift+Enter => ESC [27;2;13~
await type(stdin, "\u001B[27;2;13~", flush);
await type(stdin, "def", flush);
const frame = lastFrameStripped();
expect(frame).toMatch(/abc/);
expect(frame).toMatch(/def/);
// newline inserted -> at least 2 lines
expect(frame.split("\n").length).toBeGreaterThanOrEqual(2);
expect(onSubmit).not.toHaveBeenCalled();
cleanup();
});
});
@@ -0,0 +1,66 @@
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
import which from "which";
import { detectInstallerByPath } from "../src/utils/package-manager-detector";
import { execFileSync } from "node:child_process";
vi.mock("which", () => ({
default: { sync: vi.fn() },
}));
vi.mock("node:child_process", () => ({ execFileSync: vi.fn() }));
describe("detectInstallerByPath()", () => {
const originalArgv = process.argv;
const fakeBinDirs = {
// `npm prefix -g` returns the global “prefix” (we’ll add `/bin` when detecting)
npm: "/usr/local",
pnpm: "/home/user/.local/share/pnpm/bin",
bun: "/Users/test/.bun/bin",
} as const;
beforeEach(() => {
vi.resetAllMocks();
// Pretend each manager binary is on PATH:
vi.mocked(which.sync).mockImplementation(() => "/fake/path");
vi.mocked(execFileSync).mockImplementation(
(
cmd: string,
_args: ReadonlyArray<string> = [],
_options: unknown,
): string => {
return fakeBinDirs[cmd as keyof typeof fakeBinDirs];
},
);
});
afterEach(() => {
// Restore the real argv so tests don’t leak
process.argv = originalArgv;
});
it.each(Object.entries(fakeBinDirs))(
"detects %s when invoked from its global-bin",
async (manager, binDir) => {
// Simulate the shim living under that binDir
process.argv =
manager === "npm"
? [process.argv[0]!, `${binDir}/bin/my-cli`]
: [process.argv[0]!, `${binDir}/my-cli`];
const detected = await detectInstallerByPath();
expect(detected).toBe(manager);
},
);
it("returns undefined if argv[1] is missing", async () => {
process.argv = [process.argv[0]!];
expect(await detectInstallerByPath()).toBeUndefined();
expect(execFileSync).not.toHaveBeenCalled();
});
it("returns undefined if shim isn't in any manager's bin", async () => {
// stub execFileSync to some other dirs
vi.mocked(execFileSync).mockImplementation(() => "/some/other/dir");
process.argv = [process.argv[0]!, "/home/user/.node_modules/.bin/my-cli"];
expect(await detectInstallerByPath()).toBeUndefined();
});
});
+19
View File
@@ -0,0 +1,19 @@
import { describe, it, expect } from "vitest";
import { parse } from "shell-quote";
/* eslint-disable no-console */
describe("shell-quote parse with pipes", () => {
it("should correctly parse a command with a pipe", () => {
const cmd = 'grep -n "finally:" some-file | head';
const tokens = parse(cmd);
console.log("Parsed tokens:", JSON.stringify(tokens, null, 2));
// Check if any token has an 'op' property
const hasOpToken = tokens.some(
(token) => typeof token === "object" && "op" in token,
);
expect(hasOpToken).toBe(true);
});
});
+42 -34
View File
@@ -6,7 +6,6 @@ import { exec as rawExec } from "../src/utils/agent/sandbox/raw-exec.js";
// the direct child. The original logic only sent `SIGTERM` to the immediate
// child which meant that grandchildren (for instance when running through a
// `bash -c` wrapper) were left running and turned into "zombie" processes.
// Strategy:
// 1. Start a Bash shell that spawns a long‑running `sleep`, prints the PID
// of that `sleep`, and then waits forever. This guarantees we can later
@@ -15,7 +14,6 @@ import { exec as rawExec } from "../src/utils/agent/sandbox/raw-exec.js";
// 3. After `rawExec()` resolves we probe the previously printed PID with
// `process.kill(pid, 0)`. If the call throws `ESRCH` the process no
// longer exists – the desired outcome. Otherwise the test fails.
// The negative‑PID process‑group trick employed by the fixed implementation is
// POSIX‑only. On Windows we skip the test.
@@ -26,49 +24,59 @@ describe("rawExec – abort kills entire process group", () => {
}
const abortController = new AbortController();
// Bash script: spawn `sleep 30` in background, print its PID, then wait.
const script = "sleep 30 & pid=$!; echo $pid; wait $pid";
const cmd = ["bash", "-c", script];
// Kick off the command.
const execPromise = rawExec(cmd, {}, [], abortController.signal);
// Start a bash shell that:
// - spawns a background `sleep 30`
// - prints the PID of the `sleep`
// - waits for `sleep` to exit
const { stdout, exitCode } = await (async () => {
const p = rawExec(cmd, {}, [], abortController.signal);
// Give Bash a tiny bit of time to start and print the PID.
await new Promise((r) => setTimeout(r, 100));
// Give Bash a tiny bit of time to start and print the PID.
await new Promise((r) => setTimeout(r, 100));
// Cancel the task – this should kill *both* bash and the inner sleep.
abortController.abort();
// Cancel the task – this should kill *both* bash and the inner sleep.
abortController.abort();
const { exitCode, stdout } = await execPromise;
// Wait for rawExec to resolve after aborting
return p;
})();
// We expect a non‑zero exit code because the process was killed.
expect(exitCode).not.toBe(0);
// Attempt to extract the grand‑child PID from stdout.
const pidMatch = /^(\d+)/.exec(stdout.trim());
if (pidMatch) {
const sleepPid = Number(pidMatch[1]);
// Verify that the sleep process is no longer alive.
let alive = true;
try {
process.kill(sleepPid, 0);
} catch (error: any) {
// Check if error is ESRCH (No such process)
if (error.code === "ESRCH") {
alive = false; // Process is dead, as expected.
} else {
throw error;
}
}
expect(alive).toBe(false);
} else {
// If PID was not printed, it implies bash was killed very early.
// The test passes implicitly in this scenario as the abort mechanism
// successfully stopped the command execution quickly.
expect(true).toBe(true);
// Extract the PID of the sleep process that bash printed
const pid = Number(stdout.trim().match(/^\d+/)?.[0]);
if (pid) {
// Confirm that the sleep process is no longer alive
await ensureProcessGone(pid);
}
});
});
/**
* Waits until a process no longer exists, or throws after timeout.
* @param pid - The process ID to check
* @throws {Error} If the process is still alive after 500ms
*/
async function ensureProcessGone(pid: number) {
const timeout = 500;
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
try {
process.kill(pid, 0); // check if process still exists
await new Promise((r) => setTimeout(r, 50)); // wait and retry
} catch (e: any) {
if (e.code === "ESRCH") {
return; // process is gone — success
}
throw e; // unexpected error — rethrow
}
}
throw new Error(
`Process with PID ${pid} failed to terminate within ${timeout}ms`,
);
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect } from "vitest";
import { parse } from "shell-quote";
/* eslint-disable no-console */
// Recreate the requiresShell function for testing
function requiresShell(cmd: Array<string>): boolean {
// If the command is a single string that contains shell operators,
// it needs to be run with shell: true
if (cmd.length === 1 && cmd[0] !== undefined) {
const tokens = parse(cmd[0]) as Array<any>;
console.log(
`Parsing argument: "${cmd[0]}", tokens:`,
JSON.stringify(tokens, null, 2),
);
return tokens.some((token) => typeof token === "object" && "op" in token);
}
// If the command is split into multiple arguments, we don't need shell: true
// even if one of the arguments is a shell operator like '|'
cmd.forEach((arg) => {
const tokens = parse(arg) as Array<any>;
console.log(
`Parsing argument: "${arg}", tokens:`,
JSON.stringify(tokens, null, 2),
);
});
console.log("Result for separate arguments: false");
return false;
}
describe("requiresShell function", () => {
it("should detect pipe in a single argument", () => {
const cmd = ['grep -n "finally:" some-file | head'];
expect(requiresShell(cmd)).toBe(true);
});
it("should not detect pipe in separate arguments", () => {
const cmd = ["grep", "-n", "finally:", "some-file", "|", "head"];
const result = requiresShell(cmd);
console.log("Result for separate arguments:", result);
expect(result).toBe(false);
});
it("should handle other shell operators", () => {
const cmd = ["echo hello && echo world"];
expect(requiresShell(cmd)).toBe(true);
});
});
@@ -0,0 +1,815 @@
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
import type { OpenAI } from "openai";
import type {
ResponseCreateInput,
ResponseEvent,
} from "../src/utils/responses";
import type {
ResponseInputItem,
Tool,
ResponseCreateParams,
ResponseFunctionToolCallItem,
ResponseFunctionToolCall,
} from "openai/resources/responses/responses";
// Define specific types for streaming and non-streaming params
type ResponseCreateParamsStreaming = ResponseCreateParams & { stream: true };
type ResponseCreateParamsNonStreaming = ResponseCreateParams & {
stream?: false;
};
// Define additional type guard for tool calls done event
type ToolCallsDoneEvent = Extract<
ResponseEvent,
{ type: "response.function_call_arguments.done" }
>;
type OutputTextDeltaEvent = Extract<
ResponseEvent,
{ type: "response.output_text.delta" }
>;
type OutputTextDoneEvent = Extract<
ResponseEvent,
{ type: "response.output_text.done" }
>;
type ResponseCompletedEvent = Extract<
ResponseEvent,
{ type: "response.completed" }
>;
// Mock state to control the OpenAI client behavior
const openAiState: {
createSpy?: ReturnType<typeof vi.fn>;
createStreamSpy?: ReturnType<typeof vi.fn>;
} = {};
// Mock the OpenAI client
vi.mock("openai", () => {
class FakeOpenAI {
public chat = {
completions: {
create: (...args: Array<any>) => {
if (args[0]?.stream) {
return openAiState.createStreamSpy!(...args);
}
return openAiState.createSpy!(...args);
},
},
};
}
return {
__esModule: true,
default: FakeOpenAI,
};
});
// Helper function to create properly typed test inputs
function createTestInput(options: {
model: string;
userMessage: string;
stream?: boolean;
tools?: Array<Tool>;
previousResponseId?: string;
}): ResponseCreateInput {
const message: ResponseInputItem.Message = {
type: "message",
role: "user",
content: [
{
type: "input_text" as const,
text: options.userMessage,
},
],
};
const input: ResponseCreateInput = {
model: options.model,
input: [message],
};
if (options.stream !== undefined) {
// @ts-expect-error TypeScript doesn't recognize this is valid
input.stream = options.stream;
}
if (options.tools) {
input.tools = options.tools;
}
if (options.previousResponseId) {
input.previous_response_id = options.previousResponseId;
}
return input;
}
// Type guard for function call content
function isFunctionCall(content: any): content is ResponseFunctionToolCall {
return (
content && typeof content === "object" && content.type === "function_call"
);
}
// Additional type guard for tool call
function isToolCall(item: any): item is ResponseFunctionToolCallItem {
return item && typeof item === "object" && item.type === "function";
}
// Type guards for various event types
export function _isToolCallsDoneEvent(
event: ResponseEvent,
): event is ToolCallsDoneEvent {
return event.type === "response.function_call_arguments.done";
}
function isOutputTextDeltaEvent(
event: ResponseEvent,
): event is OutputTextDeltaEvent {
return event.type === "response.output_text.delta";
}
function isOutputTextDoneEvent(
event: ResponseEvent,
): event is OutputTextDoneEvent {
return event.type === "response.output_text.done";
}
function isResponseCompletedEvent(
event: ResponseEvent,
): event is ResponseCompletedEvent {
return event.type === "response.completed";
}
// Helper function to create a mock stream for tool calls testing
function createToolCallsStream() {
async function* fakeToolStream() {
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: { role: "assistant" },
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: {
tool_calls: [
{
index: 0,
id: "call_123",
type: "function",
function: { name: "get_weather" },
},
],
},
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: {
tool_calls: [
{
index: 0,
function: {
arguments: '{"location":"San Franci',
},
},
],
},
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: {
tool_calls: [
{
index: 0,
function: {
arguments: 'sco"}',
},
},
],
},
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: {},
finish_reason: "tool_calls",
index: 0,
},
],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
};
}
return fakeToolStream();
}
describe("responsesCreateViaChatCompletions", () => {
// Using any type here to avoid import issues
let responsesModule: any;
beforeEach(async () => {
vi.resetModules();
responsesModule = await import("../src/utils/responses");
});
afterEach(() => {
vi.resetAllMocks();
openAiState.createSpy = undefined;
openAiState.createStreamSpy = undefined;
});
describe("non-streaming mode", () => {
it("should convert basic user message to chat completions format", async () => {
// Setup mock response
openAiState.createSpy = vi.fn().mockResolvedValue({
id: "chat-123",
model: "gpt-4o",
choices: [
{
message: {
role: "assistant",
content: "This is a test response",
},
finish_reason: "stop",
},
],
usage: {
prompt_tokens: 10,
completion_tokens: 5,
total_tokens: 15,
},
});
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
const inputMessage = createTestInput({
model: "gpt-4o",
userMessage: "Hello world",
stream: false,
});
const result = await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
inputMessage as ResponseCreateParams & { stream?: false | undefined },
);
// Verify OpenAI was called with correct parameters
expect(openAiState.createSpy).toHaveBeenCalledTimes(1);
// Skip type checking for mock objects in tests - this is acceptable for test code
// @ts-ignore
const callArgs = openAiState.createSpy?.mock?.calls?.[0]?.[0];
if (callArgs) {
expect(callArgs.model).toBe("gpt-4o");
expect(callArgs.messages).toEqual([
{ role: "user", content: "Hello world" },
]);
expect(callArgs.stream).toBe(false);
}
// Verify result format
expect(result.id).toBeDefined();
expect(result.object).toBe("response");
expect(result.model).toBe("gpt-4o");
expect(result.status).toBe("completed");
expect(result.output).toHaveLength(1);
// Use type guard to check the output item type
const outputItem = result.output[0];
expect(outputItem).toBeDefined();
if (outputItem && outputItem.type === "message") {
expect(outputItem.role).toBe("assistant");
expect(outputItem.content).toHaveLength(1);
const content = outputItem.content[0];
if (content && content.type === "output_text") {
expect(content.text).toBe("This is a test response");
}
}
expect(result.usage?.total_tokens).toBe(15);
});
it("should handle function calling correctly", async () => {
// Setup mock response with tool calls
openAiState.createSpy = vi.fn().mockResolvedValue({
id: "chat-456",
model: "gpt-4o",
choices: [
{
message: {
role: "assistant",
content: null,
tool_calls: [
{
id: "call_abc123",
type: "function",
function: {
name: "get_weather",
arguments: JSON.stringify({ location: "New York" }),
},
},
],
},
finish_reason: "tool_calls",
},
],
usage: {
prompt_tokens: 15,
completion_tokens: 8,
total_tokens: 23,
},
});
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
// Define function tool correctly
const weatherTool = {
type: "function" as const,
name: "get_weather",
description: "Get the current weather",
strict: true,
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
};
const inputMessage = createTestInput({
model: "gpt-4o",
userMessage: "What's the weather in New York?",
tools: [weatherTool as any],
stream: false,
});
const result = await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
inputMessage as ResponseCreateParams & { stream: false },
);
// Verify OpenAI was called with correct parameters
expect(openAiState.createSpy).toHaveBeenCalledTimes(1);
// Skip type checking for mock objects in tests
// @ts-ignore
const callArgs = openAiState.createSpy?.mock?.calls?.[0]?.[0];
if (callArgs) {
expect(callArgs.model).toBe("gpt-4o");
expect(callArgs.tools).toHaveLength(1);
expect(callArgs.tools[0].function.name).toBe("get_weather");
}
// Verify function call output directly instead of trying to check type
expect(result.output).toHaveLength(1);
const outputItem = result.output[0];
if (outputItem && outputItem.type === "message") {
const content = outputItem.content[0];
// Use the type guard function
expect(isFunctionCall(content)).toBe(true);
// Using type assertion after type guard check
if (isFunctionCall(content)) {
// These properties should exist on ResponseFunctionToolCall
expect((content as any).name).toBe("get_weather");
expect(JSON.parse((content as any).arguments).location).toBe(
"New York",
);
}
}
});
it("should preserve conversation history", async () => {
// First interaction
openAiState.createSpy = vi.fn().mockResolvedValue({
id: "chat-789",
model: "gpt-4o",
choices: [
{
message: {
role: "assistant",
content: "Hello! How can I help you?",
},
finish_reason: "stop",
},
],
usage: { prompt_tokens: 5, completion_tokens: 6, total_tokens: 11 },
});
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
const firstInput = createTestInput({
model: "gpt-4o",
userMessage: "Hi there",
stream: false,
});
const firstResponse =
await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
firstInput as unknown as ResponseCreateParamsNonStreaming & {
stream?: false | undefined;
},
);
// Reset the mock for second interaction
openAiState.createSpy.mockReset();
openAiState.createSpy = vi.fn().mockResolvedValue({
id: "chat-790",
model: "gpt-4o",
choices: [
{
message: {
role: "assistant",
content: "I'm an AI assistant created by Anthropic.",
},
finish_reason: "stop",
},
],
usage: { prompt_tokens: 15, completion_tokens: 10, total_tokens: 25 },
});
// Second interaction with previous_response_id
const secondInput = createTestInput({
model: "gpt-4o",
userMessage: "Who are you?",
previousResponseId: firstResponse.id,
stream: false,
});
await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
secondInput as unknown as ResponseCreateParamsNonStreaming & {
stream?: false | undefined;
},
);
// Verify history was included in second call
expect(openAiState.createSpy).toHaveBeenCalledTimes(1);
// Skip type checking for mock objects in tests
// @ts-ignore
const secondCallArgs = openAiState.createSpy?.mock?.calls?.[0]?.[0];
if (secondCallArgs) {
// Should have 3 messages: original user, assistant response, and new user message
expect(secondCallArgs.messages).toHaveLength(3);
expect(secondCallArgs.messages[0].role).toBe("user");
expect(secondCallArgs.messages[0].content).toBe("Hi there");
expect(secondCallArgs.messages[1].role).toBe("assistant");
expect(secondCallArgs.messages[1].content).toBe(
"Hello! How can I help you?",
);
expect(secondCallArgs.messages[2].role).toBe("user");
expect(secondCallArgs.messages[2].content).toBe("Who are you?");
}
});
it("handles tools correctly", async () => {
const testFunction = {
type: "function" as const,
name: "get_weather",
description: "Get the weather",
strict: true,
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The location to get the weather for",
},
},
required: ["location"],
},
};
// Mock response with a tool call
openAiState.createSpy = vi.fn().mockResolvedValue({
id: "chatcmpl-123",
created: Date.now(),
model: "gpt-4o",
object: "chat.completion",
choices: [
{
message: {
role: "assistant",
content: null,
tool_calls: [
{
id: "call_123",
type: "function",
function: {
name: "get_weather",
arguments: JSON.stringify({ location: "San Francisco" }),
},
},
],
},
finish_reason: "tool_calls",
index: 0,
},
],
});
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
const inputMessage = createTestInput({
model: "gpt-4o",
userMessage: "What's the weather in San Francisco?",
tools: [testFunction],
});
const result = await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
inputMessage as unknown as ResponseCreateParamsNonStreaming,
);
expect(result.status).toBe("requires_action");
// Cast result to include required_action to address TypeScript issues
const resultWithAction = result as any;
// Add null checks for required_action
expect(resultWithAction.required_action).not.toBeNull();
expect(resultWithAction.required_action?.type).toBe(
"submit_tool_outputs",
);
// Safely access the tool calls with proper null checks
const toolCalls =
resultWithAction.required_action?.submit_tool_outputs?.tool_calls || [];
expect(toolCalls.length).toBe(1);
if (toolCalls.length > 0) {
const toolCall = toolCalls[0];
expect(toolCall.type).toBe("function");
if (isToolCall(toolCall)) {
// Access with type assertion after type guard
expect((toolCall as any).function.name).toBe("get_weather");
expect(JSON.parse((toolCall as any).function.arguments)).toEqual({
location: "San Francisco",
});
}
}
// Only check model, messages, and tools in exact match
expect(openAiState.createSpy).toHaveBeenCalledWith(
expect.objectContaining({
model: "gpt-4o",
messages: [
{
role: "user",
content: "What's the weather in San Francisco?",
},
],
tools: [
expect.objectContaining({
type: "function",
function: {
name: "get_weather",
description: "Get the weather",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The location to get the weather for",
},
},
required: ["location"],
},
},
}),
],
}),
);
});
});
describe("streaming mode", () => {
it("should handle streaming responses correctly", async () => {
// Mock an async generator for streaming
async function* fakeStream() {
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: { role: "assistant" },
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: { content: "Hello" },
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: { content: " world" },
finish_reason: null,
index: 0,
},
],
};
yield {
id: "chatcmpl-123",
model: "gpt-4o",
choices: [
{
delta: {},
finish_reason: "stop",
index: 0,
},
],
usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 },
};
}
openAiState.createStreamSpy = vi.fn().mockResolvedValue(fakeStream());
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
const inputMessage = createTestInput({
model: "gpt-4o",
userMessage: "Say hello",
stream: true,
});
const streamGenerator =
await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
inputMessage as unknown as ResponseCreateParamsStreaming & {
stream: true;
},
);
// Collect all events from the stream
const events: Array<ResponseEvent> = [];
for await (const event of streamGenerator) {
events.push(event);
}
// Verify stream generation
expect(events.length).toBeGreaterThan(0);
// Check initial events
const firstEvent = events[0];
const secondEvent = events[1];
expect(firstEvent?.type).toBe("response.created");
expect(secondEvent?.type).toBe("response.in_progress");
// Find content delta events using proper type guard
const deltaEvents = events.filter(isOutputTextDeltaEvent);
// Should have two delta events for "Hello" and " world"
expect(deltaEvents).toHaveLength(2);
expect(deltaEvents[0]?.delta).toBe("Hello");
expect(deltaEvents[1]?.delta).toBe(" world");
// Check final completion event with type guard
const completionEvent = events.find(isResponseCompletedEvent);
expect(completionEvent).toBeDefined();
if (completionEvent) {
expect(completionEvent.response.status).toBe("completed");
}
// Text should be concatenated
const textDoneEvent = events.find(isOutputTextDoneEvent);
expect(textDoneEvent).toBeDefined();
if (textDoneEvent) {
expect(textDoneEvent.text).toBe("Hello world");
}
});
it("handles streaming with tool calls", async () => {
// Mock a streaming response with tool calls
const mockStream = createToolCallsStream();
openAiState.createStreamSpy = vi.fn().mockReturnValue(mockStream);
const openaiClient = new (await import("openai")).default({
apiKey: "test-key",
}) as unknown as OpenAI;
const testFunction = {
type: "function" as const,
name: "get_weather",
description: "Get the current weather",
strict: true,
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
};
const inputMessage = createTestInput({
model: "gpt-4o",
userMessage: "What's the weather in San Francisco?",
tools: [testFunction],
stream: true,
});
const streamGenerator =
await responsesModule.responsesCreateViaChatCompletions(
openaiClient,
inputMessage as unknown as ResponseCreateParamsStreaming,
);
// Collect all events from the stream
const events: Array<ResponseEvent> = [];
for await (const event of streamGenerator) {
events.push(event);
}
// Verify stream generation
expect(events.length).toBeGreaterThan(0);
// Look for function call related events of any type related to tool calls
const toolCallEvents = events.filter(
(event) =>
event.type.includes("function_call") ||
event.type.includes("tool") ||
(event.type === "response.output_item.added" &&
"item" in event &&
event.item?.type === "function_call"),
);
expect(toolCallEvents.length).toBeGreaterThan(0);
// Check if we have the completed event which should contain the final result
const completedEvent = events.find(isResponseCompletedEvent);
expect(completedEvent).toBeDefined();
if (completedEvent) {
// Get the function call from the output array
const functionCallItem = completedEvent.response.output.find(
(item) => item.type === "function_call",
);
expect(functionCallItem).toBeDefined();
if (functionCallItem && functionCallItem.type === "function_call") {
expect(functionCallItem.name).toBe("get_weather");
// The arguments is a JSON string, but we can check if it includes San Francisco
expect(functionCallItem.arguments).toContain("San Francisco");
}
}
});
});
});
+39
View File
@@ -0,0 +1,39 @@
import { test, expect } from "vitest";
import { SLASH_COMMANDS, type SlashCommand } from "../src/utils/slash-commands";
test("SLASH_COMMANDS includes expected commands", () => {
const commands = SLASH_COMMANDS.map((c: SlashCommand) => c.command);
expect(commands).toContain("/clear");
expect(commands).toContain("/compact");
expect(commands).toContain("/history");
expect(commands).toContain("/help");
expect(commands).toContain("/model");
expect(commands).toContain("/approval");
expect(commands).toContain("/clearhistory");
expect(commands).toContain("/diff");
});
test("filters slash commands by prefix", () => {
const prefix = "/c";
const filtered = SLASH_COMMANDS.filter((c: SlashCommand) =>
c.command.startsWith(prefix),
);
const names = filtered.map((c: SlashCommand) => c.command);
expect(names).toEqual(
expect.arrayContaining(["/clear", "/clearhistory", "/compact"]),
);
expect(names).not.toEqual(
expect.arrayContaining(["/history", "/help", "/model", "/approval"]),
);
const emptyPrefixFiltered = SLASH_COMMANDS.filter((c: SlashCommand) =>
c.command.startsWith(""),
);
const emptyPrefixNames = emptyPrefixFiltered.map(
(c: SlashCommand) => c.command,
);
expect(emptyPrefixNames).toEqual(
expect.arrayContaining(SLASH_COMMANDS.map((c: SlashCommand) => c.command)),
);
expect(emptyPrefixNames).toHaveLength(SLASH_COMMANDS.length);
});
@@ -0,0 +1,46 @@
import React from "react";
import { describe, it, expect } from "vitest";
import type { ComponentProps } from "react";
import { renderTui } from "./ui-test-helpers.js";
import TerminalChatCompletions from "../src/components/chat/terminal-chat-completions.js";
describe("TerminalChatCompletions", () => {
const baseProps: ComponentProps<typeof TerminalChatCompletions> = {
completions: ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"],
displayLimit: 3,
selectedCompletion: 0,
};
it("renders visible completions within displayLimit", async () => {
const { lastFrameStripped } = renderTui(
<TerminalChatCompletions {...baseProps} />,
);
const frame = lastFrameStripped();
expect(frame).toContain("Option 1");
expect(frame).toContain("Option 2");
expect(frame).toContain("Option 3");
expect(frame).not.toContain("Option 4");
});
it("centers the selected completion in the visible list", async () => {
const { lastFrameStripped } = renderTui(
<TerminalChatCompletions {...baseProps} selectedCompletion={2} />,
);
const frame = lastFrameStripped();
expect(frame).toContain("Option 2");
expect(frame).toContain("Option 3");
expect(frame).toContain("Option 4");
expect(frame).not.toContain("Option 1");
});
it("adjusts when selectedCompletion is near the end", async () => {
const { lastFrameStripped } = renderTui(
<TerminalChatCompletions {...baseProps} selectedCompletion={4} />,
);
const frame = lastFrameStripped();
expect(frame).toContain("Option 3");
expect(frame).toContain("Option 4");
expect(frame).toContain("Option 5");
expect(frame).not.toContain("Option 2");
});
});
@@ -17,12 +17,14 @@ describe("TerminalChatInput compact command", () => {
setItems: () => {},
contextLeftPercent: 10,
openOverlay: () => {},
openDiffOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
onCompact: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
};
const { lastFrameStripped } = renderTui(<TerminalChatInput {...props} />);
const frame = lastFrameStripped();
@@ -0,0 +1,157 @@
import React from "react";
import type { ComponentProps } from "react";
import { renderTui } from "./ui-test-helpers.js";
import TerminalChatInput from "../src/components/chat/terminal-chat-input.js";
import { describe, it, expect, vi } from "vitest";
// Helper that lets us type and then immediately flush ink's async timers
async function type(
stdin: NodeJS.WritableStream,
text: string,
flush: () => Promise<void>,
) {
stdin.write(text);
await flush();
}
// Mock the createInputItem function to avoid filesystem operations
vi.mock("../src/utils/input-utils.js", () => ({
createInputItem: vi.fn(async (text: string) => ({
role: "user",
type: "message",
content: [{ type: "input_text", text }],
})),
}));
describe("TerminalChatInput multiline functionality", () => {
it("renders the multiline editor component", async () => {
const props: ComponentProps<typeof TerminalChatInput> = {
isNew: false,
loading: false,
submitInput: () => {},
confirmationPrompt: null,
explanation: undefined,
submitConfirmation: () => {},
setLastResponseId: () => {},
setItems: () => {},
contextLeftPercent: 50,
openOverlay: () => {},
openDiffOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
onCompact: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
};
const { lastFrameStripped } = renderTui(<TerminalChatInput {...props} />);
const frame = lastFrameStripped();
// Check that the help text mentions shift+enter for new line
expect(frame).toContain("shift+enter for new line");
});
it("allows multiline input with shift+enter", async () => {
const submitInput = vi.fn();
const props: ComponentProps<typeof TerminalChatInput> = {
isNew: false,
loading: false,
submitInput,
confirmationPrompt: null,
explanation: undefined,
submitConfirmation: () => {},
setLastResponseId: () => {},
setItems: () => {},
contextLeftPercent: 50,
openOverlay: () => {},
openDiffOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
onCompact: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
};
const { stdin, lastFrameStripped, flush, cleanup } = renderTui(
<TerminalChatInput {...props} />,
);
// Type some text
await type(stdin, "first line", flush);
// Send Shift+Enter (CSI-u format)
await type(stdin, "\u001B[13;2u", flush);
// Type more text
await type(stdin, "second line", flush);
// Check that both lines are visible in the editor
const frame = lastFrameStripped();
expect(frame).toContain("first line");
expect(frame).toContain("second line");
// Submit the multiline input with Enter
await type(stdin, "\r", flush);
// Check that submitInput was called with the multiline text
expect(submitInput).toHaveBeenCalledTimes(1);
cleanup();
});
it("allows multiline input with shift+enter (modifyOtherKeys=1 format)", async () => {
const submitInput = vi.fn();
const props: ComponentProps<typeof TerminalChatInput> = {
isNew: false,
loading: false,
submitInput,
confirmationPrompt: null,
explanation: undefined,
submitConfirmation: () => {},
setLastResponseId: () => {},
setItems: () => {},
contextLeftPercent: 50,
openOverlay: () => {},
openDiffOverlay: () => {},
openModelOverlay: () => {},
openApprovalOverlay: () => {},
openHelpOverlay: () => {},
onCompact: () => {},
interruptAgent: () => {},
active: true,
thinkingSeconds: 0,
};
const { stdin, lastFrameStripped, flush, cleanup } = renderTui(
<TerminalChatInput {...props} />,
);
// Type some text
await type(stdin, "first line", flush);
// Send Shift+Enter (modifyOtherKeys=1 format)
await type(stdin, "\u001B[27;2;13~", flush);
// Type more text
await type(stdin, "second line", flush);
// Check that both lines are visible in the editor
const frame = lastFrameStripped();
expect(frame).toContain("first line");
expect(frame).toContain("second line");
// Submit the multiline input with Enter
await type(stdin, "\r", flush);
// Check that submitInput was called with the multiline text
expect(submitInput).toHaveBeenCalledTimes(1);
cleanup();
});
});
+1 -1
View File
@@ -127,7 +127,7 @@ describe("TextBuffer – basic editing parity with Rust suite", () => {
expect(buf.getCursor()).toEqual([0, 2]); // after 'b'
});
it("is a no‑op at the very beginning of the buffer", () => {
it("is a no-op at the very beginning of the buffer", () => {
const buf = new TextBuffer("ab");
buf.backspace(); // caret starts at (0,0)
+1 -1
View File
@@ -26,7 +26,7 @@ vi.mock("../src/components/select-input/select-input.js", () => {
// Ink's <TextInput> toggles raw‑mode which calls .ref() / .unref() on stdin.
// The test environment's mock streams don't implement those methods, so we
// polyfill them to no‑ops on the prototype *before* the component tree mounts.
// polyfill them to no-ops on the prototype *before* the component tree mounts.
import { EventEmitter } from "node:events";
if (!(EventEmitter.prototype as any).ref) {
(EventEmitter.prototype as any).ref = () => {};