terminal.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import * as fs from "node:fs";
  2. import { createRequire } from "node:module";
  3. import * as path from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { setKittyProtocolActive } from "./keys.ts";
  6. import { isNativeModifierPressed } from "./native-modifiers.ts";
  7. import { StdinBuffer } from "./stdin-buffer.ts";
  8. const cjsRequire = createRequire(import.meta.url);
  9. const TERMINAL_PROGRESS_KEEPALIVE_MS = 1000;
  10. const TERMINAL_PROGRESS_ACTIVE_SEQUENCE = "\x1b]9;4;3\x07";
  11. const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0;\x07";
  12. const APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE = "\x1b[13;2u";
  13. const DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
  14. const KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS = 150;
  15. const KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1b[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1b[?u\x1b[c`;
  16. export type KeyboardProtocolNegotiationSequence =
  17. | { type: "kitty-flags"; flags: number }
  18. | { type: "device-attributes" };
  19. export function parseKeyboardProtocolNegotiationSequence(
  20. sequence: string,
  21. ): KeyboardProtocolNegotiationSequence | undefined {
  22. const kittyFlags = sequence.match(/^\x1b\[\?(\d+)u$/);
  23. if (kittyFlags) {
  24. return { type: "kitty-flags", flags: Number.parseInt(kittyFlags[1]!, 10) };
  25. }
  26. if (/^\x1b\[\?[\d;]*c$/.test(sequence)) {
  27. return { type: "device-attributes" };
  28. }
  29. return undefined;
  30. }
  31. function isKeyboardProtocolNegotiationSequencePrefix(sequence: string): boolean {
  32. return sequence === "\x1b[" || /^\x1b\[\?[\d;]*$/.test(sequence);
  33. }
  34. export function isAppleTerminalSession(): boolean {
  35. return process.platform === "darwin" && process.env.TERM_PROGRAM === "Apple_Terminal";
  36. }
  37. export function normalizeAppleTerminalInput(data: string, isAppleTerminal: boolean, isShiftPressed: boolean): string {
  38. if (isAppleTerminal && data === "\r" && isShiftPressed) return APPLE_TERMINAL_SHIFT_ENTER_SEQUENCE;
  39. return data;
  40. }
  41. /**
  42. * Minimal terminal interface for TUI
  43. */
  44. export interface Terminal {
  45. // Start the terminal with input and resize handlers
  46. start(onInput: (data: string) => void, onResize: () => void): void;
  47. // Stop the terminal and restore state
  48. stop(): void;
  49. /**
  50. * Drain stdin before exiting to prevent Kitty key release events from
  51. * leaking to the parent shell over slow SSH connections.
  52. * @param maxMs - Maximum time to drain (default: 1000ms)
  53. * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
  54. */
  55. drainInput(maxMs?: number, idleMs?: number): Promise<void>;
  56. // Write output to terminal
  57. write(data: string): void;
  58. // Get terminal dimensions
  59. get columns(): number;
  60. get rows(): number;
  61. // Whether Kitty keyboard protocol is active
  62. get kittyProtocolActive(): boolean;
  63. // Cursor positioning (relative to current position)
  64. moveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines
  65. // Cursor visibility
  66. hideCursor(): void; // Hide the cursor
  67. showCursor(): void; // Show the cursor
  68. // Clear operations
  69. clearLine(): void; // Clear current line
  70. clearFromCursor(): void; // Clear from cursor to end of screen
  71. clearScreen(): void; // Clear entire screen and move cursor to (0,0)
  72. // Title operations
  73. setTitle(title: string): void; // Set terminal window title
  74. // Progress indicator (OSC 9;4)
  75. setProgress(active: boolean): void;
  76. }
  77. /**
  78. * Real terminal using process.stdin/stdout
  79. */
  80. export class ProcessTerminal implements Terminal {
  81. private wasRaw = false;
  82. private inputHandler?: (data: string) => void;
  83. private resizeHandler?: () => void;
  84. private _kittyProtocolActive = false;
  85. private _modifyOtherKeysActive = false;
  86. private keyboardProtocolPushed = false;
  87. private keyboardProtocolNegotiationBuffer = "";
  88. private keyboardProtocolBufferFlushTimer?: ReturnType<typeof setTimeout>;
  89. private stdinBuffer?: StdinBuffer;
  90. private stdinDataHandler?: (data: string) => void;
  91. private progressInterval?: ReturnType<typeof setInterval>;
  92. private writeLogPath = (() => {
  93. const env = process.env.PI_TUI_WRITE_LOG || "";
  94. if (!env) return "";
  95. try {
  96. if (fs.statSync(env).isDirectory()) {
  97. const now = new Date();
  98. const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String(now.getSeconds()).padStart(2, "0")}`;
  99. return path.join(env, `tui-${ts}-${process.pid}.log`);
  100. }
  101. } catch {
  102. // Not an existing directory - use as-is (file path)
  103. }
  104. return env;
  105. })();
  106. get kittyProtocolActive(): boolean {
  107. return this._kittyProtocolActive;
  108. }
  109. get modifyOtherKeysActive(): boolean {
  110. return this._modifyOtherKeysActive;
  111. }
  112. start(onInput: (data: string) => void, onResize: () => void): void {
  113. this.inputHandler = onInput;
  114. this.resizeHandler = onResize;
  115. // Save previous state and enable raw mode
  116. this.wasRaw = process.stdin.isRaw || false;
  117. if (process.stdin.setRawMode) {
  118. process.stdin.setRawMode(true);
  119. }
  120. process.stdin.setEncoding("utf8");
  121. process.stdin.resume();
  122. // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
  123. process.stdout.write("\x1b[?2004h");
  124. // Set up resize handler immediately
  125. process.stdout.on("resize", this.resizeHandler);
  126. // Refresh terminal dimensions - they may be stale after suspend/resume
  127. // (SIGWINCH is lost while process is stopped). Unix only.
  128. if (process.platform !== "win32") {
  129. process.kill(process.pid, "SIGWINCH");
  130. }
  131. // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
  132. // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
  133. // events that lose modifier information. Must run AFTER setRawMode(true)
  134. // since that resets console mode flags.
  135. this.enableWindowsVTInput();
  136. // Query Kitty keyboard protocol and fall back to modifyOtherKeys when DA confirms no Kitty response.
  137. // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
  138. this.queryAndEnableKittyProtocol();
  139. }
  140. /**
  141. * Set up StdinBuffer to split batched input into individual sequences.
  142. * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
  143. *
  144. * Also watches for Kitty protocol response and enables it when detected.
  145. * This is done here (after stdinBuffer parsing) rather than on raw stdin
  146. * to handle the case where the response arrives split across multiple events.
  147. */
  148. private setupStdinBuffer(): void {
  149. this.stdinBuffer = new StdinBuffer({ timeout: 10 });
  150. // Forward individual sequences to the input handler
  151. this.stdinBuffer.on("data", (sequence) => {
  152. const negotiationSequence = this.readKeyboardProtocolNegotiationSequence(sequence);
  153. if (negotiationSequence === "pending") {
  154. this.scheduleKeyboardProtocolNegotiationBufferFlush();
  155. return; // Wait briefly for the rest of a split Kitty response.
  156. }
  157. if (this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)) {
  158. return;
  159. }
  160. this.forwardInputSequence(sequence);
  161. });
  162. // Re-wrap paste content with bracketed paste markers for existing editor handling
  163. this.stdinBuffer.on("paste", (content) => {
  164. if (this.inputHandler) {
  165. this.inputHandler(`\x1b[200~${content}\x1b[201~`);
  166. }
  167. });
  168. // Handler that pipes stdin data through the buffer
  169. this.stdinDataHandler = (data: string) => {
  170. this.stdinBuffer!.process(data);
  171. };
  172. }
  173. /**
  174. * Query terminal for Kitty keyboard protocol support and enable it if available.
  175. *
  176. * Kitty's progressive enhancement detection requires requesting the desired
  177. * flags before querying them. The trailing DA query is a sentinel supported by
  178. * terminals that do not know Kitty keyboard protocol; receiving DA before a
  179. * Kitty response enables modifyOtherKeys fallback without a startup timeout.
  180. *
  181. * The requested flags are:
  182. * - 1 = disambiguate escape codes
  183. * - 2 = report event types (press/repeat/release)
  184. * - 4 = report alternate keys (shifted key, base layout key)
  185. */
  186. private queryAndEnableKittyProtocol(): void {
  187. this.setupStdinBuffer();
  188. process.stdin.on("data", this.stdinDataHandler!);
  189. this.keyboardProtocolPushed = true;
  190. this.clearKeyboardProtocolNegotiationBuffer();
  191. process.stdout.write(KITTY_KEYBOARD_PROTOCOL_QUERY);
  192. }
  193. private handleKeyboardProtocolNegotiationSequence(
  194. negotiationSequence: KeyboardProtocolNegotiationSequence | undefined,
  195. ): boolean {
  196. if (!negotiationSequence) return false;
  197. this.clearKeyboardProtocolNegotiationBuffer();
  198. if (negotiationSequence.type === "kitty-flags") {
  199. if (negotiationSequence.flags !== 0) {
  200. this.disableModifyOtherKeys();
  201. if (!this._kittyProtocolActive) {
  202. this._kittyProtocolActive = true;
  203. setKittyProtocolActive(true);
  204. }
  205. } else {
  206. this.enableModifyOtherKeys();
  207. }
  208. return true;
  209. }
  210. if (!this._kittyProtocolActive) {
  211. this.enableModifyOtherKeys();
  212. }
  213. return true;
  214. }
  215. private readKeyboardProtocolNegotiationSequence(
  216. sequence: string,
  217. ): KeyboardProtocolNegotiationSequence | "pending" | undefined {
  218. if (this.keyboardProtocolNegotiationBuffer) {
  219. const bufferedSequence = this.keyboardProtocolNegotiationBuffer + sequence;
  220. const negotiationSequence = parseKeyboardProtocolNegotiationSequence(bufferedSequence);
  221. if (negotiationSequence) {
  222. this.clearKeyboardProtocolNegotiationBuffer();
  223. return negotiationSequence;
  224. }
  225. if (isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence)) {
  226. this.setKeyboardProtocolNegotiationBuffer(bufferedSequence);
  227. return "pending";
  228. }
  229. this.flushKeyboardProtocolNegotiationBufferAsInput();
  230. }
  231. const negotiationSequence = parseKeyboardProtocolNegotiationSequence(sequence);
  232. if (negotiationSequence) return negotiationSequence;
  233. if (isKeyboardProtocolNegotiationSequencePrefix(sequence)) {
  234. this.setKeyboardProtocolNegotiationBuffer(sequence);
  235. return "pending";
  236. }
  237. return undefined;
  238. }
  239. private setKeyboardProtocolNegotiationBuffer(sequence: string): void {
  240. this.clearKeyboardProtocolNegotiationBufferFlushTimer();
  241. this.keyboardProtocolNegotiationBuffer = sequence;
  242. }
  243. private clearKeyboardProtocolNegotiationBuffer(): void {
  244. this.clearKeyboardProtocolNegotiationBufferFlushTimer();
  245. this.keyboardProtocolNegotiationBuffer = "";
  246. }
  247. private flushKeyboardProtocolNegotiationBufferAsInput(): void {
  248. if (!this.keyboardProtocolNegotiationBuffer) return;
  249. const sequence = this.keyboardProtocolNegotiationBuffer;
  250. this.clearKeyboardProtocolNegotiationBuffer();
  251. this.forwardInputSequence(sequence);
  252. }
  253. private scheduleKeyboardProtocolNegotiationBufferFlush(): void {
  254. if (!this.keyboardProtocolNegotiationBuffer || this.keyboardProtocolBufferFlushTimer) return;
  255. this.keyboardProtocolBufferFlushTimer = setTimeout(() => {
  256. this.keyboardProtocolBufferFlushTimer = undefined;
  257. this.flushKeyboardProtocolNegotiationBufferAsInput();
  258. }, KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS);
  259. }
  260. private clearKeyboardProtocolNegotiationBufferFlushTimer(): void {
  261. if (!this.keyboardProtocolBufferFlushTimer) return;
  262. clearTimeout(this.keyboardProtocolBufferFlushTimer);
  263. this.keyboardProtocolBufferFlushTimer = undefined;
  264. }
  265. private forwardInputSequence(sequence: string): void {
  266. if (!this.inputHandler) return;
  267. const isAppleTerminal = sequence === "\r" && isAppleTerminalSession();
  268. const input = normalizeAppleTerminalInput(
  269. sequence,
  270. isAppleTerminal,
  271. isAppleTerminal && isNativeModifierPressed("shift"),
  272. );
  273. this.inputHandler(input);
  274. }
  275. private enableModifyOtherKeys(): void {
  276. if (this._kittyProtocolActive || this._modifyOtherKeysActive) return;
  277. process.stdout.write("\x1b[>4;2m");
  278. this._modifyOtherKeysActive = true;
  279. }
  280. private disableModifyOtherKeys(): void {
  281. if (!this._modifyOtherKeysActive) return;
  282. process.stdout.write("\x1b[>4;0m");
  283. this._modifyOtherKeysActive = false;
  284. }
  285. /**
  286. * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
  287. * console handle so the terminal sends VT sequences for modified keys
  288. * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
  289. * discards modifier state and Shift+Tab arrives as plain \t.
  290. */
  291. private enableWindowsVTInput(): void {
  292. if (process.platform !== "win32") return;
  293. try {
  294. const arch = process.arch;
  295. if (arch !== "x64" && arch !== "arm64") return;
  296. // Dynamic require so non-Windows and bundled/browser paths never load the
  297. // native helper. In the npm package native/ is next to dist/; in compiled
  298. // binary archives native/ is copied next to the executable.
  299. const moduleDir = path.dirname(fileURLToPath(import.meta.url));
  300. const nativePath = path.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
  301. const candidates = [
  302. path.join(moduleDir, "..", nativePath),
  303. path.join(moduleDir, nativePath),
  304. path.join(path.dirname(process.execPath), nativePath),
  305. ];
  306. for (const modulePath of candidates) {
  307. try {
  308. const helper = cjsRequire(modulePath) as { enableVirtualTerminalInput?: () => boolean };
  309. helper.enableVirtualTerminalInput?.();
  310. return;
  311. } catch {
  312. // Try the next possible packaging location.
  313. }
  314. }
  315. } catch {
  316. // Native helper not available — Shift+Tab won't be distinguishable from Tab.
  317. }
  318. }
  319. async drainInput(maxMs = 1000, idleMs = 50): Promise<void> {
  320. const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
  321. this.clearKeyboardProtocolNegotiationBuffer();
  322. if (shouldDisableKittyProtocol) {
  323. // Disable Kitty keyboard protocol first so any late key releases
  324. // do not generate new Kitty escape sequences.
  325. process.stdout.write("\x1b[<u");
  326. this.keyboardProtocolPushed = false;
  327. this._kittyProtocolActive = false;
  328. setKittyProtocolActive(false);
  329. }
  330. this.disableModifyOtherKeys();
  331. const previousHandler = this.inputHandler;
  332. this.inputHandler = undefined;
  333. let lastDataTime = Date.now();
  334. const onData = () => {
  335. lastDataTime = Date.now();
  336. };
  337. process.stdin.on("data", onData);
  338. const endTime = Date.now() + maxMs;
  339. try {
  340. while (true) {
  341. const now = Date.now();
  342. const timeLeft = endTime - now;
  343. if (timeLeft <= 0) break;
  344. if (now - lastDataTime >= idleMs) break;
  345. await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
  346. }
  347. } finally {
  348. process.stdin.removeListener("data", onData);
  349. this.inputHandler = previousHandler;
  350. }
  351. }
  352. stop(): void {
  353. if (this.clearProgressInterval()) {
  354. process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
  355. }
  356. // Disable bracketed paste mode
  357. process.stdout.write("\x1b[?2004l");
  358. const shouldDisableKittyProtocol = this.keyboardProtocolPushed || this._kittyProtocolActive;
  359. this.clearKeyboardProtocolNegotiationBuffer();
  360. // Disable Kitty keyboard protocol if not already done by drainInput()
  361. if (shouldDisableKittyProtocol) {
  362. process.stdout.write("\x1b[<u");
  363. this.keyboardProtocolPushed = false;
  364. this._kittyProtocolActive = false;
  365. setKittyProtocolActive(false);
  366. }
  367. this.disableModifyOtherKeys();
  368. // Clean up StdinBuffer
  369. if (this.stdinBuffer) {
  370. this.stdinBuffer.destroy();
  371. this.stdinBuffer = undefined;
  372. }
  373. // Remove event handlers
  374. if (this.stdinDataHandler) {
  375. process.stdin.removeListener("data", this.stdinDataHandler);
  376. this.stdinDataHandler = undefined;
  377. }
  378. this.inputHandler = undefined;
  379. if (this.resizeHandler) {
  380. process.stdout.removeListener("resize", this.resizeHandler);
  381. this.resizeHandler = undefined;
  382. }
  383. // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
  384. // re-interpreted after raw mode is disabled. This fixes a race condition
  385. // where Ctrl+D could close the parent shell over SSH.
  386. process.stdin.pause();
  387. // Restore raw mode state
  388. if (process.stdin.setRawMode) {
  389. process.stdin.setRawMode(this.wasRaw);
  390. }
  391. }
  392. write(data: string): void {
  393. process.stdout.write(data);
  394. if (this.writeLogPath) {
  395. try {
  396. fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
  397. } catch {
  398. // Ignore logging errors
  399. }
  400. }
  401. }
  402. get columns(): number {
  403. return process.stdout.columns || Number(process.env.COLUMNS) || 80;
  404. }
  405. get rows(): number {
  406. return process.stdout.rows || Number(process.env.LINES) || 24;
  407. }
  408. moveBy(lines: number): void {
  409. if (lines > 0) {
  410. // Move down
  411. process.stdout.write(`\x1b[${lines}B`);
  412. } else if (lines < 0) {
  413. // Move up
  414. process.stdout.write(`\x1b[${-lines}A`);
  415. }
  416. // lines === 0: no movement
  417. }
  418. hideCursor(): void {
  419. process.stdout.write("\x1b[?25l");
  420. }
  421. showCursor(): void {
  422. process.stdout.write("\x1b[?25h");
  423. }
  424. clearLine(): void {
  425. process.stdout.write("\x1b[K");
  426. }
  427. clearFromCursor(): void {
  428. process.stdout.write("\x1b[J");
  429. }
  430. clearScreen(): void {
  431. process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
  432. }
  433. setTitle(title: string): void {
  434. // OSC 0;title BEL - set terminal window title
  435. process.stdout.write(`\x1b]0;${title}\x07`);
  436. }
  437. setProgress(active: boolean): void {
  438. if (active) {
  439. // OSC 9;4;3 - indeterminate progress
  440. process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
  441. if (!this.progressInterval) {
  442. this.progressInterval = setInterval(() => {
  443. process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
  444. }, TERMINAL_PROGRESS_KEEPALIVE_MS);
  445. }
  446. } else {
  447. this.clearProgressInterval();
  448. // OSC 9;4;0 - clear progress
  449. process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
  450. }
  451. }
  452. private clearProgressInterval(): boolean {
  453. if (!this.progressInterval) return false;
  454. clearInterval(this.progressInterval);
  455. this.progressInterval = undefined;
  456. return true;
  457. }
  458. }