repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/activity/__tests__/terminal.test.ts
Rawimport { copyFile, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { openTerminal } from "../terminal.ts";
import type { ProcessStart, TerminalHandle } from "../types.ts";
const handles: TerminalHandle[] = [];
afterEach(async () => {
await Promise.all(handles.splice(0).map((handle) => handle.dispose()));
});
function command(
source: string,
options: Partial<ProcessStart> = {},
): ProcessStart {
return {
kind: "terminal",
command: process.execPath,
args: ["-e", source],
...options,
};
}
async function terminalFor(spec: ProcessStart, cwd = process.cwd()) {
const output: string[] = [];
let resolveExit!: (value: { code: number | null; error?: string }) => void;
const exited = new Promise<{ code: number | null; error?: string }>(
(resolve) => {
resolveExit = resolve;
},
);
const handle = await openTerminal(spec, cwd, {
data: (text) => output.push(text),
changed() {},
exit: (code, error) => resolveExit({ code, error }),
});
handles.push(handle);
return { handle, output, exited };
}
describe("real native terminal", () => {
it("projects human selection styles without exposing child controls or styled tool data", async () => {
const session = await terminalFor(
command(
`process.stdout.write(${JSON.stringify("\x1b]52;c;c2VjcmV0\x07\x1b_pi:c\x07\x1b[7;48;2;12;34;56mSELECT \x1b[0m")})`,
{ cols: 20, rows: 5 },
),
);
await session.exited;
const view = session.handle.view();
expect(view.lines[0]).toContain("\x1b[0;7;48;2;12;34;56mSELECT \x1b[0m");
expect(view.lines.join("")).not.toContain("\x1b]");
expect(view.lines.join("")).not.toContain("\x1b_");
expect(session.handle.screen().text).not.toContain("\x1b");
});
it("preserves every projected attribute, color mode, and default-style transition", async () => {
const styled =
"\x1b[1;2;3;4;7;8;9;38;5;123;48;2;1;2;3mX\x1b[0mY\x1b[38;2;4;5;6;48;5;17mZ\x1b[0m";
const session = await terminalFor(
command(`process.stdout.write(${JSON.stringify(styled)})`, {
cols: 20,
rows: 5,
}),
);
await session.exited;
const view = session.handle.view();
expect(view.lines[0]).toBe(
"\x1b[0;1;2;3;4;7;8;9;38;5;123;48;2;1;2;3mX\x1b[0mY\x1b[0;38;2;4;5;6;48;5;17mZ\x1b[0m" +
" ".repeat(17) +
"\x1b[0m",
);
expect(view.lines[1]).toBe("\x1b[0m" + " ".repeat(20) + "\x1b[0m");
expect(session.handle.screen().text).toContain("XYZ");
});
it("observes split and multiparameter cursor modes and soft reset", async () => {
for (const [suffix, visible] of [
["lB", false],
["lB\x1b[?25;2004h", true],
["lB\x1b[!p", true],
] as const) {
const session = await terminalFor(
command(
`process.stdout.write('A\\x1b[?25');setTimeout(()=>process.stdout.write(${JSON.stringify(suffix)}),10)`,
),
);
await session.exited;
expect(Boolean(session.handle.view().cursor)).toBe(visible);
}
});
it("bounds pathological combining cells in human views", async () => {
const session = await terminalFor(
command("process.stdout.write('a'+'\\u0301'.repeat(256))"),
);
await session.exited;
const view = session.handle.view();
expect(view.truncated).toBe(true);
expect(view.cursor).toBeUndefined();
expect(Buffer.byteLength(view.lines.join(""))).toBeLessThan(16384);
});
it("preserves modern Unicode cell positions, absolute addressing, and wrapping", async () => {
for (const sample of [
{ text: "A๐B", line: "A๐B", x: 4, y: 0 },
{ text: "A๐\x1b[1;4HB", line: "A๐B", x: 4, y: 0 },
{ text: `${"x".repeat(18)}๐Z`, line: "Z", x: 1, y: 1 },
{ text: "็e\u0301๐", line: "็e\u0301๐", x: 5, y: 0 },
]) {
const session = await terminalFor(
command(`process.stdout.write(${JSON.stringify(sample.text)})`, {
cols: 20,
rows: 5,
}),
);
await session.exited;
const screen = session.handle.screen();
expect(screen).toMatchObject({ cursorX: sample.x, cursorY: sample.y });
expect(screen.text.split("\n")[sample.y]).toBe(sample.line);
}
});
it.runIf(process.platform !== "win32")(
"never reports signal termination as success",
async () => {
const session = await terminalFor(
command("process.kill(process.pid,'SIGTERM')"),
);
const result = await session.exited;
expect(result.code).toBeNull();
expect(result.error).toContain("signal");
},
);
it("negotiates human application cursor keys without rewriting exact tool input", async () => {
for (const [application, keyboard, expected] of [
[true, true, "1b4f41"],
[true, false, "1b5b41"],
[false, true, "1b5b41"],
] as const) {
const source = `process.stdin.setRawMode(true);let b=Buffer.alloc(0);process.stdin.on('data',d=>{b=Buffer.concat([b,d]);if(b.length>=3){process.stdout.write('KEY_HEX:'+b.toString('hex'));process.exit(0)}});process.stdout.write(${JSON.stringify((application ? "\x1b[?1h" : "") + "KEY_READY")})`;
const session = await terminalFor(command(source));
await vi.waitFor(
() => expect(session.handle.screen().text).toContain("KEY_READY"),
{ timeout: 2000 },
);
session.handle.write("\x1b[A", keyboard);
await session.exited;
expect(session.output.join("")).toContain("KEY_HEX:" + expected);
}
});
it("preserves negotiated bracketed paste without leaking host delimiters", async () => {
for (const enabled of [true, false]) {
const source = `process.stdin.setRawMode(true);let parts=[];process.stdin.on('data',d=>{parts.push(d);const b=Buffer.concat(parts);if(b.includes(Buffer.from(${JSON.stringify(enabled ? "\x1b[201~" : "\n")}))){process.stdout.write('PASTE_HEX:'+b.toString('hex'));process.exit(0)}});process.stdout.write(${JSON.stringify(enabled ? "\x1b[?2004hPASTE_READY" : "PASTE_READY")})`;
const session = await terminalFor(command(source));
await vi.waitFor(
() => expect(session.handle.screen().text).toContain("PASTE_READY"),
{ timeout: 2000 },
);
session.handle.paste("x\x1b\n");
await session.exited;
expect(session.output.join("")).toContain(
enabled ? "PASTE_HEX:1b5b3230307e780a1b5b3230317e" : "PASTE_HEX:780a",
);
}
});
it("preserves immediate final output across repeated process exits", async () => {
for (let iteration = 0; iteration < 12; iteration++) {
const session = await terminalFor(
command("process.stdout.write('FINAL\\nFINAL\\n')"),
);
expect(await session.exited).toEqual({ code: 0, error: undefined });
expect(session.output.join("")).toMatch(/FINAL\r?\nFINAL/);
expect(session.handle.screen().text).toContain("FINAL");
}
});
it("accepts terminal input and resize", async () => {
const session = await terminalFor(
command(
"process.stdin.once('data', data => { process.stdout.write(data); process.exit(0) })",
),
);
session.handle.resize(80, 24);
session.handle.write("typed input\r");
await session.exited;
expect(session.output.join("")).toContain("typed input");
expect(session.handle.screen()).toMatchObject({ cols: 80, rows: 24 });
});
it("handles alternate screen transitions", async () => {
const session = await terminalFor(
command("process.stdout.write('normal\\x1b[?1049halt\\x1b[?1049l')"),
);
await session.exited;
expect(session.handle.screen().text).toContain("normal");
expect(session.handle.screen().text).not.toContain("alt");
});
it("parses split Unicode and reports bounded screen truncation", async () => {
const unicode = await terminalFor(
command(
"const b=Buffer.from('A๐'); process.stdout.write(b.subarray(0,3)); setTimeout(()=>process.stdout.write(b.subarray(3)),10)",
),
);
await unicode.exited;
expect(unicode.handle.screen().text).toContain("A๐");
expect(unicode.handle.screen()).toMatchObject({ cursorX: 3, cursorY: 0 });
const bounded = await terminalFor(
command("process.stdout.write('๐'.repeat(10000))", {
cols: 200,
rows: 60,
}),
);
await bounded.exited;
const screen = bounded.handle.screen();
expect(Buffer.byteLength(screen.text)).toBeLessThanOrEqual(16384);
expect(screen.text).not.toContain("๏ฟฝ");
expect(screen.truncated).toBe(true);
});
it("responds to terminal queries without waiting for user input", async () => {
const session = await terminalFor(
command(
"process.stdin.setRawMode(true); process.stdin.once('data',data=>{process.stdout.write('DSR_OK '+JSON.stringify(data.toString()));process.exit(0)});process.stdout.write('A๐B\\x1b[6n')",
),
);
expect((await session.exited).code).toBe(0);
expect(session.output.join("")).toContain(
`DSR_OK ${JSON.stringify("\x1b[1;5R")}`,
);
});
it("confirms cancellation without platform-specific caller signals", async () => {
const session = await terminalFor(command("setInterval(()=>{},1000)"));
expect(await session.handle.stop()).toBe(true);
await session.exited;
});
it("rejects invalid dimensions before launching", async () => {
await expect(
terminalFor(command("process.exit(0)", { cols: 1 })),
).rejects.toThrow("Terminal cols");
});
it.runIf(process.platform === "win32")(
"runs resolved Win32 executables with exact arguments and live pid",
async () => {
const source =
"process.stdout.write(JSON.stringify(process.argv.slice(1)))";
const args = [
"space value",
'"quoted"',
"trailing\\",
"a&b|c>d%HOME%",
"",
];
for (const executable of ["node", "node.exe", process.execPath]) {
const session = await terminalFor({
kind: "terminal",
command: executable,
args: ["-e", source, ...args],
});
expect((await session.exited).code).toBe(0);
expect(session.output.join("")).toContain(JSON.stringify(args));
}
const fixture = await mkdtemp(join(tmpdir(), "activity-terminal-"));
try {
const executable = join(fixture, "activity-node.exe");
await copyFile(process.execPath, executable);
const relative = await terminalFor(
command("process.stdout.write('RELATIVE')", {
command: ".\\activity-node.exe",
}),
fixture,
);
expect((await relative.exited).code).toBe(0);
expect(relative.output.join("")).toContain("RELATIVE");
} finally {
await rm(fixture, { force: true, recursive: true });
}
const live = await terminalFor(
command(
"process.stdout.write('LIVE_PID:'+process.pid);setTimeout(() => process.exit(0), 500)",
),
);
await vi.waitFor(() =>
expect(live.output.join("")).toMatch(/LIVE_PID:\d+/),
);
expect(live.handle.pid).toBe(
Number(live.output.join("").match(/LIVE_PID:(\d+)/)?.[1]),
);
await live.exited;
},
);
it.runIf(process.platform === "win32")(
"rejects missing Win32 executable and cwd before spawning",
async () => {
await expect(
terminalFor({
kind: "terminal",
command: "activity-does-not-exist",
}),
).rejects.toThrow("executable was not found");
await expect(
terminalFor(command("process.exit(0)"), "C:\\activity-no-cwd"),
).rejects.toThrow("cwd does not exist");
},
);
});