@wayofmono/wo-tui 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,395 @@
1
+ import * as fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import * as path from "node:path";
4
+ import { setKittyProtocolActive } from "./keys.js";
5
+ import { StdinBuffer } from "./stdin-buffer.js";
6
+
7
+ const cjsRequire = createRequire(import.meta.url);
8
+
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
+
13
+ /**
14
+ * Minimal terminal interface for TUI
15
+ */
16
+ export interface Terminal {
17
+ // Start the terminal with input and resize handlers
18
+ start(onInput: (data: string) => void, onResize: () => void): void;
19
+
20
+ // Stop the terminal and restore state
21
+ stop(): void;
22
+
23
+ /**
24
+ * Drain stdin before exiting to prevent Kitty key release events from
25
+ * leaking to the parent shell over slow SSH connections.
26
+ * @param maxMs - Maximum time to drain (default: 1000ms)
27
+ * @param idleMs - Exit early if no input arrives within this time (default: 50ms)
28
+ */
29
+ drainInput(maxMs?: number, idleMs?: number): Promise<void>;
30
+
31
+ // Write output to terminal
32
+ write(data: string): void;
33
+
34
+ // Get terminal dimensions
35
+ get columns(): number;
36
+ get rows(): number;
37
+
38
+ // Whether Kitty keyboard protocol is active
39
+ get kittyProtocolActive(): boolean;
40
+
41
+ // Cursor positioning (relative to current position)
42
+ moveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines
43
+
44
+ // Cursor visibility
45
+ hideCursor(): void; // Hide the cursor
46
+ showCursor(): void; // Show the cursor
47
+
48
+ // Clear operations
49
+ clearLine(): void; // Clear current line
50
+ clearFromCursor(): void; // Clear from cursor to end of screen
51
+ clearScreen(): void; // Clear entire screen and move cursor to (0,0)
52
+
53
+ // Title operations
54
+ setTitle(title: string): void; // Set terminal window title
55
+
56
+ // Progress indicator (OSC 9;4)
57
+ setProgress(active: boolean): void;
58
+ }
59
+
60
+ /**
61
+ * Real terminal using process.stdin/stdout
62
+ */
63
+ export class ProcessTerminal implements Terminal {
64
+ private wasRaw = false;
65
+ private inputHandler?: (data: string) => void;
66
+ private resizeHandler?: () => void;
67
+ private _kittyProtocolActive = false;
68
+ private _modifyOtherKeysActive = false;
69
+ private stdinBuffer?: StdinBuffer;
70
+ private stdinDataHandler?: (data: string) => void;
71
+ private progressInterval?: ReturnType<typeof setInterval>;
72
+ private writeLogPath = (() => {
73
+ const env = process.env.PI_TUI_WRITE_LOG || "";
74
+ if (!env) return "";
75
+ try {
76
+ if (fs.statSync(env).isDirectory()) {
77
+ const now = new Date();
78
+ 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")}`;
79
+ return path.join(env, `tui-${ts}-${process.pid}.log`);
80
+ }
81
+ } catch {
82
+ // Not an existing directory - use as-is (file path)
83
+ }
84
+ return env;
85
+ })();
86
+
87
+ get kittyProtocolActive(): boolean {
88
+ return this._kittyProtocolActive;
89
+ }
90
+
91
+ start(onInput: (data: string) => void, onResize: () => void): void {
92
+ this.inputHandler = onInput;
93
+ this.resizeHandler = onResize;
94
+
95
+ // Save previous state and enable raw mode
96
+ this.wasRaw = process.stdin.isRaw || false;
97
+ if (process.stdin.setRawMode) {
98
+ process.stdin.setRawMode(true);
99
+ }
100
+ process.stdin.setEncoding("utf8");
101
+ process.stdin.resume();
102
+
103
+ // Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
104
+ process.stdout.write("\x1b[?2004h");
105
+
106
+ // Set up resize handler immediately
107
+ process.stdout.on("resize", this.resizeHandler);
108
+
109
+ // Refresh terminal dimensions - they may be stale after suspend/resume
110
+ // (SIGWINCH is lost while process is stopped). Unix only.
111
+ if (process.platform !== "win32") {
112
+ process.kill(process.pid, "SIGWINCH");
113
+ }
114
+
115
+ // On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
116
+ // VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
117
+ // events that lose modifier information. Must run AFTER setRawMode(true)
118
+ // since that resets console mode flags.
119
+ this.enableWindowsVTInput();
120
+
121
+ // Query and enable Kitty keyboard protocol
122
+ // The query handler intercepts input temporarily, then installs the user's handler
123
+ // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
124
+ this.queryAndEnableKittyProtocol();
125
+ }
126
+
127
+ /**
128
+ * Set up StdinBuffer to split batched input into individual sequences.
129
+ * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
130
+ *
131
+ * Also watches for Kitty protocol response and enables it when detected.
132
+ * This is done here (after stdinBuffer parsing) rather than on raw stdin
133
+ * to handle the case where the response arrives split across multiple events.
134
+ */
135
+ private setupStdinBuffer(): void {
136
+ this.stdinBuffer = new StdinBuffer({ timeout: 10 });
137
+
138
+ // Kitty protocol response pattern: \x1b[?<flags>u
139
+ const kittyResponsePattern = /^\x1b\[\?(\d+)u$/;
140
+
141
+ // Forward individual sequences to the input handler
142
+ this.stdinBuffer.on("data", (sequence) => {
143
+ // Check for Kitty protocol response (only if not already enabled)
144
+ if (!this._kittyProtocolActive) {
145
+ const match = sequence.match(kittyResponsePattern);
146
+ if (match) {
147
+ this._kittyProtocolActive = true;
148
+ setKittyProtocolActive(true);
149
+
150
+ // Enable Kitty keyboard protocol (push flags)
151
+ // Flag 1 = disambiguate escape codes
152
+ // Flag 2 = report event types (press/repeat/release)
153
+ // Flag 4 = report alternate keys (shifted key, base layout key)
154
+ // Base layout key enables shortcuts to work with non-Latin keyboard layouts
155
+ process.stdout.write("\x1b[>7u");
156
+ return; // Don't forward protocol response to TUI
157
+ }
158
+ }
159
+
160
+ if (this.inputHandler) {
161
+ this.inputHandler(sequence);
162
+ }
163
+ });
164
+
165
+ // Re-wrap paste content with bracketed paste markers for existing editor handling
166
+ this.stdinBuffer.on("paste", (content) => {
167
+ if (this.inputHandler) {
168
+ this.inputHandler(`\x1b[200~${content}\x1b[201~`);
169
+ }
170
+ });
171
+
172
+ // Handler that pipes stdin data through the buffer
173
+ this.stdinDataHandler = (data: string) => {
174
+ this.stdinBuffer!.process(data);
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Query terminal for Kitty keyboard protocol support and enable if available.
180
+ *
181
+ * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,
182
+ * it supports the protocol and we enable it with CSI > 1 u.
183
+ *
184
+ * If no Kitty response arrives shortly after startup, fall back to enabling
185
+ * xterm modifyOtherKeys mode 2. This is needed for tmux, which can forward
186
+ * modified enter keys as CSI-u when extended-keys is enabled, but may not
187
+ * answer the Kitty protocol query.
188
+ *
189
+ * The response is detected in setupStdinBuffer's data handler, which properly
190
+ * handles the case where the response arrives split across multiple stdin events.
191
+ */
192
+ private queryAndEnableKittyProtocol(): void {
193
+ this.setupStdinBuffer();
194
+ process.stdin.on("data", this.stdinDataHandler!);
195
+ process.stdout.write("\x1b[?u");
196
+ setTimeout(() => {
197
+ if (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {
198
+ process.stdout.write("\x1b[>4;2m");
199
+ this._modifyOtherKeysActive = true;
200
+ }
201
+ }, 150);
202
+ }
203
+
204
+ /**
205
+ * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
206
+ * console handle so the terminal sends VT sequences for modified keys
207
+ * (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
208
+ * discards modifier state and Shift+Tab arrives as plain \t.
209
+ */
210
+ private enableWindowsVTInput(): void {
211
+ if (process.platform !== "win32") return;
212
+ try {
213
+ // Dynamic require to avoid bundling koffi's 74MB of cross-platform
214
+ // native binaries into every compiled binary. Koffi is only needed
215
+ // on Windows for VT input support.
216
+ const koffi = cjsRequire("koffi");
217
+ const k32 = koffi.load("kernel32.dll");
218
+ const GetStdHandle = k32.func("void* __stdcall GetStdHandle(int)");
219
+ const GetConsoleMode = k32.func("bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)");
220
+ const SetConsoleMode = k32.func("bool __stdcall SetConsoleMode(void*, uint32_t)");
221
+
222
+ const STD_INPUT_HANDLE = -10;
223
+ const ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;
224
+ const handle = GetStdHandle(STD_INPUT_HANDLE);
225
+ const mode = new Uint32Array(1);
226
+ GetConsoleMode(handle, mode);
227
+ SetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);
228
+ } catch {
229
+ // koffi not available — Shift+Tab won't be distinguishable from Tab
230
+ }
231
+ }
232
+
233
+ async drainInput(maxMs = 1000, idleMs = 50): Promise<void> {
234
+ if (this._kittyProtocolActive) {
235
+ // Disable Kitty keyboard protocol first so any late key releases
236
+ // do not generate new Kitty escape sequences.
237
+ process.stdout.write("\x1b[<u");
238
+ this._kittyProtocolActive = false;
239
+ setKittyProtocolActive(false);
240
+ }
241
+ if (this._modifyOtherKeysActive) {
242
+ process.stdout.write("\x1b[>4;0m");
243
+ this._modifyOtherKeysActive = false;
244
+ }
245
+
246
+ const previousHandler = this.inputHandler;
247
+ this.inputHandler = undefined;
248
+
249
+ let lastDataTime = Date.now();
250
+ const onData = () => {
251
+ lastDataTime = Date.now();
252
+ };
253
+
254
+ process.stdin.on("data", onData);
255
+ const endTime = Date.now() + maxMs;
256
+
257
+ try {
258
+ while (true) {
259
+ const now = Date.now();
260
+ const timeLeft = endTime - now;
261
+ if (timeLeft <= 0) break;
262
+ if (now - lastDataTime >= idleMs) break;
263
+ await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
264
+ }
265
+ } finally {
266
+ process.stdin.removeListener("data", onData);
267
+ this.inputHandler = previousHandler;
268
+ }
269
+ }
270
+
271
+ stop(): void {
272
+ if (this.clearProgressInterval()) {
273
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
274
+ }
275
+
276
+ // Disable bracketed paste mode
277
+ process.stdout.write("\x1b[?2004l");
278
+
279
+ // Disable Kitty keyboard protocol if not already done by drainInput()
280
+ if (this._kittyProtocolActive) {
281
+ process.stdout.write("\x1b[<u");
282
+ this._kittyProtocolActive = false;
283
+ setKittyProtocolActive(false);
284
+ }
285
+ if (this._modifyOtherKeysActive) {
286
+ process.stdout.write("\x1b[>4;0m");
287
+ this._modifyOtherKeysActive = false;
288
+ }
289
+
290
+ // Clean up StdinBuffer
291
+ if (this.stdinBuffer) {
292
+ this.stdinBuffer.destroy();
293
+ this.stdinBuffer = undefined;
294
+ }
295
+
296
+ // Remove event handlers
297
+ if (this.stdinDataHandler) {
298
+ process.stdin.removeListener("data", this.stdinDataHandler);
299
+ this.stdinDataHandler = undefined;
300
+ }
301
+ this.inputHandler = undefined;
302
+ if (this.resizeHandler) {
303
+ process.stdout.removeListener("resize", this.resizeHandler);
304
+ this.resizeHandler = undefined;
305
+ }
306
+
307
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
308
+ // re-interpreted after raw mode is disabled. This fixes a race condition
309
+ // where Ctrl+D could close the parent shell over SSH.
310
+ process.stdin.pause();
311
+
312
+ // Restore raw mode state
313
+ if (process.stdin.setRawMode) {
314
+ process.stdin.setRawMode(this.wasRaw);
315
+ }
316
+ }
317
+
318
+ write(data: string): void {
319
+ process.stdout.write(data);
320
+ if (this.writeLogPath) {
321
+ try {
322
+ fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
323
+ } catch {
324
+ // Ignore logging errors
325
+ }
326
+ }
327
+ }
328
+
329
+ get columns(): number {
330
+ return process.stdout.columns || Number(process.env.COLUMNS) || 80;
331
+ }
332
+
333
+ get rows(): number {
334
+ return process.stdout.rows || Number(process.env.LINES) || 24;
335
+ }
336
+
337
+ moveBy(lines: number): void {
338
+ if (lines > 0) {
339
+ // Move down
340
+ process.stdout.write(`\x1b[${lines}B`);
341
+ } else if (lines < 0) {
342
+ // Move up
343
+ process.stdout.write(`\x1b[${-lines}A`);
344
+ }
345
+ // lines === 0: no movement
346
+ }
347
+
348
+ hideCursor(): void {
349
+ process.stdout.write("\x1b[?25l");
350
+ }
351
+
352
+ showCursor(): void {
353
+ process.stdout.write("\x1b[?25h");
354
+ }
355
+
356
+ clearLine(): void {
357
+ process.stdout.write("\x1b[K");
358
+ }
359
+
360
+ clearFromCursor(): void {
361
+ process.stdout.write("\x1b[J");
362
+ }
363
+
364
+ clearScreen(): void {
365
+ process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
366
+ }
367
+
368
+ setTitle(title: string): void {
369
+ // OSC 0;title BEL - set terminal window title
370
+ process.stdout.write(`\x1b]0;${title}\x07`);
371
+ }
372
+
373
+ setProgress(active: boolean): void {
374
+ if (active) {
375
+ // OSC 9;4;3 - indeterminate progress
376
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
377
+ if (!this.progressInterval) {
378
+ this.progressInterval = setInterval(() => {
379
+ process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE);
380
+ }, TERMINAL_PROGRESS_KEEPALIVE_MS);
381
+ }
382
+ } else {
383
+ this.clearProgressInterval();
384
+ // OSC 9;4;0 - clear progress
385
+ process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
386
+ }
387
+ }
388
+
389
+ private clearProgressInterval(): boolean {
390
+ if (!this.progressInterval) return false;
391
+ clearInterval(this.progressInterval);
392
+ this.progressInterval = undefined;
393
+ return true;
394
+ }
395
+ }