| 1 | import { Key } from "ink"; |
| 2 | |
| 3 | export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content |
| 4 | export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection |
| 5 | export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image |
| 6 | export const MAX_IMAGE_COUNT = 20; // Maximum number of images |
| 7 | export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory |
| 8 | |
| 9 | export class TextBuffer { |
| 10 | private _text: string = ""; |
| 11 | private _cursor: number = 0; |
| 12 | private _pasteBuffer: string = ""; |
| 13 | private _inPasteMode: boolean = false; |
| 14 | private _rapidInputBuffer: string = ""; |
| 15 | private _rapidInputStartPos: number = 0; |
| 16 | private _lastInputTime: number = 0; |
| 17 | private _rapidInputTimer: NodeJS.Timeout | null = null; |
| 18 | private _onStateChange?: () => void; |
| 19 | private _pasteMap = new Map<string, string>(); // placeholder -> original content |
| 20 | private _pasteCounter: number = 0; |
| 21 | private _imageMap = new Map<string, Buffer>(); // placeholder -> image buffer |
| 22 | private _imageCounter: number = 0; |
| 23 | |
| 24 | constructor(initialText: string = "") { |
| 25 | this._text = initialText; |
| 26 | this._cursor = initialText.length; |
| 27 | } |
| 28 | |
| 29 | get text(): string { |
| 30 | return this._text; |
| 31 | } |
| 32 | |
| 33 | get cursor(): number { |
| 34 | return this._cursor; |
| 35 | } |
| 36 | |
| 37 | setText(text: string): void { |
| 38 | this._text = text; |
| 39 | this._cursor = Math.min(this._cursor, text.length); |
| 40 | } |
| 41 | |
| 42 | setCursor(position: number): void { |
| 43 | this._cursor = Math.max(0, Math.min(position, this._text.length)); |
| 44 | } |
| 45 | |
| 46 | insertText(text: string): void { |
| 47 | // Normalize line endings to prevent terminal display issues |
| 48 | const normalizedText = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); |
| 49 | this._text = |
| 50 | this._text.slice(0, this._cursor) + |
| 51 | normalizedText + |
| 52 | this._text.slice(this._cursor); |
| 53 | this._cursor += normalizedText.length; |
| 54 | } |
| 55 | |
| 56 | deleteCharAt(position: number): void { |
| 57 | if (position >= 0 && position < this._text.length) { |
| 58 | this._text = |
| 59 | this._text.slice(0, position) + this._text.slice(position + 1); |
| 60 | if (this._cursor > position) { |
| 61 | this._cursor--; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | deleteBackward(): void { |
| 67 | if (this._cursor > 0) { |
| 68 | this.deleteCharAt(this._cursor - 1); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | deleteForward(): void { |
| 73 | if (this._cursor < this._text.length) { |
| 74 | this.deleteCharAt(this._cursor); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | private findWordBoundary( |
| 79 | position: number, |
| 80 | direction: "left" | "right", |
| 81 | ): number { |
| 82 | if (direction === "left") { |
| 83 | // Find start of current word or previous word |
| 84 | let pos = Math.max(0, position - 1); |
| 85 | |
| 86 | // Skip whitespace |
| 87 | while (pos > 0 && /\s/.test(this._text[pos])) { |
| 88 | pos--; |
| 89 | } |
| 90 | |
| 91 | // Find word boundary |
| 92 | while (pos > 0 && !/\s/.test(this._text[pos - 1])) { |
| 93 | pos--; |
| 94 | } |
| 95 | |
| 96 | return pos; |
| 97 | } else { |
| 98 | // Find end of current word or next word |
| 99 | let pos = position; |
| 100 | |
| 101 | // Skip whitespace |
| 102 | while (pos < this._text.length && /\s/.test(this._text[pos])) { |
| 103 | pos++; |
| 104 | } |
| 105 | |
| 106 | // Find word boundary |
| 107 | while (pos < this._text.length && !/\s/.test(this._text[pos])) { |
| 108 | pos++; |
| 109 | } |
| 110 | |
| 111 | return pos; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | moveWordLeft(): void { |
| 116 | this._cursor = this.findWordBoundary(this._cursor, "left"); |
| 117 | } |
| 118 | |
| 119 | moveWordRight(): void { |
| 120 | this._cursor = this.findWordBoundary(this._cursor, "right"); |
| 121 | } |
| 122 | |
| 123 | deleteWordBackward(): void { |
| 124 | const wordStart = this.findWordBoundary(this._cursor, "left"); |
| 125 | if (wordStart < this._cursor) { |
| 126 | this._text = |
| 127 | this._text.slice(0, wordStart) + this._text.slice(this._cursor); |
| 128 | this._cursor = wordStart; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | deleteWordForward(): void { |
| 133 | const wordEnd = this.findWordBoundary(this._cursor, "right"); |
| 134 | if (wordEnd > this._cursor) { |
| 135 | this._text = |
| 136 | this._text.slice(0, this._cursor) + this._text.slice(wordEnd); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | moveToStart(): void { |
| 141 | this._cursor = 0; |
| 142 | } |
| 143 | |
| 144 | moveToEnd(): void { |
| 145 | this._cursor = this._text.length; |
| 146 | } |
| 147 | |
| 148 | moveLeft(): void { |
| 149 | this._cursor = Math.max(0, this._cursor - 1); |
| 150 | } |
| 151 | |
| 152 | moveRight(): void { |
| 153 | this._cursor = Math.min(this._text.length, this._cursor + 1); |
| 154 | } |
| 155 | |
| 156 | clear(): void { |
| 157 | this._text = ""; |
| 158 | this._cursor = 0; |
| 159 | this._pasteMap.clear(); |
| 160 | this._pasteCounter = 0; |
| 161 | this._imageMap.clear(); |
| 162 | this._imageCounter = 0; |
| 163 | this._pasteBuffer = ""; |
| 164 | this._inPasteMode = false; |
| 165 | this._rapidInputBuffer = ""; |
| 166 | this._rapidInputStartPos = 0; |
| 167 | this._lastInputTime = 0; |
| 168 | if (this._rapidInputTimer) { |
| 169 | clearTimeout(this._rapidInputTimer); |
| 170 | this._rapidInputTimer = null; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | isInPasteMode(): boolean { |
| 175 | return this._inPasteMode; |
| 176 | } |
| 177 | |
| 178 | isInRapidInputMode(): boolean { |
| 179 | return this._rapidInputBuffer.length > 0; |
| 180 | } |
| 181 | |
| 182 | setStateChangeCallback(callback: () => void): void { |
| 183 | this._onStateChange = callback; |
| 184 | } |
| 185 | |
| 186 | // Called on Enter to expand full pasted content before submission |
| 187 | expandAllPasteBlocks(): void { |
| 188 | for (const [placeholder, originalContent] of this._pasteMap.entries()) { |
| 189 | const regex = new RegExp(this.escapeRegex(placeholder), "g"); |
| 190 | // Normalize line endings to prevent terminal display issues |
| 191 | const normalizedContent = originalContent |
| 192 | .replace(/\r\n/g, "\n") |
| 193 | .replace(/\r/g, "\n"); |
| 194 | this._text = this._text.replace(regex, normalizedContent); |
| 195 | } |
| 196 | this._pasteMap.clear(); |
| 197 | } |
| 198 | |
| 199 | // Add image to buffer and return placeholder |
| 200 | addImage(imageBuffer: Buffer): string { |
| 201 | // Validate image size |
| 202 | if (imageBuffer.length > MAX_IMAGE_SIZE) { |
| 203 | throw new Error( |
| 204 | `Image size ${(imageBuffer.length / 1024 / 1024).toFixed(1)}MB exceeds maximum allowed size of ${MAX_IMAGE_SIZE / 1024 / 1024}MB`, |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | // Check image count limit |
| 209 | if (this._imageMap.size >= MAX_IMAGE_COUNT) { |
| 210 | throw new Error(`Cannot add more than ${MAX_IMAGE_COUNT} images`); |
| 211 | } |
| 212 | |
| 213 | // Check total memory usage |
| 214 | const currentMemoryUsage = Array.from(this._imageMap.values()).reduce( |
| 215 | (total, buffer) => total + buffer.length, |
| 216 | 0, |
| 217 | ); |
| 218 | |
| 219 | if (currentMemoryUsage + imageBuffer.length > MAX_TOTAL_IMAGE_MEMORY) { |
| 220 | const currentUsageMB = (currentMemoryUsage / 1024 / 1024).toFixed(1); |
| 221 | const maxUsageMB = MAX_TOTAL_IMAGE_MEMORY / 1024 / 1024; |
| 222 | throw new Error( |
| 223 | `Adding image would exceed total memory limit. Current usage: ${currentUsageMB}MB, Maximum: ${maxUsageMB}MB`, |
| 224 | ); |
| 225 | } |
| 226 | |
| 227 | this._imageCounter++; |
| 228 | const placeholder = `[Image #${this._imageCounter}]`; |
| 229 | this._imageMap.set(placeholder, imageBuffer); |
| 230 | this.insertText(placeholder); |
| 231 | return placeholder; |
| 232 | } |
| 233 | |
| 234 | // Get all images for message formatting |
| 235 | getAllImages(): Map<string, Buffer> { |
| 236 | return new Map(this._imageMap); |
| 237 | } |
| 238 | |
| 239 | // Clear images after message submission |
| 240 | clearImages(): void { |
| 241 | this._imageMap.clear(); |
| 242 | this._imageCounter = 0; |
| 243 | } |
| 244 | |
| 245 | // Test helper: forces immediate finalization without waiting for timers |
| 246 | flushPendingInput(): void { |
| 247 | if (this._rapidInputTimer) { |
| 248 | clearTimeout(this._rapidInputTimer); |
| 249 | this._rapidInputTimer = null; |
| 250 | this.finalizeRapidInput(); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | private escapeRegex(str: string): string { |
| 255 | return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 256 | } |
| 257 | |
| 258 | // Creates placeholder for single line or multi-line pastes |
| 259 | private createPlaceholder(originalText: string): string { |
| 260 | this._pasteCounter++; |
| 261 | const lineCount = originalText.split(/\r\n|\r|\n/).length; |
| 262 | |
| 263 | if (lineCount === 1) { |
| 264 | return `[Paste #${this._pasteCounter}]`; |
| 265 | } else { |
| 266 | return `[Paste #${this._pasteCounter}, ${lineCount} lines]`; |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // Handles bracketed paste: \e[200~ (start) and \e[201~ (end) sequences |
| 271 | private handleBracketedPaste(input: string): boolean { |
| 272 | // Modern terminals wrap pasted content in escape sequences |
| 273 | if (input === "\u001b[200~") { |
| 274 | // Clear any pending rapid input timer to avoid conflicts |
| 275 | if (this._rapidInputTimer) { |
| 276 | clearTimeout(this._rapidInputTimer); |
| 277 | this._rapidInputTimer = null; |
| 278 | } |
| 279 | this._inPasteMode = true; |
| 280 | this._pasteBuffer = ""; |
| 281 | return true; |
| 282 | } |
| 283 | |
| 284 | if (input === "\u001b[201~") { |
| 285 | this._inPasteMode = false; |
| 286 | |
| 287 | if (this._pasteBuffer.length > COLLAPSE_SIZE) { |
| 288 | const placeholder = this.createPlaceholder(this._pasteBuffer); |
| 289 | this._pasteMap.set(placeholder, this._pasteBuffer); |
| 290 | this.insertText(placeholder); |
| 291 | } else { |
| 292 | this.insertText(this._pasteBuffer); |
| 293 | } |
| 294 | |
| 295 | this._pasteBuffer = ""; |
| 296 | return true; |
| 297 | } |
| 298 | |
| 299 | return false; |
| 300 | } |
| 301 | |
| 302 | // Fallback paste detection: detects rapid chunks by timing and size RAPID_INPUT_THRESHOLD |
| 303 | private handleRapidInput(input: string): boolean { |
| 304 | const now = Date.now(); |
| 305 | const timeSinceLastInput = now - this._lastInputTime; |
| 306 | |
| 307 | // If we're already in rapid input mode and this comes quickly, add to buffer |
| 308 | // But only if it's a reasonably large chunk - small inputs are likely typing, not paste |
| 309 | // This prevents typed characters from being mixed into paste content during accumulation |
| 310 | if ( |
| 311 | this._rapidInputBuffer.length > 0 && |
| 312 | timeSinceLastInput < 200 && |
| 313 | input.length >= 50 |
| 314 | ) { |
| 315 | this._rapidInputBuffer += input; |
| 316 | this._lastInputTime = now; |
| 317 | |
| 318 | if (this._rapidInputTimer) { |
| 319 | clearTimeout(this._rapidInputTimer); |
| 320 | } |
| 321 | |
| 322 | // Reset timer: 200ms pause indicates end of paste |
| 323 | this._rapidInputTimer = setTimeout(() => { |
| 324 | this.finalizeRapidInput(); |
| 325 | }, 200); |
| 326 | |
| 327 | return true; |
| 328 | } |
| 329 | |
| 330 | // Fallback paste detection: some terminals send large pastes as rapid chunks |
| 331 | // instead of using bracketed paste mode. We detect this by timing between inputs. |
| 332 | // The >= 50 char threshold was restored to detect Terminal.app/Ghostty split pastes |
| 333 | if ( |
| 334 | input.length > RAPID_INPUT_THRESHOLD || |
| 335 | (input.length >= 50 && this._rapidInputBuffer.length === 0) |
| 336 | ) { |
| 337 | this._rapidInputStartPos = this._cursor; |
| 338 | |
| 339 | // Accumulate chunks without inserting to avoid visual flicker |
| 340 | this._rapidInputBuffer = input; |
| 341 | this._lastInputTime = now; |
| 342 | |
| 343 | if (this._rapidInputTimer) { |
| 344 | clearTimeout(this._rapidInputTimer); |
| 345 | } |
| 346 | |
| 347 | // 200ms pause indicates end of paste |
| 348 | this._rapidInputTimer = setTimeout(() => { |
| 349 | this.finalizeRapidInput(); |
| 350 | }, 200); |
| 351 | |
| 352 | return true; // Consume input without inserting until finalized |
| 353 | } |
| 354 | |
| 355 | this._lastInputTime = now; |
| 356 | return false; |
| 357 | } |
| 358 | |
| 359 | // Called after rapid input timer expires to collapse or insert buffered content |
| 360 | private finalizeRapidInput(): void { |
| 361 | if (this._rapidInputBuffer.length > COLLAPSE_SIZE) { |
| 362 | const placeholder = this.createPlaceholder(this._rapidInputBuffer); |
| 363 | this._pasteMap.set(placeholder, this._rapidInputBuffer); |
| 364 | |
| 365 | this._text = |
| 366 | this._text.slice(0, this._rapidInputStartPos) + |
| 367 | placeholder + |
| 368 | this._text.slice(this._rapidInputStartPos); |
| 369 | this._cursor = this._rapidInputStartPos + placeholder.length; |
| 370 | |
| 371 | if (this._onStateChange) { |
| 372 | this._onStateChange(); |
| 373 | } |
| 374 | } else { |
| 375 | this.insertText(this._rapidInputBuffer); |
| 376 | |
| 377 | if (this._onStateChange) { |
| 378 | this._onStateChange(); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | this._rapidInputBuffer = ""; |
| 383 | this._rapidInputStartPos = 0; |
| 384 | this._rapidInputTimer = null; |
| 385 | } |
| 386 | |
| 387 | private handleOptionKey(sequence: string): boolean { |
| 388 | // Option + backspace (usually \u001b\u0008 or \u001b\u007f) |
| 389 | if (sequence === "\u0008" || sequence === "\u007f") { |
| 390 | this.deleteWordBackward(); |
| 391 | return true; |
| 392 | } |
| 393 | return true; // Consume other option sequences |
| 394 | } |
| 395 | |
| 396 | private handleCtrlKey(input: string): boolean { |
| 397 | switch (input) { |
| 398 | case "a": |
| 399 | this.moveToStart(); |
| 400 | return true; |
| 401 | case "e": |
| 402 | this.moveToEnd(); |
| 403 | return true; |
| 404 | case "u": |
| 405 | // Delete from cursor to start of line |
| 406 | this._text = this._text.slice(this._cursor); |
| 407 | this._cursor = 0; |
| 408 | return true; |
| 409 | case "k": |
| 410 | // Delete from cursor to end of line |
| 411 | this._text = this._text.slice(0, this._cursor); |
| 412 | return true; |
| 413 | case "w": |
| 414 | this.deleteWordBackward(); |
| 415 | return true; |
| 416 | case "d": |
| 417 | this.deleteWordForward(); |
| 418 | return true; |
| 419 | default: |
| 420 | return false; |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | private handleMetaKey(input: string, key: Key): boolean { |
| 425 | if (key.backspace || key.delete) { |
| 426 | this.deleteWordBackward(); |
| 427 | return true; |
| 428 | } |
| 429 | if (key.leftArrow) { |
| 430 | this.moveWordLeft(); |
| 431 | return true; |
| 432 | } |
| 433 | if (key.rightArrow) { |
| 434 | this.moveWordRight(); |
| 435 | return true; |
| 436 | } |
| 437 | // Handle option+left/right as characters (on Mac, option+arrow sends character codes) |
| 438 | if (input === "b") { |
| 439 | this.moveWordLeft(); |
| 440 | return true; |
| 441 | } |
| 442 | if (input === "f") { |
| 443 | this.moveWordRight(); |
| 444 | return true; |
| 445 | } |
| 446 | return false; |
| 447 | } |
| 448 | |
| 449 | private handleArrowKeys(key: Key): boolean { |
| 450 | if (key.leftArrow && !key.meta) { |
| 451 | this.moveLeft(); |
| 452 | return true; |
| 453 | } |
| 454 | if (key.rightArrow && !key.meta) { |
| 455 | this.moveRight(); |
| 456 | return true; |
| 457 | } |
| 458 | return false; |
| 459 | } |
| 460 | |
| 461 | private handleDeleteKeys(key: Key): boolean { |
| 462 | // On Mac, backspace key registers as key.delete, so treat it as backward deletion |
| 463 | if ((key.delete || key.backspace) && !key.meta) { |
| 464 | this.deleteBackward(); |
| 465 | return true; |
| 466 | } |
| 467 | return false; |
| 468 | } |
| 469 | |
| 470 | private handleSpecialKeys(input: string, key: Key): boolean { |
| 471 | // Detect option key combinations through escape sequences |
| 472 | const isOptionKey = input.startsWith("\u001b") && input.length > 1; |
| 473 | |
| 474 | // Handle option key combinations (detected through escape sequences) |
| 475 | if (isOptionKey) { |
| 476 | return this.handleOptionKey(input.slice(1)); |
| 477 | } |
| 478 | |
| 479 | // Handle special key combinations based on input character |
| 480 | if (key.ctrl && this.handleCtrlKey(input)) { |
| 481 | return true; |
| 482 | } |
| 483 | |
| 484 | // Handle meta key combinations (cmd on Mac) |
| 485 | if (key.meta && this.handleMetaKey(input, key)) { |
| 486 | return true; |
| 487 | } |
| 488 | |
| 489 | // Handle arrow keys |
| 490 | if (this.handleArrowKeys(key)) { |
| 491 | return true; |
| 492 | } |
| 493 | |
| 494 | // Handle backspace/delete |
| 495 | if (this.handleDeleteKeys(key)) { |
| 496 | return true; |
| 497 | } |
| 498 | |
| 499 | return false; |
| 500 | } |
| 501 | |
| 502 | private handleTextInput(input: string): boolean { |
| 503 | // Direct paste detection: single large input - but delay insertion to catch split pastes |
| 504 | if (input.length > COLLAPSE_SIZE && this._rapidInputBuffer.length === 0) { |
| 505 | // Start rapid input mode immediately to delay placeholder creation |
| 506 | this._rapidInputStartPos = this._cursor; |
| 507 | this._rapidInputBuffer = input; |
| 508 | this._lastInputTime = Date.now(); |
| 509 | |
| 510 | if (this._rapidInputTimer) { |
| 511 | clearTimeout(this._rapidInputTimer); |
| 512 | } |
| 513 | |
| 514 | // Wait 250ms to see if more content comes (split paste) |
| 515 | this._rapidInputTimer = setTimeout(() => { |
| 516 | this.finalizeRapidInput(); |
| 517 | }, 250); |
| 518 | |
| 519 | return true; |
| 520 | } |
| 521 | |
| 522 | // Fallback: detect chunked paste operations |
| 523 | if (this.handleRapidInput(input)) { |
| 524 | return true; |
| 525 | } |
| 526 | |
| 527 | this.insertText(input); |
| 528 | return true; |
| 529 | } |
| 530 | |
| 531 | handleInput(input: string, key: Key): boolean { |
| 532 | // Handle bracketed paste sequences first |
| 533 | if (this.handleBracketedPaste(input)) { |
| 534 | return true; |
| 535 | } |
| 536 | |
| 537 | // If we're in paste mode, accumulate the pasted content but DON'T insert it yet |
| 538 | if (this._inPasteMode) { |
| 539 | this._pasteBuffer += input; |
| 540 | // Don't insert text during paste mode - wait until paste ends |
| 541 | return true; |
| 542 | } |
| 543 | |
| 544 | // Handle special keys (option, ctrl, meta, arrows, delete) |
| 545 | if (this.handleSpecialKeys(input, key)) { |
| 546 | return true; |
| 547 | } |
| 548 | |
| 549 | // Handle regular text input |
| 550 | const isOptionKey = input.startsWith("\u001b") && input.length > 1; |
| 551 | if (input && input.length >= 1 && !key.ctrl && !key.meta && !isOptionKey) { |
| 552 | return this.handleTextInput(input); |
| 553 | } |
| 554 | |
| 555 | return false; |
| 556 | } |
| 557 | |
| 558 | // Helper method to render text with cursor |
| 559 | renderWithCursor(placeholder?: string): { |
| 560 | text: string; |
| 561 | cursorPosition: number; |
| 562 | } { |
| 563 | if (this._text.length === 0 && placeholder) { |
| 564 | return { text: placeholder, cursorPosition: 0 }; |
| 565 | } |
| 566 | |
| 567 | return { |
| 568 | text: this._text, |
| 569 | cursorPosition: this._cursor, |
| 570 | }; |
| 571 | } |
| 572 | } |