@tensorspark/dravix-code 1.5.0 → 1.5.1

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.
package/dist/cli/repl.js CHANGED
@@ -6,12 +6,12 @@ import { streamChat, fetchSystemPrompt, FLASH_MODEL } from '../services/ai.js';
6
6
  import { buildContext } from '../services/context.js';
7
7
  import { parseOps, executeSingleOp, computeDiff } from '../services/executor.js';
8
8
  import { handleCommand } from './commands.js';
9
- import { printOpResult, printError, printInfo, colors } from '../utils/display.js';
9
+ import { printOpResult, printError, printInfo, colors, Spinner, SPINNER_FRAMES, stripAnsi, visWidth, charWidth, clipVis, clipStartVis, padVis, wrapAnsi, physRowsOf, renderUnifiedDiff, renderCompactHeader, } from '../utils/display.js';
10
+ import { ChatLayout } from '../utils/layout.js';
10
11
  import { saveConversation, loadConversation, listConversations, generateTitle, generateId } from '../services/conversations.js';
11
12
  import { getToken } from '../services/auth.js';
12
13
  import { checkUsage, reportUsage, estimateTokens, usageBar, fmtNum, formatResetTime } from '../services/usage.js';
13
14
  let _serverWebDesignerSkill = '';
14
- const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
15
15
  const SLASH_COMMANDS = [
16
16
  { name: '/files', desc: 'List project files and git status' },
17
17
  { name: '/resume', desc: 'Resume a saved conversation' },
@@ -134,15 +134,11 @@ class TagStripper {
134
134
  return r;
135
135
  }
136
136
  }
137
- // ── Helpers ─────────────────────────────────────────────────────
138
- function stripAnsi(s) {
139
- return s.replace(/\x1b\[[0-9;]*m/g, '');
140
- }
141
137
  // ── Syntax highlighter ───────────────────────────────────────────
142
138
  const SH = {
143
139
  keyword: chalk.hex('#a78bfa'),
144
140
  string: chalk.hex('#86efac'),
145
- comment: chalk.hex('#4b5563'),
141
+ comment: chalk.hex('#64748b'),
146
142
  number: chalk.hex('#fb923c'),
147
143
  type: chalk.hex('#67e8f9'),
148
144
  fn: chalk.hex('#60a5fa'),
@@ -157,7 +153,6 @@ const KW_GO = new Set('break case chan const continue default defer else fallthr
157
153
  const KW_RS = new Set('as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type union unsafe use where while'.split(' '));
158
154
  function highlightCode(line, lang) {
159
155
  const L = lang.toLowerCase();
160
- // ── JSON ─────────────────────────────────────────────────────
161
156
  if (L === 'json' || L === 'jsonc') {
162
157
  let r = '';
163
158
  let i = 0;
@@ -204,7 +199,6 @@ function highlightCode(line, lang) {
204
199
  }
205
200
  return r;
206
201
  }
207
- // ── Choose keyword set ────────────────────────────────────────
208
202
  const KW = L === 'py' || L === 'python' ? KW_PY
209
203
  : L === 'go' ? KW_GO
210
204
  : L === 'rs' || L === 'rust' ? KW_RS
@@ -212,24 +206,20 @@ function highlightCode(line, lang) {
212
206
  const lineComStarts = (L === 'py' || L === 'python' || L === 'sh' || L === 'bash' || L === 'shell' || L === 'zsh') ? ['#']
213
207
  : (L === 'lua' || L === 'sql') ? ['--']
214
208
  : ['//', '#'];
215
- // ── Tokenize ─────────────────────────────────────────────────
216
209
  let result = '';
217
210
  let i = 0;
218
211
  while (i < line.length) {
219
- // Line comment
220
212
  const lc = lineComStarts.find(s => line.startsWith(s, i));
221
213
  if (lc) {
222
214
  result += SH.comment(line.slice(i));
223
215
  break;
224
216
  }
225
- // Block comment /* */
226
217
  if (line.startsWith('/*', i)) {
227
218
  const end = line.indexOf('*/', i + 2);
228
219
  result += SH.comment(end >= 0 ? line.slice(i, end + 2) : line.slice(i));
229
220
  i = end >= 0 ? end + 2 : line.length;
230
221
  continue;
231
222
  }
232
- // String / template literal
233
223
  if (line[i] === '"' || line[i] === "'" || line[i] === '`') {
234
224
  const q = line[i];
235
225
  let j = i + 1;
@@ -248,7 +238,6 @@ function highlightCode(line, lang) {
248
238
  i = j;
249
239
  continue;
250
240
  }
251
- // Number
252
241
  if (/\d/.test(line[i]) && (i === 0 || !/[\w$]/.test(line[i - 1]))) {
253
242
  const m = line.slice(i).match(/^(?:0x[\da-fA-F]+|0b[01]+|\d+\.?\d*(?:[eE][+-]?\d+)?)/);
254
243
  if (m) {
@@ -257,7 +246,6 @@ function highlightCode(line, lang) {
257
246
  continue;
258
247
  }
259
248
  }
260
- // Identifier / keyword / type / function
261
249
  if (/[a-zA-Z_$]/.test(line[i])) {
262
250
  let j = i;
263
251
  while (j < line.length && /[\w$]/.test(line[j]))
@@ -285,12 +273,25 @@ function highlightCode(line, lang) {
285
273
  }
286
274
  return result;
287
275
  }
288
- // ── Markdown renderer (line-buffered, streaming-safe) ───────────
276
+ // ── Markdown renderer (line-buffered, ANSI-wrap safe) ─────────────
289
277
  function applyInline(text) {
290
- return text
291
- .replace(/\*\*(.+?)\*\*|__(.+?)__/g, (_, a, b) => chalk.bold(a ?? b))
292
- .replace(/`([^`\n]+)`/g, (_, c) => '`' + chalk.hex('#fbbf24')(c) + '`')
293
- .replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, (_, t) => chalk.italic(t));
278
+ // Protect inline code spans first so **bold** / *italic* inside backticks are never mutated
279
+ const codeSpans = [];
280
+ let s = text.replace(/`([^`\n]+)`/g, (_, c) => {
281
+ const idx = codeSpans.length;
282
+ codeSpans.push(chalk.bgHex('#1e293b').hex('#7dd3fc')(c));
283
+ return `\x00CODE${idx}\x00`;
284
+ });
285
+ // Links [label](url)
286
+ s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, (_, label, url) => colors.primary(label) + colors.muted(` (${url})`));
287
+ // Bold **...** / __...__
288
+ s = s.replace(/\*\*(.+?)\*\*|__(.+?)__/g, (_, a, b) => chalk.bold.hex('#f8fafc')(a ?? b ?? ''));
289
+ // Strikethrough ~~...~~
290
+ s = s.replace(/~~([^~\n]+)~~/g, (_, t) => chalk.strikethrough.hex('#64748b')(t));
291
+ // Italic *...* (avoid matching inside words/multiplication)
292
+ s = s.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g, (_, t) => chalk.italic(t));
293
+ // Restore inline code spans
294
+ return s.replace(/\x00CODE(\d+)\x00/g, (_, idx) => codeSpans[Number(idx)] ?? '');
294
295
  }
295
296
  class MarkdownRenderer {
296
297
  lineBuf = '';
@@ -301,7 +302,6 @@ class MarkdownRenderer {
301
302
  inTable = false;
302
303
  tableRows = [];
303
304
  format(chunk) {
304
- // Strip \r to normalise Windows/mixed line endings
305
305
  const clean = chunk.replace(/\r/g, '');
306
306
  let out = '';
307
307
  for (const c of clean) {
@@ -349,9 +349,11 @@ class MarkdownRenderer {
349
349
  return '';
350
350
  }
351
351
  // ── Table row ─────────────────────────────────────────────
352
- if (raw.startsWith('|')) {
352
+ if (raw.trimStart().startsWith('|')) {
353
353
  this.inTable = true;
354
- const allCells = raw.split('|').slice(1, -1).map(c => c.trim());
354
+ const trimmed = raw.trim();
355
+ const parts = trimmed.split('|');
356
+ const allCells = (parts.length >= 2 ? parts.slice(1, trimmed.endsWith('|') ? -1 : undefined) : parts).map(c => c.trim());
355
357
  const isSep = allCells.length > 0 && allCells.every(c => /^:?-+:?$/.test(c));
356
358
  if (!isSep && allCells.length > 0) {
357
359
  this.tableRows.push(allCells);
@@ -362,13 +364,15 @@ class MarkdownRenderer {
362
364
  this.inTable = false;
363
365
  return this.renderTable() + this.processLine(raw);
364
366
  }
365
- // ── Blank line (collapse 3+ to 2) ─────────────────────────
367
+ // ── Blank line (collapse 3+ to 1-2) ───────────────────────
366
368
  if (!raw.trim()) {
367
369
  this.blankCount++;
368
- return this.blankCount <= 2 ? '\n' : '';
370
+ return this.blankCount <= 1 ? '\n' : '';
369
371
  }
372
+ const cols = process.stdout.columns ?? 80;
373
+ const maxW = Math.max(cols - 2, 24);
370
374
  // ── Heading # / ## / ### ──────────────────────────────────
371
- const hm = raw.match(/^(#{1,3})\s+(.+)$/);
375
+ const hm = raw.match(/^(#{1,4})\s+(.+)$/);
372
376
  if (hm) {
373
377
  const lvl = hm[1].length;
374
378
  const title = hm[2];
@@ -377,93 +381,89 @@ class MarkdownRenderer {
377
381
  : chalk.bold.hex('#c4b5fd');
378
382
  const prefix = this.blankCount === 0 ? '\n' : '';
379
383
  this.blankCount = 0;
380
- return prefix + ' ' + paint(title) + '\n';
384
+ const wrapped = wrapAnsi(paint(title), maxW, ' ', ' ').join('\n');
385
+ return prefix + wrapped + '\n';
381
386
  }
382
387
  this.blankCount = 0;
383
388
  // ── Unordered list - or * ─────────────────────────────────
384
- const ulm = raw.match(/^(\s*)[-*]\s+(.+)$/);
389
+ const ulm = raw.match(/^(\s*)[-*•]\s+(.+)$/);
385
390
  if (ulm) {
386
- const indent = ' '.repeat(Math.floor(ulm[1].length / 2) + 1);
387
- return indent + colors.muted('·') + ' ' + colors.ai(applyInline(ulm[2])) + '\n';
391
+ const depth = Math.min(Math.floor(ulm[1].length / 2), 4);
392
+ const pad = ' '.repeat(depth + 1);
393
+ const bullet = depth === 0 ? colors.primary('•') : colors.muted('◦');
394
+ const first = `${pad}${bullet} `;
395
+ const next = `${pad} `;
396
+ const body = colors.ai(applyInline(ulm[2]));
397
+ return wrapAnsi(body, maxW, first, next).join('\n') + '\n';
388
398
  }
389
399
  // ── Ordered list 1. ──────────────────────────────────────
390
- const olm = raw.match(/^(\s*)(\d+)\.\s+(.+)$/);
400
+ const olm = raw.match(/^(\s*)(\d+)[.)]\s+(.+)$/);
391
401
  if (olm) {
392
- const indent = ' '.repeat(Math.floor(olm[1].length / 2) + 1);
393
- return indent + colors.muted(olm[2] + '.') + ' ' + colors.ai(applyInline(olm[3])) + '\n';
402
+ const depth = Math.min(Math.floor(olm[1].length / 2), 4);
403
+ const pad = ' '.repeat(depth + 1);
404
+ const num = colors.primary(olm[2] + '.');
405
+ const first = `${pad}${num} `;
406
+ const next = `${pad}${' '.repeat(olm[2].length + 2)}`;
407
+ const body = colors.ai(applyInline(olm[3]));
408
+ return wrapAnsi(body, maxW, first, next).join('\n') + '\n';
394
409
  }
395
410
  // ── Blockquote > ─────────────────────────────────────────
396
411
  const bqm = raw.match(/^>\s?(.*)$/);
397
412
  if (bqm) {
398
- return ' ' + colors.dim('│') + ' ' + colors.muted(applyInline(bqm[1])) + '\n';
413
+ const bar = ' ' + colors.brand('│') + ' ';
414
+ const body = colors.subtext(applyInline(bqm[1]));
415
+ return wrapAnsi(body, maxW, bar, bar).join('\n') + '\n';
399
416
  }
400
417
  // ── Horizontal rule --- / *** ─────────────────────────────
401
418
  if (/^[-*_]{3,}\s*$/.test(raw.trim())) {
402
- return ' ' + colors.dim('─'.repeat(Math.min((process.stdout.columns ?? 80) - 4, 72))) + '\n';
403
- }
404
- // ── Normal text ───────────────────────────────────────────
405
- // Wrap text before right edge, but with minimal margin
406
- const termWidth = process.stdout.columns ?? 80;
407
- const maxTextWidth = termWidth - 1; // just 1 char from right edge
408
- const rawText = applyInline(raw);
409
- if (rawText.length > maxTextWidth) {
410
- // Word-wrap at spaces, keeping lines close to edge
411
- const words = rawText.split(' ');
412
- let line = '';
413
- let result = ' ';
414
- for (const word of words) {
415
- if (line.length + word.length + 1 > maxTextWidth && line.length > 0) {
416
- result += line.trimEnd() + '\n ';
417
- line = word + ' ';
418
- }
419
- else {
420
- line += word + ' ';
421
- }
422
- }
423
- result += line.trimEnd();
424
- return colors.ai(result) + '\n';
419
+ return ' ' + colors.dim('─'.repeat(Math.min(Math.max(cols - 4, 20), 72))) + '\n';
425
420
  }
426
- return ' ' + colors.ai(rawText) + '\n';
421
+ // ── Normal paragraph text ─────────────────────────────────
422
+ const styled = colors.ai(applyInline(raw));
423
+ return wrapAnsi(styled, maxW, ' ', ' ').join('\n') + '\n';
427
424
  }
428
425
  renderTable() {
429
426
  const rows = this.tableRows;
430
427
  this.tableRows = [];
431
428
  if (rows.length === 0)
432
429
  return '';
433
- // Filter out separator rows (--- | --- | ---)
434
430
  const dataRows = rows.filter(r => !r.every(c => /^:?-+:?$/.test(c.trim())));
435
431
  if (dataRows.length === 0)
436
432
  return '';
437
433
  const cols = Math.max(...dataRows.map(r => r.length));
438
434
  const termW = process.stdout.columns ?? 80;
439
- // max usable width per column (distribute evenly, min 6)
440
- const maxColW = Math.max(6, Math.floor((termW - 4 - (cols + 1)) / cols));
441
- const widths = Array(cols).fill(0);
442
- for (const row of dataRows) {
435
+ const availW = Math.max(termW - 4 - (cols + 1), cols * 6);
436
+ const formattedGrid = dataRows.map((row, ri) => Array.from({ length: cols }, (_, ci) => {
437
+ const raw = (row[ci] ?? '').trim();
438
+ const styled = ri === 0 ? chalk.bold.hex('#f8fafc')(stripAnsi(applyInline(raw))) : colors.ai(applyInline(raw));
439
+ return styled;
440
+ }));
441
+ const desired = Array(cols).fill(4);
442
+ for (const row of formattedGrid) {
443
443
  for (let i = 0; i < cols; i++) {
444
- // Strip markdown formatting for width calculation
445
- const rawCell = (row[i] ?? '').replace(/\*\*/g, '').replace(/`/g, '').trim();
446
- const cellLen = Math.min(rawCell.length, maxColW);
447
- widths[i] = Math.max(widths[i], cellLen + 2);
444
+ desired[i] = Math.max(desired[i], visWidth(row[i]) + 2);
448
445
  }
449
446
  }
447
+ const totalDesired = desired.reduce((a, b) => a + b, 0);
448
+ const widths = totalDesired <= availW
449
+ ? desired
450
+ : desired.map(w => Math.max(6, Math.floor((w / totalDesired) * availW)));
450
451
  const bar = (l, m, r) => colors.dim(' ' + l + widths.map(w => '─'.repeat(w)).join(m) + r);
451
452
  let out = '\n' + bar('┌', '┬', '┐') + '\n';
452
- for (let ri = 0; ri < dataRows.length; ri++) {
453
- const row = dataRows[ri];
453
+ for (let ri = 0; ri < formattedGrid.length; ri++) {
454
+ const row = formattedGrid[ri];
454
455
  const cells = widths.map((w, i) => {
455
- const raw = (row[i] ?? '').trim();
456
- // Strip markdown for display but keep formatting
457
- const plain = raw.replace(/\*\*/g, '').replace(/`/g, '');
458
- const cell = plain.length > w - 2 ? plain.slice(0, w - 3) + '…' : plain;
459
- const pad = w - cell.length - 1;
460
- // Apply formatting to the cell content
461
- const formatted = applyInline(raw);
462
- const text = ri === 0 ? chalk.bold.white(cell) : colors.ai(cell);
463
- return ' ' + text + ' '.repeat(Math.max(pad, 0));
456
+ const cellMax = Math.max(w - 2, 1);
457
+ const clipped = visWidth(row[i]) > cellMax
458
+ ? clipVis(stripAnsi(row[i]), cellMax)
459
+ : row[i];
460
+ const finalCell = ri === 0 && typeof clipped === 'string' && !clipped.includes('\x1b')
461
+ ? chalk.bold.hex('#f8fafc')(clipped)
462
+ : clipped;
463
+ return ' ' + padVis(finalCell, w - 1);
464
464
  });
465
465
  out += colors.dim(' │') + cells.join(colors.dim('│')) + colors.dim('│') + '\n';
466
- if (ri === 0 && dataRows.length > 1)
466
+ if (ri === 0 && formattedGrid.length > 1)
467
467
  out += bar('├', '┼', '┤') + '\n';
468
468
  }
469
469
  out += bar('└', '┴', '┘') + '\n';
@@ -487,21 +487,22 @@ class MarkdownRenderer {
487
487
  return this.renderTable();
488
488
  }
489
489
  const termW = process.stdout.columns ?? 80;
490
- const maxInner = Math.min(termW - 8, 80);
491
- const maxLen = lines.length > 0 ? Math.max(...lines.map(l => l.length)) : 0;
492
- const inner = Math.max(maxLen, lang.length + 4, 20, 0);
493
- const capped = Math.min(inner, maxInner);
494
- const dashAfterLang = Math.max(0, capped - lang.length - 2);
495
- const top = lang
496
- ? colors.dim(' ╭─ ') + colors.primary(lang) + colors.dim(' ' + '─'.repeat(dashAfterLang))
497
- : colors.dim(' ╭' + '─'.repeat(capped + 2));
498
- const bot = colors.dim(' ╰' + '─'.repeat(capped + 2));
490
+ const maxLineW = Math.max(termW - 6, 20);
491
+ const barW = Math.min(Math.max(lines.length > 0 ? Math.max(...lines.map(l => visWidth(l))) + 4 : 28, lang.length + 8, 28), Math.max(termW - 4, 24), 96);
499
492
  const canHighlight = lang && !['text', 'txt', 'plain', 'output', 'log'].includes(lang.toLowerCase());
493
+ const dashAfterLang = Math.max(2, barW - visWidth(lang) - 5);
494
+ const top = lang
495
+ ? ' ' + colors.dim('╭─ ') + colors.primary.bold(lang) + colors.dim(' ' + '─'.repeat(dashAfterLang))
496
+ : ' ' + colors.dim('╭' + '─'.repeat(Math.max(barW - 2, 10)));
497
+ const bot = ' ' + colors.dim('╰' + '─'.repeat(Math.max(barW - 2, 10)));
500
498
  let out = '\n' + top + '\n';
501
- for (const l of lines) {
502
- const display = l.length > capped ? l.slice(0, capped - 1) + '…' : l;
503
- const colorized = canHighlight ? highlightCode(display, lang) : colors.text(display);
504
- out += colors.dim(' │ ') + colorized + '\n';
499
+ for (const rawLine of lines) {
500
+ const expanded = rawLine.replace(/\t/g, ' ');
501
+ const colorized = canHighlight ? highlightCode(expanded, lang) : colors.text(expanded);
502
+ const wrapped = wrapAnsi(colorized, maxLineW, ' ' + colors.dim('│') + ' ', ' ' + colors.dim('│') + ' ');
503
+ for (const wl of wrapped) {
504
+ out += wl + '\n';
505
+ }
505
506
  }
506
507
  out += bot + '\n';
507
508
  return out;
@@ -582,35 +583,66 @@ function opKey(op, cwd) {
582
583
  return exists ? 'modify' : 'create';
583
584
  return op.type;
584
585
  }
586
+ // ── User message card ───────────────────────────────────────────
587
+ function renderUserMessage(text, cols = process.stdout.columns ?? 80, pasteHint) {
588
+ const displayRaw = pasteHint ?? text;
589
+ const maxInner = Math.max(cols - 6, 16);
590
+ const bg = chalk.bgHex('#1b2238').hex('#f1f5f9');
591
+ const bar = colors.primary('▌');
592
+ const rawLines = displayRaw.replace(/\r/g, '').split('\n');
593
+ const wrappedAll = [];
594
+ for (const rl of rawLines) {
595
+ const clean = rl.replace(/\t/g, ' ');
596
+ if (!clean) {
597
+ wrappedAll.push('');
598
+ }
599
+ else {
600
+ wrappedAll.push(...wrapAnsi(clean, maxInner, '', ''));
601
+ }
602
+ }
603
+ if (wrappedAll.length === 0)
604
+ wrappedAll.push('');
605
+ process.stdout.write('\n');
606
+ for (let i = 0; i < wrappedAll.length; i++) {
607
+ const prefixIcon = i === 0 ? ' › ' : ' ';
608
+ const padded = padVis(wrappedAll[i], maxInner);
609
+ process.stdout.write(' ' + bar + bg(prefixIcon + padded + ' ') + '\n');
610
+ }
611
+ process.stdout.write('\n');
612
+ }
585
613
  // ── Permission prompt ───────────────────────────────────────────
586
614
  function opStyle(label) {
587
615
  const l = label.toLowerCase();
588
616
  if (l.startsWith('create folder'))
589
- return { icon: '+', paint: colors.success };
617
+ return { icon: '+', paint: colors.success, borderHex: '#065f46' };
590
618
  if (l.startsWith('create'))
591
- return { icon: '+', paint: colors.success };
619
+ return { icon: '+', paint: colors.success, borderHex: '#065f46' };
592
620
  if (l.startsWith('delete'))
593
- return { icon: '!', paint: colors.error };
621
+ return { icon: '!', paint: colors.error, borderHex: '#7f1d1d' };
594
622
  if (l.startsWith('run'))
595
- return { icon: '$', paint: colors.primary };
596
- return { icon: '~', paint: colors.warn };
623
+ return { icon: '$', paint: colors.primary, borderHex: '#4338ca' };
624
+ return { icon: '~', paint: colors.warn, borderHex: '#78350f' };
597
625
  }
598
- const OPT_LABELS_DEFAULT = ['Apply this change', 'Apply to all changes', 'Skip this change'];
599
- const OPT_LABELS_RUN = ['Yes, run it', 'No, skip'];
600
- const SEP = '─'.repeat(40);
601
- function clearMenu(lines) {
602
- process.stdout.write('\x1b[2K');
603
- for (let i = 0; i < lines; i++) {
626
+ const OPT_LABELS_DEFAULT = [
627
+ { label: 'Apply this change', key: 'y' },
628
+ { label: 'Apply to all changes', key: 'a' },
629
+ { label: 'Skip this change', key: 'n' },
630
+ ];
631
+ const OPT_LABELS_RUN = [
632
+ { label: 'Yes, run command', key: 'y' },
633
+ { label: 'No, skip', key: 'n' },
634
+ ];
635
+ function clearMenu(physLines) {
636
+ process.stdout.write('\r\x1b[2K');
637
+ for (let i = 0; i < physLines; i++) {
604
638
  process.stdout.write('\x1b[1A\x1b[2K');
605
639
  }
606
640
  }
607
- // Returns number of terminal lines printed (for clearing after acceptance)
641
+ // Returns exact number of physical terminal rows printed (for clean clearing after acceptance)
608
642
  function printDiffPreview(op, cwd) {
609
643
  let printed = 0;
610
644
  try {
611
645
  const cols = process.stdout.columns ?? 80;
612
- const maxW = Math.min(cols - 12, 120);
613
- const clip = (t) => t.length > maxW ? t.slice(0, maxW - 1) + '…' : t;
614
646
  let diff = null;
615
647
  if (op.type === 'write' && op.path && op.content !== undefined) {
616
648
  const fp = path.resolve(cwd, op.path);
@@ -618,7 +650,6 @@ function printDiffPreview(op, cwd) {
618
650
  diff = computeDiff(old, op.content);
619
651
  }
620
652
  else if (op.type === 'edit' && op.path && op.find !== undefined && op.replace !== undefined) {
621
- // Find real line offset in file so line numbers match actual file
622
653
  const rawDiff = computeDiff(op.find, op.replace);
623
654
  try {
624
655
  const fp = path.resolve(cwd, op.path);
@@ -646,174 +677,100 @@ function printDiffPreview(op, cwd) {
646
677
  removes > 0 ? colors.error.bold(`-${removes}`) : '',
647
678
  adds > 0 ? colors.success.bold(`+${adds}`) : '',
648
679
  ].filter(Boolean).join(' ');
649
- const writeLine = (s) => { process.stdout.write(s + '\n'); printed++; };
680
+ const writeLine = (s) => {
681
+ process.stdout.write(s + '\n');
682
+ const r = physRowsOf(s, cols);
683
+ printed += r;
684
+ return r;
685
+ };
650
686
  process.stdout.write('\n');
651
- printed++;
652
- writeLine(colors.warn(' ~') +
653
- colors.subtext(' ') +
654
- colors.text(op.path ?? '') +
687
+ printed += 1;
688
+ writeLine(' ' + colors.warn('~') + ' ' +
689
+ colors.text.bold(clipVis(op.path ?? '', Math.max(cols - 22, 16))) +
655
690
  (statStr ? ' ' + statStr : ''));
656
- const CONTEXT = 2;
657
- const show = new Uint8Array(diff.length);
658
- for (let i = 0; i < diff.length; i++) {
659
- if (diff[i].kind !== 'context') {
660
- for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++)
661
- show[c] = 1;
662
- }
663
- }
664
- const renderLine = (line) => {
665
- const num = String(line.lineNo).padStart(5, ' ');
666
- if (line.kind === 'remove') {
667
- const content = ` ${num} ${colors.error('-')} ${clip(line.text)}`;
668
- writeLine(' ' + colors.error('▌') + chalk.bgHex('#1c0a0a')(content.padEnd(cols - 3)));
669
- }
670
- else if (line.kind === 'add') {
671
- const content = ` ${num} ${colors.success('+')} ${clip(line.text)}`;
672
- writeLine(' ' + colors.success('▌') + chalk.bgHex('#021a0e')(content.padEnd(cols - 3)));
673
- }
674
- else {
675
- writeLine(colors.dim(` ${num} ${clip(line.text)}`));
676
- }
677
- };
678
- const hunks = [];
679
- let curHunk = [];
680
- let lastIdx = -1;
681
- for (let i = 0; i < diff.length; i++) {
682
- if (!show[i])
683
- continue;
684
- if (lastIdx >= 0 && i > lastIdx + 1) {
685
- hunks.push(curHunk);
686
- curHunk = [];
687
- }
688
- lastIdx = i;
689
- curHunk.push(diff[i]);
690
- }
691
- if (curHunk.length > 0)
692
- hunks.push(curHunk);
693
- let shown = 0;
694
- const MAX_LINES = 60;
695
- for (let h = 0; h < hunks.length; h++) {
696
- if (shown >= MAX_LINES)
697
- break;
698
- if (h > 0) {
699
- writeLine(colors.dim(' ╌╌╌'));
700
- }
701
- const hunk = hunks[h];
702
- const before = [];
703
- const hRem = [];
704
- const hAdd = [];
705
- let pendingCtx = [];
706
- let seenChange = false;
707
- for (const line of hunk) {
708
- if (line.kind === 'context') {
709
- if (!seenChange)
710
- before.push(line);
711
- else
712
- pendingCtx.push(line);
713
- }
714
- else {
715
- seenChange = true;
716
- pendingCtx = [];
717
- if (line.kind === 'remove')
718
- hRem.push(line);
719
- else
720
- hAdd.push(line);
721
- }
722
- }
723
- for (const l of before)
724
- renderLine(l);
725
- for (const l of hRem) {
726
- if (shown >= MAX_LINES)
727
- break;
728
- renderLine(l);
729
- shown++;
730
- }
731
- for (const l of hAdd) {
732
- if (shown >= MAX_LINES)
733
- break;
734
- renderLine(l);
735
- shown++;
736
- }
737
- for (const l of pendingCtx)
738
- renderLine(l);
739
- }
740
- const total = diff.filter(d => d.kind !== 'context').length;
741
- if (total > MAX_LINES) {
742
- writeLine(colors.muted(` … ${total - MAX_LINES} more lines`));
743
- }
691
+ printed += renderUnifiedDiff(diff, { maxLines: 44, cols, writeLine });
744
692
  }
745
693
  catch { /* ignore */ }
746
694
  return printed;
747
695
  }
748
- async function askPermission(label, key, alwaysAllowed, noAlways, diffShown, previewLineCount = 0) {
696
+ async function askPermission(label, key, alwaysAllowed, noAlways, diffShown, previewLineCount = 0, layout, sessionMeta, cwd) {
749
697
  if (!noAlways && alwaysAllowed.has(key))
750
698
  return true;
751
699
  return new Promise((resolve) => {
752
700
  let sel = 0;
753
- let drawn = false;
701
+ let drawnPhysRows = 0;
754
702
  const ci = label.indexOf(': ');
755
703
  const opType = ci !== -1 ? label.slice(0, ci) : label;
756
704
  const opValue = ci !== -1 ? label.slice(ci + 2) : '';
757
- const { icon, paint } = opStyle(label);
758
- const optLabels = noAlways ? OPT_LABELS_RUN : OPT_LABELS_DEFAULT;
759
- const optCount = optLabels.length;
760
- // when diff already shown: just blank + options (no box)
761
- const menuLines = diffShown ? (1 + optCount) : (noAlways ? 3 : 4) + 1 + optCount;
762
- function printMenu() {
763
- if (drawn)
764
- clearMenu(menuLines);
765
- drawn = true;
766
- let lines;
767
- if (diffShown) {
768
- lines = [
769
- '',
770
- ...optLabels.map((lbl, i) => i === sel
771
- ? ` ${colors.primary('›')} ${colors.primary.bold(lbl)}`
772
- : ` ${colors.muted(lbl)}`),
773
- ];
774
- }
775
- else {
776
- let boxLines;
777
- if (noAlways) {
778
- const dashes = SEP.length - 2 - 'run command'.length - 1;
779
- boxLines = [
780
- colors.dim(' ╭─ ') + colors.primary('run command') + colors.dim(' ' + '─'.repeat(Math.max(dashes, 1))),
781
- ` │ ${chalk.hex('#fbbf24')('$')} ${chalk.white(opValue)}`,
782
- colors.dim(' ╰' + SEP),
783
- ];
705
+ const { icon, paint, borderHex } = opStyle(label);
706
+ const optItems = noAlways ? OPT_LABELS_RUN : OPT_LABELS_DEFAULT;
707
+ const optCount = optItems.length;
708
+ function buildLines() {
709
+ const cols = process.stdout.columns ?? 80;
710
+ const DW = Math.min(Math.max(cols - 4, 42), 82);
711
+ const IW = DW - 6;
712
+ const BC = chalk.hex(borderHex);
713
+ const lines = [];
714
+ if (!diffShown) {
715
+ const headerTag = noAlways ? ' $ Run command ' : ` ${icon} ${opType} `;
716
+ const hDashes = Math.max(DW - 3 - visWidth(headerTag), 2);
717
+ lines.push(' ' + BC('╭─') + paint(headerTag) + BC('─'.repeat(hDashes) + '╮'));
718
+ const valColor = noAlways ? colors.warn : colors.text;
719
+ const wrappedVal = wrapAnsi(valColor(opValue), IW, '', '');
720
+ for (const wl of wrappedVal.slice(0, 4)) {
721
+ lines.push(' ' + BC('│') + ' ' + padVis(wl, IW) + ' ' + BC('│'));
722
+ }
723
+ if (wrappedVal.length > 4) {
724
+ lines.push(' ' + BC('│') + ' ' + padVis(colors.muted('…'), IW) + ' ' + BC('│'));
725
+ }
726
+ lines.push(' ' + BC('╰' + '─'.repeat(DW - 2) + '╯'));
727
+ }
728
+ lines.push('');
729
+ const optW = Math.min(DW, 46);
730
+ for (let i = 0; i < optItems.length; i++) {
731
+ const item = optItems[i];
732
+ const isSel = i === sel;
733
+ const keyBadge = isSel
734
+ ? chalk.bgHex('#312e81').hex('#c7d2fe')(` ${item.key} `)
735
+ : colors.dim(`[${item.key}]`);
736
+ if (isSel) {
737
+ const rowInner = padVis(`${colors.primary.bold('›')} ${keyBadge} ${colors.text.bold(item.label)}`, optW - 2);
738
+ lines.push(' ' + chalk.bgHex('#1e253b')(' ' + rowInner + ' '));
784
739
  }
785
740
  else {
786
- boxLines = [
787
- colors.dim(' ╭' + SEP),
788
- ` │ ${paint(icon + ' ' + opType)}`,
789
- ` │ ${chalk.white(opValue)}`,
790
- colors.dim(' ╰' + SEP),
791
- ];
792
- }
793
- lines = [
794
- ...boxLines,
795
- '',
796
- ...optLabels.map((lbl, i) => i === sel
797
- ? ` ${colors.primary('›')} ${colors.primary.bold(lbl)}`
798
- : ` ${colors.muted(lbl)}`),
799
- ];
741
+ lines.push(' ' + ` ${keyBadge} ${colors.subtext(item.label)}`);
742
+ }
800
743
  }
744
+ return lines;
745
+ }
746
+ function printMenu() {
747
+ const cols = process.stdout.columns ?? 80;
748
+ if (drawnPhysRows > 0)
749
+ clearMenu(drawnPhysRows);
750
+ const lines = buildLines();
751
+ drawnPhysRows = lines.reduce((sum, l) => sum + physRowsOf(l, cols), 0);
801
752
  process.stdout.write(lines.join('\n') + '\n');
802
753
  }
803
754
  printMenu();
755
+ function onResize() {
756
+ layout?.resize({ focused: false, streaming: true, placeholder: 'Waiting for confirmation...', cwd, meta: sessionMeta, focusCursor: false });
757
+ printMenu();
758
+ }
759
+ process.stdout.on('resize', onResize);
804
760
  function cleanup() {
805
761
  process.stdin.removeListener('data', onData);
762
+ process.stdout.removeListener('resize', onResize);
806
763
  }
807
764
  function confirm(idx) {
808
765
  cleanup();
809
- clearMenu(menuLines);
810
- // Clear the diff preview lines (all except the first blank separator)
811
- for (let i = 0; i < previewLineCount - 1; i++) {
766
+ clearMenu(drawnPhysRows);
767
+ // Clear the diff preview lines (all except the leading blank separator)
768
+ for (let i = 0; i < Math.max(0, previewLineCount - 1); i++) {
812
769
  process.stdout.write('\x1b[1A\x1b[2K');
813
770
  }
814
771
  const skipIdx = noAlways ? 1 : 2;
815
772
  if (idx === skipIdx) {
816
- process.stdout.write(` ${colors.muted('○')} ${colors.muted('Skipped: ' + label)}\n`);
773
+ process.stdout.write(` ${colors.muted('○')} ${colors.muted('Skipped: ' + clipVis(label, Math.max((process.stdout.columns ?? 80) - 16, 20)))}\n`);
817
774
  resolve(false);
818
775
  }
819
776
  else {
@@ -852,11 +809,12 @@ async function askPermission(label, key, alwaysAllowed, noAlways, diffShown, pre
852
809
  break;
853
810
  case '\x03':
854
811
  cleanup();
855
- clearMenu(menuLines);
812
+ clearMenu(drawnPhysRows);
813
+ layout?.cleanup(true);
856
814
  process.exit(0);
857
815
  }
858
816
  }
859
- catch (e) {
817
+ catch {
860
818
  cleanup();
861
819
  resolve(false);
862
820
  }
@@ -864,25 +822,23 @@ async function askPermission(label, key, alwaysAllowed, noAlways, diffShown, pre
864
822
  process.stdin.on('data', onData);
865
823
  });
866
824
  }
867
- async function readLine(prompt, cwd) {
868
- const rows = process.stdout.rows ?? 24;
869
- const cols = process.stdout.columns ?? 80;
870
- const sR = rows - 2;
871
- const iR = rows - 1;
872
- let SEP = colors.dim(' ' + '─'.repeat(Math.max(cols - 4, 40)));
873
- // Ensure scroll region is active for chat history (top rows)
874
- process.stdout.write(`\x1b[1;${rows - 3}r`);
875
- // Render fixed bottom container (separator + input bar)
876
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
877
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${prompt}`);
878
- process.stdout.write(`\x1b[${iR};5H`);
825
+ async function readLine(layout, cwd, meta, inputHistory) {
826
+ layout.refreshSize();
827
+ // Capture latest chat cursor position BEFORE DECSTBM (\x1b[...r homes cursor to 1;1)
828
+ await layout.captureChatRow();
829
+ process.stdout.write(`\x1b[1;${layout.scrollEnd}r`);
879
830
  return new Promise((resolve) => {
880
- let prefix = '';
831
+ let chars = [];
832
+ let cursor = 0; // codepoint index inside chars
881
833
  let pasteBlock = null;
882
834
  let pasteCount = 0;
883
- let suffix = '';
835
+ let suffixChars = []; // text typed after a pasted block
836
+ let suffixCursor = 0;
837
+ let histIdx = -1; // -1 = live draft, 0..N-1 = history from newest
838
+ let savedDraft = '';
884
839
  let ctrlCCount = 0;
885
840
  let ctrlCTimer = null;
841
+ let statusNotice = '';
886
842
  let atMode = false;
887
843
  let atQuery = '';
888
844
  let atSel = 0;
@@ -899,33 +855,7 @@ async function readLine(prompt, cwd) {
899
855
  let tabBoxLines = 0;
900
856
  let tabDrawn = false;
901
857
  let tabPreWord = '';
902
- function onResize() {
903
- const newCols = process.stdout.columns ?? 80;
904
- const newRows = process.stdout.rows ?? 24;
905
- process.stdout.write(`\x1b[1;${newRows - 3}r`);
906
- SEP = colors.dim(' ' + '─'.repeat(Math.max(newCols - 4, 40)));
907
- if (atMode) {
908
- drawPicker();
909
- }
910
- else if (slashMode) {
911
- drawSlashPicker();
912
- }
913
- else if (tabMode) {
914
- drawTabPicker();
915
- }
916
- else {
917
- redraw();
918
- }
919
- }
920
- process.stdout.on('resize', onResize);
921
- function cleanup() {
922
- if (ctrlCTimer) {
923
- clearTimeout(ctrlCTimer);
924
- ctrlCTimer = null;
925
- }
926
- process.stdin.removeListener('data', onData);
927
- process.stdout.removeListener('resize', onResize);
928
- }
858
+ let atDrawn = false;
929
859
  function loadFiles() {
930
860
  if (allFiles.length > 0)
931
861
  return;
@@ -966,11 +896,11 @@ async function readLine(prompt, cwd) {
966
896
  ...arr.filter(f => !f.endsWith('/')),
967
897
  ];
968
898
  if (!q)
969
- return dirsFirst(allFiles).slice(0, 10);
899
+ return dirsFirst(allFiles).slice(0, 12);
970
900
  const lq = q.toLowerCase();
971
901
  const a = allFiles.filter(f => f.toLowerCase().startsWith(lq));
972
902
  const b = allFiles.filter(f => !f.toLowerCase().startsWith(lq) && f.toLowerCase().includes(lq));
973
- return dirsFirst([...a, ...b]).slice(0, 10);
903
+ return dirsFirst([...a, ...b]).slice(0, 12);
974
904
  }
975
905
  function filterSlash(q) {
976
906
  if (!q)
@@ -978,85 +908,164 @@ async function readLine(prompt, cwd) {
978
908
  const lq = q.toLowerCase();
979
909
  return SLASH_COMMANDS.filter(c => c.name.slice(1).toLowerCase().startsWith(lq));
980
910
  }
981
- let atDrawn = false;
982
- function drawPicker() {
983
- const cols = process.stdout.columns ?? 80;
984
- const rows = process.stdout.rows ?? 24;
985
- const sR = rows - 2;
986
- const iR = rows - 1;
987
- const filtered = filterFiles(atQuery);
988
- if (atSel >= filtered.length && filtered.length > 0)
989
- atSel = filtered.length - 1;
990
- if (atSel < 0)
991
- atSel = 0;
992
- const maxVisible = Math.min(8, Math.max(3, rows - 6));
993
- const shown = filtered.slice(0, maxVisible);
994
- const DW = Math.min(Math.max(cols - 6, 44), 74);
995
- const IW = DW - 6;
911
+ /** Compute horizontal scroll slice & cursor column inside innerTextWidth */
912
+ function renderPlainInput(rawPlain, cursorCharIdx, styledOverride) {
913
+ const innerW = layout.innerTextWidth;
914
+ const cp = [...rawPlain];
915
+ const cIdx = Math.max(0, Math.min(cursorCharIdx, cp.length));
916
+ // Calculate width of each character
917
+ const widths = cp.map(ch => charWidth(ch.codePointAt(0) ?? 0));
918
+ let cursorVis = 0;
919
+ for (let i = 0; i < cIdx; i++)
920
+ cursorVis += widths[i];
921
+ const totalVis = widths.reduce((a, b) => a + b, 0);
922
+ // Keep cursor within [0, innerW - 1]
923
+ let startVis = 0;
924
+ if (cursorVis >= innerW) {
925
+ startVis = cursorVis - innerW + 1;
926
+ }
927
+ let acc = 0;
928
+ let startIdx = 0;
929
+ while (startIdx < cp.length && acc < startVis) {
930
+ acc += widths[startIdx];
931
+ startIdx++;
932
+ }
933
+ let visUsed = 0;
934
+ let endIdx = startIdx;
935
+ while (endIdx < cp.length && visUsed + widths[endIdx] <= innerW) {
936
+ visUsed += widths[endIdx];
937
+ endIdx++;
938
+ }
939
+ let cursorOffset = 0;
940
+ for (let i = startIdx; i < cIdx; i++)
941
+ cursorOffset += widths[i];
942
+ const sliceStr = cp.slice(startIdx, endIdx).join('');
943
+ const displayText = styledOverride && startIdx === 0 && endIdx === cp.length
944
+ ? styledOverride
945
+ : sliceStr
946
+ ? colors.text(sliceStr)
947
+ : '';
948
+ layout.drawComposer({
949
+ displayText,
950
+ cursorOffset,
951
+ placeholder: rawPlain.length === 0 ? 'Ask Dravix anything, @file, or /command...' : undefined,
952
+ focused: true,
953
+ leftOverflow: startIdx > 0,
954
+ rightOverflow: totalVis > acc + visUsed,
955
+ cwd,
956
+ meta,
957
+ notice: statusNotice || undefined,
958
+ focusCursor: true,
959
+ });
960
+ }
961
+ function redraw() {
962
+ if (pasteBlock !== null) {
963
+ const preStr = chars.join('');
964
+ const tag = `[paste: ${pasteCount} line${pasteCount === 1 ? '' : 's'}]`;
965
+ const sufStr = suffixChars.join('');
966
+ const rawCombined = preStr + tag + sufStr;
967
+ const curPos = preStr.length + tag.length + suffixCursor;
968
+ const styled = (preStr ? colors.text(preStr) : '') +
969
+ chalk.bgHex('#312e81').hex('#c7d2fe')(tag) +
970
+ (sufStr ? colors.text(sufStr) : '');
971
+ renderPlainInput(rawCombined, curPos, styled);
972
+ }
973
+ else {
974
+ renderPlainInput(chars.join(''), cursor);
975
+ }
976
+ }
977
+ /** Shared clean popup renderer anchored immediately above the composer box */
978
+ function drawPopupBox(titleLabel, titlePaint, rowsData, emptyMsg, hintText, prevCount, inputPreviewPlain, inputPreviewStyled, cursorCharIdx) {
979
+ layout.refreshSize();
980
+ const cols = layout.cols;
981
+ const sR = layout.topBorderRow;
982
+ const DW = Math.min(Math.max(cols - 4, 42), 76);
983
+ const BC = colors.brand;
984
+ const innerRowW = DW - 6; // inside " │ " + " │" (excluding 2-char indent and 4-char padding)
996
985
  const boxLines = [];
997
- const qLabel = atQuery ? `@${atQuery}` : 'files';
998
- const hDashes = Math.max(DW - 4 - qLabel.length, 1);
999
- boxLines.push(colors.dim(' ╭─ ') + colors.primary(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
1000
- if (shown.length === 0) {
1001
- const msg = 'no matches';
1002
- const pad = ' '.repeat(Math.max(IW - msg.length, 0));
1003
- boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
986
+ const titlePad = ` ${titleLabel} `;
987
+ const hDashes = Math.max(DW - 3 - visWidth(titlePad), 1);
988
+ boxLines.push(' ' + BC('╭─') + titlePaint(titlePad) + BC('─'.repeat(hDashes) + '╮'));
989
+ if (rowsData.length === 0) {
990
+ const msg = padVis(colors.muted(clipVis(emptyMsg, innerRowW - 2)), innerRowW);
991
+ boxLines.push(' ' + BC('│') + ' ' + msg + ' ' + BC('│'));
1004
992
  }
1005
993
  else {
1006
- for (let i = 0; i < shown.length; i++) {
1007
- const f = shown[i];
1008
- const isDir = f.endsWith('/');
1009
- const sel = i === atSel;
1010
- const mark = sel ? colors.primary('›') : ' ';
1011
- const clip = f.length > IW ? f.slice(0, IW - 1) + '…' : f;
1012
- const pad = ' '.repeat(Math.max(IW - clip.length, 0));
1013
- const name = sel && isDir ? colors.primary.bold(clip) + pad
1014
- : sel ? colors.primary.bold(clip) + pad
1015
- : isDir ? chalk.hex('#74b9ff')(clip) + pad
1016
- : colors.subtext(clip + pad);
1017
- boxLines.push(colors.dim(' │') + ` ${mark} ` + name + colors.dim('│'));
1018
- }
1019
- }
1020
- const hint = ' ↑↓ Navigate Enter Select Esc Close ';
1021
- const fInner = DW - 2 - hint.length;
994
+ for (const item of rowsData) {
995
+ const mark = item.selected ? colors.primary.bold('›') : ' ';
996
+ const rightStr = item.right ?? '';
997
+ const rightW = visWidth(rightStr);
998
+ const leftBudget = Math.max(innerRowW - 2 - (rightW > 0 ? rightW + 2 : 0), 8);
999
+ const leftClip = clipVis(stripAnsi(item.left), leftBudget);
1000
+ const leftPainted = item.selected
1001
+ ? colors.text.bold(leftClip)
1002
+ : item.isDir
1003
+ ? colors.info(leftClip)
1004
+ : colors.subtext(leftClip);
1005
+ const content = rightW > 0
1006
+ ? padVis(leftPainted, leftBudget) + ' ' + rightStr
1007
+ : padVis(leftPainted, innerRowW - 2);
1008
+ if (item.selected) {
1009
+ const hl = chalk.bgHex('#1e253b')(' ' + mark + ' ' + padVis(content, innerRowW - 2) + ' ');
1010
+ boxLines.push(' ' + BC('│') + hl + BC('│'));
1011
+ }
1012
+ else {
1013
+ boxLines.push(' ' + BC('│') + ' ' + mark + ' ' + padVis(content, innerRowW - 2) + ' ' + BC('│'));
1014
+ }
1015
+ }
1016
+ }
1017
+ const hintClip = clipVis(hintText, DW - 4);
1018
+ const fInner = DW - 2 - visWidth(hintClip);
1022
1019
  const fLeft = Math.max(0, Math.floor(fInner / 2));
1023
1020
  const fRight = Math.max(0, fInner - fLeft);
1024
- boxLines.push(colors.dim(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + colors.dim('─'.repeat(fRight) + '╯'));
1025
- const newLinesCount = boxLines.length;
1026
- // Clear any leftover lines from previous taller popup
1027
- if (atBoxLines > newLinesCount) {
1028
- for (let r = sR - atBoxLines; r < sR - newLinesCount; r++) {
1021
+ boxLines.push(' ' + BC('╰' + '─'.repeat(fLeft)) + colors.muted(hintClip) + BC('─'.repeat(fRight) + '╯'));
1022
+ const newCount = boxLines.length;
1023
+ if (prevCount > newCount) {
1024
+ for (let r = sR - prevCount; r < sR - newCount; r++) {
1029
1025
  if (r >= 1)
1030
1026
  process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1031
1027
  }
1032
1028
  }
1033
- // Render popup above separator
1034
- for (let i = 0; i < newLinesCount; i++) {
1035
- const targetRow = sR - newLinesCount + i;
1029
+ for (let i = 0; i < newCount; i++) {
1030
+ const targetRow = sR - newCount + i;
1036
1031
  if (targetRow >= 1) {
1037
1032
  process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
1038
1033
  }
1039
1034
  }
1040
- // Re-draw separator and input
1041
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
1042
- const inputLine = colors.primary(' › ') + colors.text(prefix) +
1043
- (pasteBlock !== null ? colors.muted(`[paste: ${pasteCount} lines]`) + colors.text(suffix) : '') +
1044
- colors.primary('@') + colors.text(atQuery);
1045
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
1046
- const cursorCol = 5 + prefix.length + (pasteBlock !== null ? `[paste: ${pasteCount} lines]`.length + suffix.length : 0) + 1 + atQuery.length;
1047
- process.stdout.write(`\x1b[${iR};${cursorCol}H`);
1048
- atBoxLines = newLinesCount;
1035
+ renderPlainInput(inputPreviewPlain, cursorCharIdx, inputPreviewStyled);
1036
+ return newCount;
1037
+ }
1038
+ function clearPopupRows(count) {
1039
+ const sR = layout.topBorderRow;
1040
+ for (let r = sR - count; r < sR; r++) {
1041
+ if (r >= 1)
1042
+ process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1043
+ }
1044
+ }
1045
+ function drawPicker() {
1046
+ const filtered = filterFiles(atQuery);
1047
+ if (atSel >= filtered.length && filtered.length > 0)
1048
+ atSel = filtered.length - 1;
1049
+ if (atSel < 0)
1050
+ atSel = 0;
1051
+ const maxVisible = Math.min(8, Math.max(3, layout.scrollEnd - 3));
1052
+ const shown = filtered.slice(0, maxVisible);
1053
+ const preStr = pasteBlock !== null
1054
+ ? chars.join('') + `[paste: ${pasteCount} line${pasteCount === 1 ? '' : 's'}]` + suffixChars.join('')
1055
+ : chars.join('');
1056
+ const previewPlain = preStr + '@' + atQuery;
1057
+ const previewStyled = colors.text(preStr) + colors.primary.bold('@') + colors.text(atQuery);
1058
+ atBoxLines = drawPopupBox(atQuery ? `@${atQuery}` : 'attach file', colors.primary.bold, shown.map((f, i) => ({
1059
+ left: f,
1060
+ right: f.endsWith('/') ? colors.muted('dir') : undefined,
1061
+ selected: i === atSel,
1062
+ isDir: f.endsWith('/'),
1063
+ })), 'no matching files', ' ↑↓ navigate · Enter/Space select · → open dir · Esc close ', atBoxLines, previewPlain, previewStyled, previewPlain.length);
1049
1064
  atDrawn = true;
1050
1065
  }
1051
1066
  function closePicker() {
1052
- const rows = process.stdout.rows ?? 24;
1053
- const sR = rows - 2;
1054
- if (atDrawn && atBoxLines > 0) {
1055
- for (let r = sR - atBoxLines; r < sR; r++) {
1056
- if (r >= 1)
1057
- process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1058
- }
1059
- }
1067
+ if (atDrawn && atBoxLines > 0)
1068
+ clearPopupRows(atBoxLines);
1060
1069
  atBoxLines = 0;
1061
1070
  atMode = false;
1062
1071
  atQuery = '';
@@ -1064,79 +1073,24 @@ async function readLine(prompt, cwd) {
1064
1073
  atDrawn = false;
1065
1074
  }
1066
1075
  function drawSlashPicker() {
1067
- const cols = process.stdout.columns ?? 80;
1068
- const rows = process.stdout.rows ?? 24;
1069
- const sR = rows - 2;
1070
- const iR = rows - 1;
1071
1076
  const filtered = filterSlash(slashQuery);
1072
1077
  if (slashSel >= filtered.length && filtered.length > 0)
1073
1078
  slashSel = filtered.length - 1;
1074
1079
  if (slashSel < 0)
1075
1080
  slashSel = 0;
1076
- const maxVisible = Math.min(8, Math.max(3, rows - 6));
1081
+ const maxVisible = Math.min(8, Math.max(3, layout.scrollEnd - 3));
1077
1082
  const shown = filtered.slice(0, maxVisible);
1078
- const DW = Math.min(Math.max(cols - 6, 44), 74);
1079
- const nameW = 11;
1080
- const descW = Math.max(DW - nameW - 9, 10);
1081
- const boxLines = [];
1082
- const qLabel = slashQuery ? `/${slashQuery}` : 'commands';
1083
- const hDashes = Math.max(DW - 4 - qLabel.length, 1);
1084
- boxLines.push(colors.dim(' ╭─ ') + colors.primary(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
1085
- if (filtered.length === 0) {
1086
- const msg = 'no matching commands';
1087
- const pad = ' '.repeat(Math.max(DW - 4 - msg.length - 2, 0));
1088
- boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
1089
- }
1090
- else {
1091
- for (let i = 0; i < shown.length; i++) {
1092
- const cmd = shown[i];
1093
- const sel = i === slashSel;
1094
- const mark = sel ? colors.primary('›') : ' ';
1095
- const nameStr = cmd.name.padEnd(nameW);
1096
- const descStr = cmd.desc.length > descW ? cmd.desc.slice(0, descW - 1) + '…' : cmd.desc;
1097
- const descPad = ' '.repeat(Math.max(descW - descStr.length, 0));
1098
- const namePaint = sel ? colors.primary.bold(nameStr) : colors.primary(nameStr);
1099
- const descPaint = sel ? chalk.hex('#f1f5f9')(descStr) : colors.subtext(descStr);
1100
- boxLines.push(colors.dim(' │') + ` ${mark} ` + namePaint + ' ' + descPaint + descPad + colors.dim('│'));
1101
- }
1102
- }
1103
- const hint = ' ↑↓ Navigate Tab Complete ↵ Run Esc Close ';
1104
- const fInner = DW - 2 - hint.length;
1105
- const fLeft = Math.max(0, Math.floor(fInner / 2));
1106
- const fRight = Math.max(0, fInner - fLeft);
1107
- boxLines.push(colors.dim(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + colors.dim('─'.repeat(fRight) + '╯'));
1108
- const newLinesCount = boxLines.length;
1109
- // Clear any leftover lines from previous taller popup
1110
- if (slashBoxLines > newLinesCount) {
1111
- for (let r = sR - slashBoxLines; r < sR - newLinesCount; r++) {
1112
- if (r >= 1)
1113
- process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1114
- }
1115
- }
1116
- // Render popup above separator
1117
- for (let i = 0; i < newLinesCount; i++) {
1118
- const targetRow = sR - newLinesCount + i;
1119
- if (targetRow >= 1) {
1120
- process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
1121
- }
1122
- }
1123
- // Re-draw separator and input line
1124
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
1125
- const inputLine = colors.primary(' › ') + colors.primary('/') + colors.text(slashQuery);
1126
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
1127
- process.stdout.write(`\x1b[${iR};${5 + 1 + slashQuery.length}H`);
1128
- slashBoxLines = newLinesCount;
1083
+ const previewPlain = '/' + slashQuery;
1084
+ const previewStyled = colors.primary.bold('/') + colors.text(slashQuery);
1085
+ slashBoxLines = drawPopupBox(slashQuery ? `/${slashQuery}` : 'commands', colors.primary.bold, shown.map((c, i) => ({
1086
+ left: c.name.padEnd(10) + c.desc,
1087
+ selected: i === slashSel,
1088
+ })), 'no matching commands', ' ↑↓ navigate · Tab complete · Enter run · Esc close ', slashBoxLines, previewPlain, previewStyled, previewPlain.length);
1129
1089
  slashDrawn = true;
1130
1090
  }
1131
1091
  function closeSlashPicker() {
1132
- const rows = process.stdout.rows ?? 24;
1133
- const sR = rows - 2;
1134
- if (slashDrawn && slashBoxLines > 0) {
1135
- for (let r = sR - slashBoxLines; r < sR; r++) {
1136
- if (r >= 1)
1137
- process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1138
- }
1139
- }
1092
+ if (slashDrawn && slashBoxLines > 0)
1093
+ clearPopupRows(slashBoxLines);
1140
1094
  slashBoxLines = 0;
1141
1095
  slashMode = false;
1142
1096
  slashQuery = '';
@@ -1144,81 +1098,26 @@ async function readLine(prompt, cwd) {
1144
1098
  slashDrawn = false;
1145
1099
  }
1146
1100
  function drawTabPicker() {
1147
- const cols = process.stdout.columns ?? 80;
1148
- const rows = process.stdout.rows ?? 24;
1149
- const sR = rows - 2;
1150
- const iR = rows - 1;
1151
- const TC = colors.success;
1152
- const DW = Math.min(Math.max(cols - 6, 44), 74);
1153
- const IW = DW - 6;
1154
1101
  const filtered = filterFiles(tabQuery);
1155
1102
  if (tabSel >= filtered.length && filtered.length > 0)
1156
1103
  tabSel = filtered.length - 1;
1157
1104
  if (tabSel < 0)
1158
1105
  tabSel = 0;
1159
- const maxVisible = Math.min(8, Math.max(3, rows - 6));
1106
+ const maxVisible = Math.min(8, Math.max(3, layout.scrollEnd - 3));
1160
1107
  const shown = filtered.slice(0, maxVisible);
1161
- const boxLines = [];
1162
- const qLabel = tabQuery || 'tab complete';
1163
- const hDashes = Math.max(DW - 4 - qLabel.length, 1);
1164
- boxLines.push(colors.dim(' ╭─ ') + TC(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
1165
- if (shown.length === 0) {
1166
- const msg = 'no matches';
1167
- const pad = ' '.repeat(Math.max(IW - msg.length, 0));
1168
- boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
1169
- }
1170
- else {
1171
- for (let i = 0; i < shown.length; i++) {
1172
- const f = shown[i];
1173
- const isDir = f.endsWith('/');
1174
- const sel = i === tabSel;
1175
- const mark = sel ? TC('›') : ' ';
1176
- const clip = f.length > IW ? f.slice(0, IW - 1) + '…' : f;
1177
- const pad = ' '.repeat(Math.max(IW - clip.length, 0));
1178
- const name = sel ? TC.bold(clip) + pad
1179
- : isDir ? chalk.hex('#74b9ff')(clip) + pad
1180
- : colors.subtext(clip + pad);
1181
- boxLines.push(colors.dim(' │') + ` ${mark} ` + name + colors.dim('│'));
1182
- }
1183
- }
1184
- const hint = ' Tab/↑↓ Navigate Enter Select Esc Close ';
1185
- const fInner = DW - 2 - hint.length;
1186
- const fLeft = Math.floor(fInner / 2);
1187
- const fRight = fInner - fLeft;
1188
- boxLines.push(colors.dim(' ╰' + '─'.repeat(Math.max(fLeft, 0))) + colors.muted(hint) + colors.dim('─'.repeat(Math.max(fRight, 0)) + '╯'));
1189
- const newLinesCount = boxLines.length;
1190
- // Clear any leftover lines from previous taller popup
1191
- if (tabBoxLines > newLinesCount) {
1192
- for (let r = sR - tabBoxLines; r < sR - newLinesCount; r++) {
1193
- if (r >= 1)
1194
- process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1195
- }
1196
- }
1197
- // Render popup above separator
1198
- for (let i = 0; i < newLinesCount; i++) {
1199
- const targetRow = sR - newLinesCount + i;
1200
- if (targetRow >= 1) {
1201
- process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
1202
- }
1203
- }
1204
- // Re-draw separator and input line
1205
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
1206
- const inputLine = colors.primary(' › ') + colors.text(tabPreWord) + TC(tabQuery);
1207
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
1208
- const cursorCol = 5 + tabPreWord.length + tabQuery.length;
1209
- process.stdout.write(`\x1b[${iR};${cursorCol}H`);
1210
- tabBoxLines = newLinesCount;
1108
+ const previewPlain = tabPreWord + tabQuery;
1109
+ const previewStyled = colors.text(tabPreWord) + colors.success(tabQuery);
1110
+ tabBoxLines = drawPopupBox(tabQuery || 'path complete', colors.success.bold, shown.map((f, i) => ({
1111
+ left: f,
1112
+ right: f.endsWith('/') ? colors.muted('dir') : undefined,
1113
+ selected: i === tabSel,
1114
+ isDir: f.endsWith('/'),
1115
+ })), 'no matches', ' Tab/↑↓ navigate · Enter select · Esc close ', tabBoxLines, previewPlain, previewStyled, previewPlain.length);
1211
1116
  tabDrawn = true;
1212
1117
  }
1213
1118
  function closeTabPicker() {
1214
- const rows = process.stdout.rows ?? 24;
1215
- const sR = rows - 2;
1216
- if (tabDrawn && tabBoxLines > 0) {
1217
- for (let r = sR - tabBoxLines; r < sR; r++) {
1218
- if (r >= 1)
1219
- process.stdout.write(`\x1b[${r};1H\x1b[2K`);
1220
- }
1221
- }
1119
+ if (tabDrawn && tabBoxLines > 0)
1120
+ clearPopupRows(tabBoxLines);
1222
1121
  tabBoxLines = 0;
1223
1122
  tabMode = false;
1224
1123
  tabQuery = '';
@@ -1226,99 +1125,206 @@ async function readLine(prompt, cwd) {
1226
1125
  tabPreWord = '';
1227
1126
  tabDrawn = false;
1228
1127
  }
1229
- function redraw() {
1230
- const cols = process.stdout.columns ?? 80;
1231
- const rows = process.stdout.rows ?? 24;
1232
- const sR = rows - 2;
1233
- const iR = rows - 1;
1234
- const maxLen = Math.max(cols - 8, 10);
1235
- let displayPre = prefix;
1236
- if (displayPre.length > maxLen)
1237
- displayPre = '…' + displayPre.slice(-(maxLen - 1));
1238
- let inp;
1239
- let cursorCol = 5 + displayPre.length;
1240
- if (pasteBlock !== null) {
1241
- const pTag = `[paste: ${pasteCount} lines]`;
1242
- inp = colors.primary(' › ') + colors.text(displayPre) +
1243
- colors.muted(pTag) + colors.text(suffix);
1244
- cursorCol = 5 + displayPre.length + pTag.length + suffix.length;
1245
- }
1246
- else {
1247
- inp = colors.primary(' › ') + colors.text(displayPre) + colors.text(suffix);
1248
- cursorCol = 5 + displayPre.length;
1128
+ function onResize() {
1129
+ layout.resize({ focused: true, cwd, meta, focusCursor: true });
1130
+ if (atMode)
1131
+ drawPicker();
1132
+ else if (slashMode)
1133
+ drawSlashPicker();
1134
+ else if (tabMode)
1135
+ drawTabPicker();
1136
+ else
1137
+ redraw();
1138
+ }
1139
+ process.stdout.on('resize', onResize);
1140
+ function cleanup() {
1141
+ if (ctrlCTimer) {
1142
+ clearTimeout(ctrlCTimer);
1143
+ ctrlCTimer = null;
1249
1144
  }
1250
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
1251
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${inp}`);
1252
- process.stdout.write(`\x1b[${iR};${cursorCol}H`);
1145
+ process.stdin.removeListener('data', onData);
1146
+ process.stdout.removeListener('resize', onResize);
1253
1147
  }
1148
+ // Initial render
1149
+ redraw();
1150
+ let submitted = false;
1254
1151
  function submit() {
1152
+ if (submitted)
1153
+ return;
1255
1154
  if (atMode)
1256
1155
  closePicker();
1257
1156
  if (slashMode)
1258
1157
  closeSlashPicker();
1259
1158
  if (tabMode) {
1260
- prefix = tabPreWord + tabQuery;
1159
+ const s = tabPreWord + tabQuery;
1160
+ chars = [...s];
1161
+ cursor = chars.length;
1261
1162
  closeTabPicker();
1262
1163
  }
1164
+ const preStr = chars.join('');
1165
+ const sufStr = suffixChars.join('');
1263
1166
  const parts = [];
1264
- if (prefix.trim())
1265
- parts.push(prefix.trim());
1167
+ if (preStr.trim())
1168
+ parts.push(preStr.trim());
1266
1169
  if (pasteBlock)
1267
1170
  parts.push(...pasteBlock.split('\n').filter(Boolean));
1268
- if (suffix.trim())
1269
- parts.push(suffix.trim());
1171
+ if (sufStr.trim())
1172
+ parts.push(sufStr.trim());
1270
1173
  const text = parts.join('\n');
1271
1174
  const lns = parts.length > 0 ? parts : (text ? [text] : []);
1175
+ submitted = true;
1272
1176
  cleanup();
1273
- const rows = process.stdout.rows ?? 24;
1274
- const cols = process.stdout.columns ?? 80;
1275
- const sR = rows - 2;
1276
- const iR = rows - 1;
1277
- const scrBottom = rows - 3;
1278
- // Clear fixed bottom input line
1279
- process.stdout.write(`\x1b[${iR};1H\x1b[2K`);
1280
1177
  if (!text) {
1281
- process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
1282
- process.stdout.write(`\x1b[${iR};1H\x1b[2K${prompt}`);
1283
- process.stdout.write(`\x1b[${iR};5H`);
1284
1178
  resolve(null);
1285
1179
  return;
1286
1180
  }
1287
- const msgBg = chalk.bgHex('#334155').hex('#f1f5f9');
1288
- const fillMsg = (raw) => (' > ' + raw + ' ').padEnd(cols);
1289
- // Move to bottom of scroll region to append user message into chat
1290
- process.stdout.write(`\x1b[${scrBottom};1H\n`);
1181
+ // Record in prompt history (deduplicated at head)
1182
+ if (inputHistory[0] !== text) {
1183
+ inputHistory.unshift(text);
1184
+ if (inputHistory.length > 50)
1185
+ inputHistory.pop();
1186
+ }
1187
+ // Put composer in streaming/busy state cleanly while AI works
1188
+ layout.drawComposer({
1189
+ focused: false,
1190
+ streaming: true,
1191
+ placeholder: 'Processing...',
1192
+ cwd,
1193
+ meta,
1194
+ focusCursor: false,
1195
+ });
1196
+ // Print user message card inside chat scroll region
1197
+ layout.enterChat();
1198
+ const dispHint = pasteBlock !== null
1199
+ ? [preStr.trim(), `[pasted ${pasteCount} line${pasteCount === 1 ? '' : 's'}]`, sufStr.trim()].filter(Boolean).join(' ')
1200
+ : undefined;
1201
+ renderUserMessage(text, layout.cols, dispHint);
1202
+ resolve({ text, lines: lns });
1203
+ }
1204
+ function insertAtCursor(str) {
1205
+ const ins = [...str];
1291
1206
  if (pasteBlock !== null) {
1292
- const disp = [
1293
- prefix ? prefix : '',
1294
- `[${pasteCount} lines]`,
1295
- suffix.trim() ? suffix.trim() : '',
1296
- ].filter(Boolean).join(' ');
1297
- process.stdout.write(msgBg(fillMsg(disp)) + '\n');
1207
+ suffixChars.splice(suffixCursor, 0, ...ins);
1208
+ suffixCursor += ins.length;
1298
1209
  }
1299
1210
  else {
1300
- process.stdout.write(msgBg(fillMsg(text)) + '\n');
1211
+ chars.splice(cursor, 0, ...ins);
1212
+ cursor += ins.length;
1213
+ }
1214
+ }
1215
+ function tokenizeKeys(chunk) {
1216
+ const tokens = [];
1217
+ let i = 0;
1218
+ while (i < chunk.length) {
1219
+ if (chunk[i] === '\x1b') {
1220
+ const m = chunk.slice(i).match(/^\x1b(?:\[[0-9;?]*[A-Za-z~]|O[A-Za-z]|.)/);
1221
+ if (m) {
1222
+ tokens.push(m[0]);
1223
+ i += m[0].length;
1224
+ continue;
1225
+ }
1226
+ tokens.push('\x1b');
1227
+ i++;
1228
+ continue;
1229
+ }
1230
+ const cp = chunk.codePointAt(i) ?? 0;
1231
+ if (cp < 32 || cp === 127) {
1232
+ tokens.push(chunk[i]);
1233
+ i++;
1234
+ continue;
1235
+ }
1236
+ let j = i;
1237
+ while (j < chunk.length) {
1238
+ const c = chunk.codePointAt(j) ?? 0;
1239
+ if (c < 32 || c === 127)
1240
+ break;
1241
+ j += c > 0xffff ? 2 : 1;
1242
+ }
1243
+ tokens.push(chunk.slice(i, j));
1244
+ i = j;
1301
1245
  }
1302
- process.stdout.write(`\x1b[${scrBottom};1H`);
1303
- resolve({ text, lines: lns });
1246
+ return tokens;
1304
1247
  }
1305
- function onData(data) {
1248
+ function onData(rawChunk) {
1306
1249
  try {
1307
- if (data === '\x03') {
1308
- // Close any active picker first
1250
+ if (submitted)
1251
+ return;
1252
+ const isBracketed = rawChunk.includes('\x1b[200~');
1253
+ const cleaned = rawChunk.replace(/\x1b\[200~/g, '').replace(/\x1b\[201~/g, '');
1254
+ if (!cleaned)
1255
+ return;
1256
+ // Real multi-line paste: bracketed paste containing \n, OR unbracketed chunk with internal \n between lines
1257
+ const normPaste = cleaned.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
1258
+ const hasInternalNewline = normPaste.replace(/\n+$/, '').includes('\n');
1259
+ if ((isBracketed && normPaste.includes('\n')) || (!isBracketed && hasInternalNewline && !cleaned.includes('\x1b'))) {
1309
1260
  if (atMode)
1310
1261
  closePicker();
1311
1262
  if (slashMode)
1312
1263
  closeSlashPicker();
1313
1264
  if (tabMode)
1314
1265
  closeTabPicker();
1315
- // If there is typed input — clear it (safe copy behavior, like bash)
1316
- if (prefix || pasteBlock !== null || suffix) {
1317
- prefix = '';
1266
+ if (suffixChars.length > 0) {
1267
+ chars.push(...suffixChars);
1268
+ suffixChars = [];
1269
+ suffixCursor = 0;
1270
+ }
1271
+ const pasted = normPaste.replace(/\n$/, '');
1272
+ pasteBlock = pasteBlock ? pasteBlock + '\n' + pasted : pasted;
1273
+ pasteCount = pasteBlock.split('\n').filter(l => l.length > 0).length || 1;
1274
+ redraw();
1275
+ return;
1276
+ }
1277
+ if (isBracketed) {
1278
+ const printable = [...cleaned].filter(c => (c.codePointAt(0) ?? 0) >= 32).join('');
1279
+ if (printable) {
1280
+ insertAtCursor(printable);
1281
+ redraw();
1282
+ }
1283
+ return;
1284
+ }
1285
+ for (const tok of tokenizeKeys(cleaned)) {
1286
+ if (submitted)
1287
+ break;
1288
+ handleKey(tok);
1289
+ }
1290
+ }
1291
+ catch {
1292
+ cleanup();
1293
+ resolve(null);
1294
+ }
1295
+ }
1296
+ function handleKey(data) {
1297
+ try {
1298
+ // Ignore delayed DSR cursor-position reports (\x1b[row;colR)
1299
+ if (/^\x1b\[\d+;\d+R$/.test(data))
1300
+ return;
1301
+ if (data === '\x03') {
1302
+ if (atMode) {
1303
+ closePicker();
1304
+ redraw();
1305
+ return;
1306
+ }
1307
+ if (slashMode) {
1308
+ closeSlashPicker();
1309
+ redraw();
1310
+ return;
1311
+ }
1312
+ if (tabMode) {
1313
+ closeTabPicker();
1314
+ redraw();
1315
+ return;
1316
+ }
1317
+ if (chars.length > 0 || pasteBlock !== null || suffixChars.length > 0) {
1318
+ chars = [];
1319
+ cursor = 0;
1318
1320
  pasteBlock = null;
1319
1321
  pasteCount = 0;
1320
- suffix = '';
1322
+ suffixChars = [];
1323
+ suffixCursor = 0;
1324
+ histIdx = -1;
1325
+ savedDraft = '';
1321
1326
  ctrlCCount = 0;
1327
+ statusNotice = '';
1322
1328
  if (ctrlCTimer) {
1323
1329
  clearTimeout(ctrlCTimer);
1324
1330
  ctrlCTimer = null;
@@ -1326,21 +1332,27 @@ async function readLine(prompt, cwd) {
1326
1332
  redraw();
1327
1333
  return;
1328
1334
  }
1329
- // No input: require double Ctrl+C to exit (prevents accidental exit from copy)
1330
1335
  ctrlCCount++;
1331
1336
  if (ctrlCTimer)
1332
1337
  clearTimeout(ctrlCTimer);
1333
1338
  if (ctrlCCount >= 2) {
1334
1339
  cleanup();
1335
- process.stdout.write('\n\n ' + colors.muted('Goodbye!') + '\n\n');
1340
+ layout.cleanup(true);
1341
+ process.stdout.write('\n ' + colors.muted('Goodbye!') + '\n\n');
1336
1342
  process.exit(0);
1337
1343
  }
1338
- process.stdout.write('\r\x1b[K ' + colors.muted('(Ctrl+C again to exit — use /exit or close window)'));
1339
- ctrlCTimer = setTimeout(() => { ctrlCCount = 0; redraw(); }, 1500);
1344
+ statusNotice = 'Press Ctrl+C again to exit · or type /exit';
1345
+ redraw();
1346
+ ctrlCTimer = setTimeout(() => {
1347
+ ctrlCCount = 0;
1348
+ statusNotice = '';
1349
+ redraw();
1350
+ }, 1800);
1340
1351
  return;
1341
1352
  }
1342
1353
  if (ctrlCCount > 0) {
1343
1354
  ctrlCCount = 0;
1355
+ statusNotice = '';
1344
1356
  if (ctrlCTimer) {
1345
1357
  clearTimeout(ctrlCTimer);
1346
1358
  ctrlCTimer = null;
@@ -1351,7 +1363,7 @@ async function readLine(prompt, cwd) {
1351
1363
  resolve(null);
1352
1364
  return;
1353
1365
  }
1354
- // Ctrl+L — clear screen, redraw input
1366
+ // Ctrl+L — clear chat scroll region while keeping composer + typed text intact
1355
1367
  if (data === '\x0c') {
1356
1368
  if (atMode)
1357
1369
  closePicker();
@@ -1359,24 +1371,20 @@ async function readLine(prompt, cwd) {
1359
1371
  closeSlashPicker();
1360
1372
  if (tabMode)
1361
1373
  closeTabPicker();
1362
- const curRows = process.stdout.rows ?? 24;
1363
- const curSR = curRows - 2;
1364
- const curIR = curRows - 1;
1365
- console.clear();
1366
- process.stdout.write(`\x1b[1;${curRows - 3}r`);
1367
- process.stdout.write(`\x1b[${curSR};1H\x1b[2K${SEP}`);
1368
- process.stdout.write(`\x1b[${curIR};1H\x1b[2K${prompt}`);
1369
- process.stdout.write(`\x1b[${curIR};5H`);
1374
+ layout.clearChat({ cwd, meta });
1375
+ renderCompactHeader(cwd, meta);
1376
+ layout.chatRow = Math.min(4, layout.scrollEnd);
1377
+ redraw();
1370
1378
  return;
1371
1379
  }
1372
- // ── @ picker mode ─────────────────────────────────────────
1380
+ // ── @ picker mode ───────────────────────────────────────
1373
1381
  if (atMode) {
1374
- if (data === '\x1b') { // Escape → cancel
1382
+ if (data === '\x1b') {
1375
1383
  closePicker();
1376
1384
  redraw();
1377
1385
  return;
1378
1386
  }
1379
- if (data === '\x1b[A') { // Arrow up
1387
+ if (data === '\x1b[A') {
1380
1388
  const f = filterFiles(atQuery);
1381
1389
  if (f.length) {
1382
1390
  atSel = (atSel - 1 + f.length) % f.length;
@@ -1384,7 +1392,7 @@ async function readLine(prompt, cwd) {
1384
1392
  }
1385
1393
  return;
1386
1394
  }
1387
- if (data === '\x1b[B') { // Arrow down
1395
+ if (data === '\x1b[B') {
1388
1396
  const f = filterFiles(atQuery);
1389
1397
  if (f.length) {
1390
1398
  atSel = (atSel + 1) % f.length;
@@ -1392,7 +1400,7 @@ async function readLine(prompt, cwd) {
1392
1400
  }
1393
1401
  return;
1394
1402
  }
1395
- if (data === '\x1b[C') { // Arrow right → enter folder
1403
+ if (data === '\x1b[C') {
1396
1404
  const f = filterFiles(atQuery);
1397
1405
  if (f.length > 0) {
1398
1406
  const file = f[Math.min(atSel, f.length - 1)];
@@ -1404,7 +1412,7 @@ async function readLine(prompt, cwd) {
1404
1412
  }
1405
1413
  return;
1406
1414
  }
1407
- if (data === '\x1b[D') { // Arrow left → go up one level
1415
+ if (data === '\x1b[D') {
1408
1416
  const noTrail = atQuery.endsWith('/') ? atQuery.slice(0, -1) : atQuery;
1409
1417
  const lastSlash = noTrail.lastIndexOf('/');
1410
1418
  atQuery = lastSlash >= 0 ? noTrail.slice(0, lastSlash + 1) : '';
@@ -1412,7 +1420,7 @@ async function readLine(prompt, cwd) {
1412
1420
  drawPicker();
1413
1421
  return;
1414
1422
  }
1415
- if (data === '\r' || data === '\n' || data === '\t') { // Enter/Tab → drill into folder or insert file
1423
+ if (data === '\r' || data === '\n' || data === '\t') {
1416
1424
  const filtered = filterFiles(atQuery);
1417
1425
  if (filtered.length > 0) {
1418
1426
  const file = filtered[Math.min(atSel, filtered.length - 1)];
@@ -1422,12 +1430,9 @@ async function readLine(prompt, cwd) {
1422
1430
  drawPicker();
1423
1431
  }
1424
1432
  else {
1425
- const mention = '@' + file;
1433
+ const mention = '@' + file + ' ';
1426
1434
  closePicker();
1427
- if (pasteBlock !== null)
1428
- suffix += mention;
1429
- else
1430
- prefix += mention;
1435
+ insertAtCursor(mention);
1431
1436
  redraw();
1432
1437
  }
1433
1438
  }
@@ -1437,16 +1442,12 @@ async function readLine(prompt, cwd) {
1437
1442
  }
1438
1443
  return;
1439
1444
  }
1440
- if (data === ' ') { // Space → select current item (file or folder)
1445
+ if (data === ' ') {
1441
1446
  const filtered = filterFiles(atQuery);
1442
1447
  if (filtered.length > 0) {
1443
1448
  const file = filtered[Math.min(atSel, filtered.length - 1)];
1444
- const mention = '@' + file;
1445
1449
  closePicker();
1446
- if (pasteBlock !== null)
1447
- suffix += mention;
1448
- else
1449
- prefix += mention;
1450
+ insertAtCursor('@' + file + ' ');
1450
1451
  redraw();
1451
1452
  }
1452
1453
  else {
@@ -1455,9 +1456,11 @@ async function readLine(prompt, cwd) {
1455
1456
  }
1456
1457
  return;
1457
1458
  }
1458
- if (data === '\x7f' || data === '\b') { // Backspace
1459
- if (atQuery.length > 0) {
1460
- atQuery = atQuery.slice(0, -1);
1459
+ if (data === '\x7f' || data === '\b') {
1460
+ const qChars = [...atQuery];
1461
+ if (qChars.length > 0) {
1462
+ qChars.pop();
1463
+ atQuery = qChars.join('');
1461
1464
  atSel = 0;
1462
1465
  drawPicker();
1463
1466
  }
@@ -1467,7 +1470,7 @@ async function readLine(prompt, cwd) {
1467
1470
  }
1468
1471
  return;
1469
1472
  }
1470
- if (data.length === 1 && data >= ' ') { // type to filter
1473
+ if (!data.startsWith('\x1b') && data >= ' ') {
1471
1474
  atQuery += data;
1472
1475
  atSel = 0;
1473
1476
  drawPicker();
@@ -1475,7 +1478,7 @@ async function readLine(prompt, cwd) {
1475
1478
  }
1476
1479
  return;
1477
1480
  }
1478
- // ── / slash picker mode ───────────────────────────────────
1481
+ // ── / slash picker mode ─────────────────────────────────
1479
1482
  if (slashMode) {
1480
1483
  if (data === '\x1b') {
1481
1484
  closeSlashPicker();
@@ -1500,36 +1503,31 @@ async function readLine(prompt, cwd) {
1500
1503
  }
1501
1504
  if (data === '\r' || data === '\n') {
1502
1505
  const filtered = filterSlash(slashQuery);
1503
- if (filtered.length > 0) {
1504
- const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
1505
- prefix = cmd.name;
1506
- closeSlashPicker();
1507
- submit();
1508
- }
1509
- else {
1510
- prefix = '/' + slashQuery;
1511
- closeSlashPicker();
1512
- submit();
1513
- }
1506
+ const val = filtered.length > 0
1507
+ ? filtered[Math.min(slashSel, filtered.length - 1)].name
1508
+ : '/' + slashQuery;
1509
+ chars = [...val];
1510
+ cursor = chars.length;
1511
+ closeSlashPicker();
1512
+ submit();
1514
1513
  return;
1515
1514
  }
1516
- if (data === '\t') {
1515
+ if (data === '\t' || data === ' ') {
1517
1516
  const filtered = filterSlash(slashQuery);
1518
- if (filtered.length > 0) {
1519
- const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
1520
- prefix = cmd.name + ' ';
1521
- closeSlashPicker();
1522
- redraw();
1523
- }
1524
- else {
1525
- closeSlashPicker();
1526
- redraw();
1527
- }
1517
+ const val = filtered.length > 0
1518
+ ? filtered[Math.min(slashSel, filtered.length - 1)].name + ' '
1519
+ : '/' + slashQuery + ' ';
1520
+ chars = [...val];
1521
+ cursor = chars.length;
1522
+ closeSlashPicker();
1523
+ redraw();
1528
1524
  return;
1529
1525
  }
1530
1526
  if (data === '\x7f' || data === '\b') {
1531
- if (slashQuery.length > 0) {
1532
- slashQuery = slashQuery.slice(0, -1);
1527
+ const qChars = [...slashQuery];
1528
+ if (qChars.length > 0) {
1529
+ qChars.pop();
1530
+ slashQuery = qChars.join('');
1533
1531
  slashSel = 0;
1534
1532
  drawSlashPicker();
1535
1533
  }
@@ -1539,20 +1537,7 @@ async function readLine(prompt, cwd) {
1539
1537
  }
1540
1538
  return;
1541
1539
  }
1542
- if (data === ' ') {
1543
- const filtered = filterSlash(slashQuery);
1544
- if (filtered.length > 0) {
1545
- const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
1546
- prefix = cmd.name + ' ';
1547
- }
1548
- else {
1549
- prefix = '/' + slashQuery + ' ';
1550
- }
1551
- closeSlashPicker();
1552
- redraw();
1553
- return;
1554
- }
1555
- if (data.length === 1 && data >= ' ') {
1540
+ if (!data.startsWith('\x1b') && data >= ' ') {
1556
1541
  slashQuery += data;
1557
1542
  slashSel = 0;
1558
1543
  drawSlashPicker();
@@ -1560,16 +1545,17 @@ async function readLine(prompt, cwd) {
1560
1545
  }
1561
1546
  return;
1562
1547
  }
1563
- // ── Tab path-autocomplete mode ────────────────────────────
1548
+ // ── Tab path-autocomplete mode ──────────────────────────
1564
1549
  if (tabMode) {
1565
- if (data === '\x1b') { // Escape → cancel, restore text
1550
+ if (data === '\x1b') {
1566
1551
  const saved = tabPreWord + tabQuery;
1567
1552
  closeTabPicker();
1568
- prefix = saved;
1553
+ chars = [...saved];
1554
+ cursor = chars.length;
1569
1555
  redraw();
1570
1556
  return;
1571
1557
  }
1572
- if (data === '\x1b[A') { // Arrow up
1558
+ if (data === '\x1b[A') {
1573
1559
  const f = filterFiles(tabQuery);
1574
1560
  if (f.length) {
1575
1561
  tabSel = (tabSel - 1 + f.length) % f.length;
@@ -1577,7 +1563,7 @@ async function readLine(prompt, cwd) {
1577
1563
  }
1578
1564
  return;
1579
1565
  }
1580
- if (data === '\x1b[B' || data === '\t') { // Arrow down / Tab → next
1566
+ if (data === '\x1b[B' || data === '\t') {
1581
1567
  const f = filterFiles(tabQuery);
1582
1568
  if (f.length) {
1583
1569
  tabSel = (tabSel + 1) % f.length;
@@ -1585,7 +1571,7 @@ async function readLine(prompt, cwd) {
1585
1571
  }
1586
1572
  return;
1587
1573
  }
1588
- if (data === '\x1b[C') { // Arrow right → enter folder
1574
+ if (data === '\x1b[C') {
1589
1575
  const f = filterFiles(tabQuery);
1590
1576
  if (f.length > 0) {
1591
1577
  const file = f[Math.min(tabSel, f.length - 1)];
@@ -1597,7 +1583,7 @@ async function readLine(prompt, cwd) {
1597
1583
  }
1598
1584
  return;
1599
1585
  }
1600
- if (data === '\x1b[D') { // Arrow left → go up
1586
+ if (data === '\x1b[D') {
1601
1587
  const noTrail = tabQuery.endsWith('/') ? tabQuery.slice(0, -1) : tabQuery;
1602
1588
  const lastSlash = noTrail.lastIndexOf('/');
1603
1589
  tabQuery = lastSlash >= 0 ? noTrail.slice(0, lastSlash + 1) : '';
@@ -1605,7 +1591,7 @@ async function readLine(prompt, cwd) {
1605
1591
  drawTabPicker();
1606
1592
  return;
1607
1593
  }
1608
- if (data === '\r' || data === '\n') { // Enter → insert or drill
1594
+ if (data === '\r' || data === '\n') {
1609
1595
  const filtered = filterFiles(tabQuery);
1610
1596
  if (filtered.length > 0) {
1611
1597
  const file = filtered[Math.min(tabSel, filtered.length - 1)];
@@ -1615,32 +1601,39 @@ async function readLine(prompt, cwd) {
1615
1601
  drawTabPicker();
1616
1602
  }
1617
1603
  else {
1618
- prefix = tabPreWord + file;
1604
+ const s = tabPreWord + file;
1605
+ chars = [...s];
1606
+ cursor = chars.length;
1619
1607
  closeTabPicker();
1620
1608
  redraw();
1621
1609
  }
1622
1610
  }
1623
1611
  else {
1624
- prefix = tabPreWord + tabQuery;
1612
+ const s = tabPreWord + tabQuery;
1613
+ chars = [...s];
1614
+ cursor = chars.length;
1625
1615
  closeTabPicker();
1626
1616
  redraw();
1627
1617
  }
1628
1618
  return;
1629
1619
  }
1630
- if (data === '\x7f' || data === '\b') { // Backspace
1631
- if (tabQuery.length > 0) {
1632
- tabQuery = tabQuery.slice(0, -1);
1620
+ if (data === '\x7f' || data === '\b') {
1621
+ const qChars = [...tabQuery];
1622
+ if (qChars.length > 0) {
1623
+ qChars.pop();
1624
+ tabQuery = qChars.join('');
1633
1625
  tabSel = 0;
1634
1626
  drawTabPicker();
1635
1627
  }
1636
1628
  else {
1637
1629
  closeTabPicker();
1638
- prefix = tabPreWord;
1630
+ chars = [...tabPreWord];
1631
+ cursor = chars.length;
1639
1632
  redraw();
1640
1633
  }
1641
1634
  return;
1642
1635
  }
1643
- if (data.length === 1 && data >= ' ') { // Type to filter
1636
+ if (!data.startsWith('\x1b') && data >= ' ') {
1644
1637
  tabQuery += data;
1645
1638
  tabSel = 0;
1646
1639
  drawTabPicker();
@@ -1648,23 +1641,24 @@ async function readLine(prompt, cwd) {
1648
1641
  }
1649
1642
  return;
1650
1643
  }
1651
- // Enter
1644
+ // ── Enter → submit ──────────────────────────────────────
1652
1645
  if (data === '\r' || data === '\n' || data === '\r\n') {
1653
1646
  submit();
1654
1647
  return;
1655
1648
  }
1656
- // ── Tab trigger ───────────────────────────────────────────
1649
+ // ── Tab trigger ─────────────────────────────────────────
1657
1650
  if (data === '\t' && pasteBlock === null) {
1658
1651
  loadFiles();
1659
- const spaceIdx = prefix.lastIndexOf(' ');
1660
- tabPreWord = spaceIdx >= 0 ? prefix.slice(0, spaceIdx + 1) : '';
1661
- tabQuery = spaceIdx >= 0 ? prefix.slice(spaceIdx + 1) : prefix;
1652
+ const curStr = chars.join('');
1653
+ const spaceIdx = curStr.lastIndexOf(' ');
1654
+ tabPreWord = spaceIdx >= 0 ? curStr.slice(0, spaceIdx + 1) : '';
1655
+ tabQuery = spaceIdx >= 0 ? curStr.slice(spaceIdx + 1) : curStr;
1662
1656
  tabSel = 0;
1663
1657
  tabMode = true;
1664
1658
  drawTabPicker();
1665
1659
  return;
1666
1660
  }
1667
- // ── @ trigger ─────────────────────────────────────────────
1661
+ // ── @ trigger ───────────────────────────────────────────
1668
1662
  if (data === '@') {
1669
1663
  loadFiles();
1670
1664
  atMode = true;
@@ -1673,68 +1667,189 @@ async function readLine(prompt, cwd) {
1673
1667
  drawPicker();
1674
1668
  return;
1675
1669
  }
1676
- // ── / trigger ─────────────────────────────────────────────
1677
- if (data === '/' && prefix === '' && pasteBlock === null) {
1670
+ // ── / trigger (at empty input) ──────────────────────────
1671
+ if (data === '/' && chars.length === 0 && pasteBlock === null) {
1678
1672
  slashMode = true;
1679
1673
  slashQuery = '';
1680
1674
  slashSel = 0;
1681
1675
  drawSlashPicker();
1682
1676
  return;
1683
1677
  }
1684
- // ── Paste detection ───────────────────────────────────────
1685
- const normalized = data.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
1686
- if (normalized.includes('\n')) {
1687
- prefix += suffix;
1688
- suffix = '';
1689
- const pasted = normalized.replace(/\n$/, '');
1690
- pasteBlock = pasted;
1691
- pasteCount = pasted.split('\n').filter(l => l.length > 0).length || 1;
1678
+ // ── History navigation (↑ / ↓) ──────────────────────────
1679
+ if (data === '\x1b[A' && pasteBlock === null) {
1680
+ if (inputHistory.length === 0)
1681
+ return;
1682
+ if (histIdx === -1)
1683
+ savedDraft = chars.join('');
1684
+ if (histIdx + 1 < inputHistory.length) {
1685
+ histIdx++;
1686
+ chars = [...inputHistory[histIdx].replace(/\n/g, ' ')];
1687
+ cursor = chars.length;
1688
+ redraw();
1689
+ }
1690
+ return;
1691
+ }
1692
+ if (data === '\x1b[B' && pasteBlock === null) {
1693
+ if (histIdx === -1)
1694
+ return;
1695
+ histIdx--;
1696
+ const target = histIdx === -1 ? savedDraft : inputHistory[histIdx].replace(/\n/g, ' ');
1697
+ chars = [...target];
1698
+ cursor = chars.length;
1692
1699
  redraw();
1693
1700
  return;
1694
1701
  }
1695
- // Backspace
1702
+ // ── Cursor movement (← → Home End Ctrl+A/E/B/F Word) ────
1703
+ if (data === '\x1b[D' || data === '\x02') { // Left / Ctrl+B
1704
+ if (pasteBlock !== null) {
1705
+ if (suffixCursor > 0) {
1706
+ suffixCursor--;
1707
+ redraw();
1708
+ }
1709
+ }
1710
+ else if (cursor > 0) {
1711
+ cursor--;
1712
+ redraw();
1713
+ }
1714
+ return;
1715
+ }
1716
+ if (data === '\x1b[C' || data === '\x06') { // Right / Ctrl+F
1717
+ if (pasteBlock !== null) {
1718
+ if (suffixCursor < suffixChars.length) {
1719
+ suffixCursor++;
1720
+ redraw();
1721
+ }
1722
+ }
1723
+ else if (cursor < chars.length) {
1724
+ cursor++;
1725
+ redraw();
1726
+ }
1727
+ return;
1728
+ }
1729
+ if (data === '\x1b[H' || data === '\x1b[1~' || data === '\x1bOH' || data === '\x01') { // Home / Ctrl+A
1730
+ if (pasteBlock !== null) {
1731
+ suffixCursor = 0;
1732
+ }
1733
+ else {
1734
+ cursor = 0;
1735
+ }
1736
+ redraw();
1737
+ return;
1738
+ }
1739
+ if (data === '\x1b[F' || data === '\x1b[4~' || data === '\x1bOF' || data === '\x05') { // End / Ctrl+E
1740
+ if (pasteBlock !== null) {
1741
+ suffixCursor = suffixChars.length;
1742
+ }
1743
+ else {
1744
+ cursor = chars.length;
1745
+ }
1746
+ redraw();
1747
+ return;
1748
+ }
1749
+ if (data === '\x1b[1;5D' || data === '\x1b[5D' || data === '\x1bb') { // Ctrl+Left / Alt+B
1750
+ if (pasteBlock === null && cursor > 0) {
1751
+ let p = cursor - 1;
1752
+ while (p > 0 && chars[p] === ' ')
1753
+ p--;
1754
+ while (p > 0 && chars[p - 1] !== ' ')
1755
+ p--;
1756
+ cursor = p;
1757
+ redraw();
1758
+ }
1759
+ return;
1760
+ }
1761
+ if (data === '\x1b[1;5C' || data === '\x1b[5C' || data === '\x1bf') { // Ctrl+Right / Alt+F
1762
+ if (pasteBlock === null && cursor < chars.length) {
1763
+ let p = cursor;
1764
+ while (p < chars.length && chars[p] === ' ')
1765
+ p++;
1766
+ while (p < chars.length && chars[p] !== ' ')
1767
+ p++;
1768
+ cursor = p;
1769
+ redraw();
1770
+ }
1771
+ return;
1772
+ }
1773
+ // ── Editing (Backspace / Delete / Ctrl+W / Ctrl+U / Ctrl+K) ──
1696
1774
  if (data === '\x7f' || data === '\b') {
1697
- if (suffix.length > 0) {
1698
- suffix = suffix.slice(0, -1);
1699
- process.stdout.write('\b \b');
1775
+ if (pasteBlock !== null) {
1776
+ if (suffixCursor > 0) {
1777
+ suffixChars.splice(suffixCursor - 1, 1);
1778
+ suffixCursor--;
1779
+ redraw();
1780
+ }
1781
+ else {
1782
+ pasteBlock = null;
1783
+ pasteCount = 0;
1784
+ redraw();
1785
+ }
1700
1786
  }
1701
- else if (pasteBlock !== null) {
1702
- pasteBlock = null;
1703
- pasteCount = 0;
1787
+ else if (cursor > 0) {
1788
+ chars.splice(cursor - 1, 1);
1789
+ cursor--;
1704
1790
  redraw();
1705
1791
  }
1706
- else if (prefix.length > 0) {
1707
- prefix = prefix.slice(0, -1);
1708
- process.stdout.write('\b \b');
1792
+ return;
1793
+ }
1794
+ if (data === '\x1b[3~') { // Delete key
1795
+ if (pasteBlock !== null) {
1796
+ if (suffixCursor < suffixChars.length) {
1797
+ suffixChars.splice(suffixCursor, 1);
1798
+ redraw();
1799
+ }
1800
+ }
1801
+ else if (cursor < chars.length) {
1802
+ chars.splice(cursor, 1);
1803
+ redraw();
1709
1804
  }
1710
1805
  return;
1711
1806
  }
1712
- // Ignore unrecognised escape sequences (arrow keys, Fn keys, etc.)
1713
- if (data.startsWith('\x1b'))
1807
+ if (data === '\x17') { // Ctrl+W (delete previous word)
1808
+ if (pasteBlock === null && cursor > 0) {
1809
+ let p = cursor - 1;
1810
+ while (p > 0 && chars[p] === ' ')
1811
+ p--;
1812
+ while (p > 0 && chars[p - 1] !== ' ')
1813
+ p--;
1814
+ chars.splice(p, cursor - p);
1815
+ cursor = p;
1816
+ redraw();
1817
+ }
1714
1818
  return;
1715
- // Single-line paste (multiple printable chars arriving at once — no newline)
1716
- if (data.length > 1) {
1717
- const printable = data.split('').filter(c => c >= ' ').join('');
1718
- if (printable) {
1719
- if (pasteBlock !== null)
1720
- suffix += printable;
1721
- else
1722
- prefix += printable;
1723
- process.stdout.write(printable);
1819
+ }
1820
+ if (data === '\x15') { // Ctrl+U (clear before cursor)
1821
+ if (pasteBlock !== null) {
1822
+ suffixChars.splice(0, suffixCursor);
1823
+ suffixCursor = 0;
1724
1824
  }
1825
+ else {
1826
+ chars.splice(0, cursor);
1827
+ cursor = 0;
1828
+ }
1829
+ redraw();
1725
1830
  return;
1726
1831
  }
1727
- // Regular single printable char
1728
- if (data.length === 1 && data >= ' ') {
1729
- if (pasteBlock !== null)
1730
- suffix += data;
1731
- else
1732
- prefix += data;
1733
- process.stdout.write(data);
1832
+ if (data === '\x0b') { // Ctrl+K (clear after cursor)
1833
+ if (pasteBlock !== null) {
1834
+ suffixChars.splice(suffixCursor);
1835
+ }
1836
+ else {
1837
+ chars.splice(cursor);
1838
+ }
1839
+ redraw();
1840
+ return;
1841
+ }
1842
+ // Ignore other escape sequences (PgUp/PgDn/Fn)
1843
+ if (data.startsWith('\x1b'))
1844
+ return;
1845
+ // Printable text (single key or single-line paste, UTF-8 / Tajik / emoji safe)
1846
+ const printable = [...data].filter(c => (c.codePointAt(0) ?? 0) >= 32).join('');
1847
+ if (printable) {
1848
+ insertAtCursor(printable);
1849
+ redraw();
1734
1850
  }
1735
1851
  }
1736
- catch (e) {
1737
- // If any keypress handler throws, restore terminal so keys don't get stuck
1852
+ catch {
1738
1853
  cleanup();
1739
1854
  resolve(null);
1740
1855
  }
@@ -1763,7 +1878,7 @@ function timeAgoShort(iso) {
1763
1878
  return `${d}d`;
1764
1879
  return `${Math.floor(d / 30)}mo`;
1765
1880
  }
1766
- async function showConversationPicker(cwd) {
1881
+ async function showConversationPicker(cwd, layout, meta) {
1767
1882
  const allConvs = listConversations(cwd, 100);
1768
1883
  if (allConvs.length === 0) {
1769
1884
  printInfo('No saved conversations yet.');
@@ -1772,10 +1887,8 @@ async function showConversationPicker(cwd) {
1772
1887
  return new Promise((resolve) => {
1773
1888
  let sel = 0;
1774
1889
  let query = '';
1775
- let drawnLines = 0;
1776
- let lastDW = 0;
1777
- const MAX_SHOWN = 10;
1778
- let scroll = 0; // first visible index within filtered list
1890
+ let drawnPhysRows = 0;
1891
+ let scroll = 0;
1779
1892
  function getAllFiltered() {
1780
1893
  if (!query)
1781
1894
  return allConvs;
@@ -1783,107 +1896,89 @@ async function showConversationPicker(cwd) {
1783
1896
  return allConvs.filter(c => c.title.toLowerCase().includes(lq));
1784
1897
  }
1785
1898
  function draw() {
1786
- const cols = process.stdout.columns ?? 80;
1787
- const DW = Math.min(Math.max(cols - 6, 50), 84);
1788
- lastDW = DW;
1899
+ layout.refreshSize();
1900
+ const cols = layout.cols;
1901
+ const DW = Math.min(Math.max(cols - 4, 48), 86);
1902
+ const maxShown = Math.max(3, Math.min(9, layout.scrollEnd - 7));
1789
1903
  const all = getAllFiltered();
1790
1904
  const total = all.length;
1791
1905
  if (total > 0 && sel >= total)
1792
1906
  sel = total - 1;
1793
1907
  if (sel < 0)
1794
1908
  sel = 0;
1795
- // Keep sel in visible window
1796
1909
  if (sel < scroll)
1797
1910
  scroll = sel;
1798
- if (sel >= scroll + MAX_SHOWN)
1799
- scroll = sel - MAX_SHOWN + 1;
1800
- scroll = Math.max(0, Math.min(scroll, Math.max(0, total - MAX_SHOWN)));
1801
- const shown = all.slice(scroll, scroll + MAX_SHOWN);
1911
+ if (sel >= scroll + maxShown)
1912
+ scroll = sel - maxShown + 1;
1913
+ scroll = Math.max(0, Math.min(scroll, Math.max(0, total - maxShown)));
1914
+ const shown = all.slice(scroll, scroll + maxShown);
1802
1915
  const N = shown.length;
1803
- // Clear previous draw
1804
- if (drawnLines > 0) {
1805
- for (let i = 0; i < drawnLines; i++)
1806
- process.stdout.write('\x1b[1A\x1b[2K');
1807
- }
1808
- drawnLines = 0;
1809
- const BC = chalk.hex('#4338ca');
1810
- const PC = chalk.hex('#818cf8');
1811
- const DIM = chalk.hex('#4b5563');
1812
- // ── Header ─────────────────────────────────────────────────
1813
- // Visible: " ╭─" (4) + hLabel + " " + "─"*hDashes + "╮" (1) = DW+2
1916
+ if (drawnPhysRows > 0) {
1917
+ clearMenu(drawnPhysRows);
1918
+ }
1919
+ const BC = colors.brand;
1920
+ const PC = colors.primary;
1921
+ const DIM = colors.muted;
1922
+ const lines = [];
1923
+ // Header
1814
1924
  const hLabel = query
1815
- ? ` / ${query} ` + DIM(`${total} found`)
1816
- : ` ${allConvs.length} conversation${allConvs.length !== 1 ? 's' : ''}`;
1817
- const hLabelVis = stripAnsi(hLabel).length;
1818
- const hDashes = Math.max(DW - 4 - hLabelVis, 1);
1819
- process.stdout.write(BC(' ╭─') + PC(hLabel) + BC(' ' + '─'.repeat(hDashes) + '╮') + '\n');
1820
- drawnLines++;
1821
- // ── Search input ────────────────────────────────────────────
1822
- // Visible: " │" (3) + " / " (5) + query + cursor(1) + pad + "│" (1) = DW+2
1823
- // → pad = DW - 8 - query.length
1824
- const sCursor = colors.primary('│');
1825
- const sPad = ' '.repeat(Math.max(DW - 8 - query.length, 0));
1826
- process.stdout.write(BC(' │') + colors.muted(' / ') + chalk.white(query) + sCursor + sPad + BC('│') + '\n');
1827
- drawnLines++;
1828
- // ── Separator ──────────────────────────────────────────────
1829
- process.stdout.write(BC(' ├' + '─'.repeat(DW - 2) + '┤') + '\n');
1830
- drawnLines++;
1831
- // ── Items ──────────────────────────────────────────────────
1832
- // Row visible: " │" (3) + " > " (4) + TITLE_W + " " (2) + msgs(7) + " " (2) + ago(3) + " │" (2) = DW+2
1833
- // → 3+4+TITLE_W+2+7+2+3+2 = 23+TITLE_W = DW+2 → TITLE_W = DW-21
1925
+ ? ` / ${clipVis(query, 24)} · ${total} found `
1926
+ : ` ${allConvs.length} conversation${allConvs.length !== 1 ? 's' : ''} `;
1927
+ const hDashes = Math.max(DW - 3 - visWidth(hLabel), 2);
1928
+ lines.push(' ' + BC('╭─') + PC.bold(hLabel) + BC('─'.repeat(hDashes) + '╮'));
1929
+ // Search input
1930
+ const qClip = clipVis(query, Math.max(DW - 10, 10));
1931
+ const searchInner = colors.muted(' / ') + colors.text(qClip) + PC('│');
1932
+ lines.push(' ' + BC('│') + padVis(searchInner, DW - 2) + BC('│'));
1933
+ // Divider
1934
+ lines.push(' ' + BC('├' + '─'.repeat(DW - 2) + '┤'));
1935
+ // Items
1834
1936
  const TITLE_W = Math.max(DW - 21, 12);
1835
1937
  if (N === 0) {
1836
1938
  const msg = query ? 'no matching conversations' : 'no conversations yet';
1837
- const ipad = ' '.repeat(Math.max(DW - 6 - msg.length, 0));
1838
- process.stdout.write(BC(' │') + ' ' + colors.muted(msg) + ipad + BC('│') + '\n');
1839
- drawnLines++;
1939
+ lines.push(' ' + BC('│') + ' ' + padVis(colors.muted(msg), DW - 6) + BC('│'));
1840
1940
  }
1841
1941
  else {
1842
1942
  for (let i = 0; i < N; i++) {
1843
1943
  const c = shown[i];
1844
1944
  const isSel = (scroll + i) === sel;
1845
- const mark = isSel ? PC('>') : ' ';
1846
- const title = c.title.replace(/\s+/g, ' ');
1847
- const disp = title.length > TITLE_W ? title.slice(0, TITLE_W - 1) + '…' : title;
1848
- const gap = ' '.repeat(Math.max(TITLE_W - disp.length, 0));
1849
- // msgs: always 7 chars — e.g. " 2 msgs" or "20 msgs"
1945
+ const mark = isSel ? PC.bold('›') : ' ';
1946
+ const title = c.title.replace(/\s+/g, ' ').trim();
1947
+ const disp = clipVis(title, TITLE_W);
1850
1948
  const msgs = String(c.messageCount).padStart(2) + ' msgs';
1851
- // ago: always 3 chars
1852
1949
  const ago = timeAgoShort(c.updatedAt).padStart(3);
1853
- const titleC = isSel ? PC.bold(disp) : chalk.hex('#94a3b8')(disp);
1854
- const msgsC = isSel ? chalk.hex('#818cf8')(msgs) : DIM(msgs);
1950
+ const titleC = isSel ? colors.text.bold(disp) : colors.subtext(disp);
1951
+ const msgsC = isSel ? PC(msgs) : DIM(msgs);
1855
1952
  const agoC = isSel ? PC(ago) : DIM(ago);
1856
- process.stdout.write(BC(' │') + ` ${mark} ` + titleC + gap + ` ` + msgsC + ` ` + agoC + ` ` + BC('│') + '\n');
1857
- drawnLines++;
1953
+ const inner = ` ${mark} ${padVis(titleC, TITLE_W)} ${msgsC} ${agoC} `;
1954
+ if (isSel) {
1955
+ lines.push(' ' + BC('│') + chalk.bgHex('#1e253b')(padVis(inner, DW - 2)) + BC('│'));
1956
+ }
1957
+ else {
1958
+ lines.push(' ' + BC('│') + padVis(inner, DW - 2) + BC('│'));
1959
+ }
1858
1960
  }
1859
1961
  }
1860
- // ── Scroll indicator row (if needed) ───────────────────────
1861
- if (total > MAX_SHOWN) {
1962
+ // Scroll indicator row
1963
+ if (total > maxShown) {
1862
1964
  const above = scroll > 0;
1863
- const below = scroll + MAX_SHOWN < total;
1864
- const pos = `${sel + 1} / ${total}`;
1865
- const arrows = (above ? '↑ ' : ' ') + pos + (below ? ' ↓' : ' ');
1866
- const ipad = ' '.repeat(Math.max(DW - 4 - arrows.length, 0));
1867
- process.stdout.write(BC(' │') + ipad + colors.muted(arrows) + ` ` + BC('│') + '\n');
1868
- drawnLines++;
1869
- }
1870
- // ── Footer ─────────────────────────────────────────────────
1871
- const hint = ' ↑↓ navigate Enter open Esc cancel ';
1872
- const fInner = DW - 2 - hint.length;
1965
+ const below = scroll + maxShown < total;
1966
+ const arrows = `${above ? '↑ ' : ' '}${sel + 1} / ${total}${below ? ' ↓' : ' '}`;
1967
+ const padL = ' '.repeat(Math.max(DW - 4 - visWidth(arrows), 0));
1968
+ lines.push(' ' + BC('│') + padL + colors.muted(arrows) + ' ' + BC('│'));
1969
+ }
1970
+ // Footer
1971
+ const hint = ' ↑↓ navigate · Enter open · Esc cancel ';
1972
+ const fInner = DW - 2 - visWidth(hint);
1873
1973
  const fLeft = Math.max(Math.floor(fInner / 2), 0);
1874
1974
  const fRight = Math.max(fInner - fLeft, 0);
1875
- process.stdout.write(BC(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + BC('─'.repeat(fRight) + '╯') + '\n');
1876
- drawnLines++;
1975
+ lines.push(' ' + BC('╰' + '─'.repeat(fLeft)) + colors.muted(hint) + BC('─'.repeat(fRight) + '╯'));
1976
+ drawnPhysRows = lines.reduce((sum, l) => sum + physRowsOf(l, cols), 0);
1977
+ process.stdout.write(lines.join('\n') + '\n');
1877
1978
  }
1878
1979
  draw();
1879
1980
  function onResize() {
1880
- const newCols = process.stdout.columns ?? 80;
1881
- const rowsPerLine = Math.max(1, Math.ceil((lastDW + 2) / newCols));
1882
- const physRows = drawnLines * rowsPerLine;
1883
- for (let i = 0; i < physRows; i++)
1884
- process.stdout.write('\x1b[1A');
1885
- process.stdout.write('\r\x1b[0J');
1886
- drawnLines = 0;
1981
+ layout.resize({ focused: false, cwd, meta, focusCursor: false });
1887
1982
  draw();
1888
1983
  }
1889
1984
  process.stdout.on('resize', onResize);
@@ -1893,21 +1988,21 @@ async function showConversationPicker(cwd) {
1893
1988
  }
1894
1989
  function close(id) {
1895
1990
  cleanup();
1896
- for (let i = 0; i < drawnLines; i++)
1897
- process.stdout.write('\x1b[1A\x1b[2K');
1991
+ clearMenu(drawnPhysRows);
1992
+ layout.drawComposer({ focused: false, cwd, meta, focusCursor: false });
1898
1993
  resolve(id);
1899
1994
  }
1900
1995
  function onKey(data) {
1901
1996
  const all = getAllFiltered();
1902
1997
  const N = all.length;
1903
1998
  switch (data) {
1904
- case '\x1b[A': // Arrow up
1999
+ case '\x1b[A':
1905
2000
  if (N > 0) {
1906
2001
  sel = Math.max(sel - 1, 0);
1907
2002
  draw();
1908
2003
  }
1909
2004
  break;
1910
- case '\x1b[B': // Arrow down
2005
+ case '\x1b[B':
1911
2006
  if (N > 0) {
1912
2007
  sel = Math.min(sel + 1, N - 1);
1913
2008
  draw();
@@ -1922,19 +2017,23 @@ async function showConversationPicker(cwd) {
1922
2017
  break;
1923
2018
  case '\x03':
1924
2019
  cleanup();
2020
+ clearMenu(drawnPhysRows);
2021
+ layout.cleanup(true);
1925
2022
  process.exit(0);
1926
2023
  break;
1927
2024
  case '\x7f':
1928
2025
  case '\b':
1929
2026
  if (query.length > 0) {
1930
- query = query.slice(0, -1);
2027
+ const qc = [...query];
2028
+ qc.pop();
2029
+ query = qc.join('');
1931
2030
  sel = 0;
1932
2031
  scroll = 0;
1933
2032
  draw();
1934
2033
  }
1935
2034
  break;
1936
2035
  default:
1937
- if (data.length === 1 && data >= ' ') {
2036
+ if (!data.startsWith('\x1b') && data >= ' ') {
1938
2037
  query += data;
1939
2038
  sel = 0;
1940
2039
  scroll = 0;
@@ -1950,7 +2049,6 @@ function printConversationHistory(messages) {
1950
2049
  const chatMsgs = messages.filter(m => m.role === 'user' || m.role === 'assistant');
1951
2050
  if (chatMsgs.length === 0)
1952
2051
  return;
1953
- // Build map: filepath → last known content (from system read_file messages)
1954
2052
  const fileSnapshot = new Map();
1955
2053
  for (const msg of messages) {
1956
2054
  if (msg.role === 'system') {
@@ -1964,14 +2062,12 @@ function printConversationHistory(messages) {
1964
2062
  if (chatMsgs.length > 20) {
1965
2063
  process.stdout.write(colors.muted(`\n … ${chatMsgs.length - 20} earlier messages …\n`));
1966
2064
  }
1967
- const msgBg = chalk.bgHex('#334155').hex('#f1f5f9');
1968
- const BC = chalk.hex('#4338ca');
1969
- const FC = chalk.hex('#e2e8f0');
2065
+ const BC = colors.border;
2066
+ const FC = colors.text;
1970
2067
  for (const msg of toShow) {
1971
2068
  if (msg.role === 'user') {
1972
2069
  const raw = String(msg.content).replace(/\s+/g, ' ').trim();
1973
- const display = raw.length > cols - 8 ? raw.slice(0, cols - 11) + '...' : raw;
1974
- process.stdout.write('\n' + msgBg((' > ' + display + ' ').padEnd(cols)) + '\n');
2070
+ renderUserMessage(raw, cols);
1975
2071
  }
1976
2072
  else {
1977
2073
  const raw = String(msg.content);
@@ -1980,106 +2076,13 @@ function printConversationHistory(messages) {
1980
2076
  const stripped = stripper.feed(raw) + stripper.flush();
1981
2077
  const rendered = (renderer.format(stripped) + renderer.flush()).replace(/^\n+/, '');
1982
2078
  if (rendered.trim())
1983
- process.stdout.write('\n' + rendered);
2079
+ process.stdout.write(rendered);
1984
2080
  const allOps = parseOps(normalizeResponse(raw));
1985
2081
  const readOps = allOps.filter(op => (op.type === 'read_file' && op.path) ||
1986
2082
  (op.type === 'read_folder' && op.path) ||
1987
2083
  (op.type === 'search_code' && op.pattern));
1988
2084
  const fileOps = allOps.filter(op => op.type !== 'read_file' && op.type !== 'read_folder' && op.type !== 'search_code');
1989
- // ── File operation summaries ─────────────────────────────
1990
2085
  if (fileOps.length > 0) {
1991
- const maxW = Math.min(cols - 12, 120);
1992
- const clip = (t) => t.length > maxW ? t.slice(0, maxW - 1) + '…' : t;
1993
- const renderDiffLines = (diff, maxLines = 60) => {
1994
- const CONTEXT = 2;
1995
- const show = new Uint8Array(diff.length);
1996
- for (let i = 0; i < diff.length; i++) {
1997
- if (diff[i].kind !== 'context') {
1998
- for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++)
1999
- show[c] = 1;
2000
- }
2001
- }
2002
- const renderLine = (line) => {
2003
- const num = String(line.lineNo).padStart(5, ' ');
2004
- if (line.kind === 'remove') {
2005
- const content = ` ${num} ${chalk.hex('#f87171')('-')} ${clip(line.text)}`;
2006
- process.stdout.write(' ' + chalk.hex('#7f1d1d')('▌') + chalk.bgHex('#1c0a0a')(content.padEnd(cols - 3)) + '\n');
2007
- }
2008
- else if (line.kind === 'add') {
2009
- const content = ` ${num} ${chalk.hex('#34d399')('+')} ${clip(line.text)}`;
2010
- process.stdout.write(' ' + chalk.hex('#065f46')('▌') + chalk.bgHex('#021a0e')(content.padEnd(cols - 3)) + '\n');
2011
- }
2012
- else {
2013
- process.stdout.write(chalk.hex('#374151')(` ${num} ${clip(line.text)}\n`));
2014
- }
2015
- };
2016
- // Build hunks
2017
- const hunks = [];
2018
- let curHunk = [];
2019
- let lastIdx = -1;
2020
- for (let i = 0; i < diff.length; i++) {
2021
- if (!show[i])
2022
- continue;
2023
- if (lastIdx >= 0 && i > lastIdx + 1) {
2024
- hunks.push(curHunk);
2025
- curHunk = [];
2026
- }
2027
- lastIdx = i;
2028
- curHunk.push(diff[i]);
2029
- }
2030
- if (curHunk.length > 0)
2031
- hunks.push(curHunk);
2032
- // Per-hunk: leading context, all removes, all adds, trailing context
2033
- let shown = 0;
2034
- for (let h = 0; h < hunks.length; h++) {
2035
- if (shown >= maxLines)
2036
- break;
2037
- if (h > 0)
2038
- process.stdout.write(chalk.hex('#374151')(' ╌╌╌\n'));
2039
- const hunk = hunks[h];
2040
- const before = [];
2041
- const hRemoves = [];
2042
- const hAdds = [];
2043
- let pendingCtx = [];
2044
- let seenChange = false;
2045
- for (const line of hunk) {
2046
- if (line.kind === 'context') {
2047
- if (!seenChange)
2048
- before.push(line);
2049
- else
2050
- pendingCtx.push(line);
2051
- }
2052
- else {
2053
- seenChange = true;
2054
- pendingCtx = [];
2055
- if (line.kind === 'remove')
2056
- hRemoves.push(line);
2057
- else
2058
- hAdds.push(line);
2059
- }
2060
- }
2061
- for (const l of before)
2062
- renderLine(l);
2063
- for (const l of hRemoves) {
2064
- if (shown >= maxLines)
2065
- break;
2066
- renderLine(l);
2067
- shown++;
2068
- }
2069
- for (const l of hAdds) {
2070
- if (shown >= maxLines)
2071
- break;
2072
- renderLine(l);
2073
- shown++;
2074
- }
2075
- for (const l of pendingCtx)
2076
- renderLine(l);
2077
- }
2078
- const total = diff.filter(d => d.kind !== 'context').length;
2079
- if (total > maxLines) {
2080
- process.stdout.write(chalk.hex('#4b5563')(` … ${total - maxLines} more lines\n`));
2081
- }
2082
- };
2083
2086
  process.stdout.write('\n');
2084
2087
  for (const op of fileOps) {
2085
2088
  if (op.type === 'write' && op.path && op.content !== undefined) {
@@ -2088,13 +2091,12 @@ function printConversationHistory(messages) {
2088
2091
  const adds = diff.filter(d => d.kind === 'add').length;
2089
2092
  const removes = diff.filter(d => d.kind === 'remove').length;
2090
2093
  const statStr = [
2091
- removes > 0 ? chalk.hex('#f87171').bold(`-${removes}`) : '',
2092
- adds > 0 ? chalk.hex('#34d399').bold(`+${adds}`) : '',
2094
+ removes > 0 ? colors.error.bold(`-${removes}`) : '',
2095
+ adds > 0 ? colors.success.bold(`+${adds}`) : '',
2093
2096
  ].filter(Boolean).join(' ');
2094
- process.stdout.write(chalk.hex('#fbbf24')(' ~') + chalk.hex('#94a3b8')(' Updated ') +
2095
- chalk.hex('#e2e8f0')(op.path) + (statStr ? ' ' + statStr : '') + '\n');
2096
- renderDiffLines(diff);
2097
- // Update snapshot so subsequent ops see the new content
2097
+ process.stdout.write(' ' + colors.warn('~') + colors.subtext(' Updated ') +
2098
+ colors.text(op.path) + (statStr ? ' ' + statStr : '') + '\n');
2099
+ renderUnifiedDiff(diff, { maxLines: 40, cols });
2098
2100
  fileSnapshot.set(op.path, op.content);
2099
2101
  }
2100
2102
  else if (op.type === 'edit' && op.path && op.find !== undefined && op.replace !== undefined) {
@@ -2102,46 +2104,40 @@ function printConversationHistory(messages) {
2102
2104
  const adds = diff.filter(d => d.kind === 'add').length;
2103
2105
  const removes = diff.filter(d => d.kind === 'remove').length;
2104
2106
  const statStr = [
2105
- removes > 0 ? chalk.hex('#f87171').bold(`-${removes}`) : '',
2106
- adds > 0 ? chalk.hex('#34d399').bold(`+${adds}`) : '',
2107
+ removes > 0 ? colors.error.bold(`-${removes}`) : '',
2108
+ adds > 0 ? colors.success.bold(`+${adds}`) : '',
2107
2109
  ].filter(Boolean).join(' ');
2108
- process.stdout.write(chalk.hex('#fbbf24')(' ~') + chalk.hex('#94a3b8')(' Updated ') +
2109
- chalk.hex('#e2e8f0')(op.path) + (statStr ? ' ' + statStr : '') + '\n');
2110
- renderDiffLines(diff);
2110
+ process.stdout.write(' ' + colors.warn('~') + colors.subtext(' Updated ') +
2111
+ colors.text(op.path) + (statStr ? ' ' + statStr : '') + '\n');
2112
+ renderUnifiedDiff(diff, { maxLines: 40, cols });
2111
2113
  }
2112
2114
  else if (op.type === 'run' && op.command) {
2113
- process.stdout.write(colors.primary(' $') + ' ' + chalk.white(op.command) + '\n');
2115
+ process.stdout.write(' ' + colors.primary('$') + ' ' + colors.text(op.command) + '\n');
2114
2116
  }
2115
2117
  else if (op.type === 'delete' && op.path) {
2116
- process.stdout.write(colors.error(' ✗') + chalk.hex('#94a3b8')(' Deleted ') + colors.muted(op.path) + '\n');
2118
+ process.stdout.write(' ' + colors.error('✗') + colors.subtext(' Deleted ') + colors.muted(op.path) + '\n');
2117
2119
  }
2118
2120
  else if (op.type === 'mkdir' && op.path) {
2119
- process.stdout.write(colors.success(' ✓') + chalk.hex('#94a3b8')(' Created ') + colors.muted(op.path) + '\n');
2121
+ process.stdout.write(' ' + colors.success('✓') + colors.subtext(' Created ') + colors.muted(op.path) + '\n');
2120
2122
  }
2121
2123
  }
2122
2124
  }
2123
- // ── Read / search / folder summary (compact box) ────────
2124
2125
  if (readOps.length > 0) {
2125
2126
  const total = readOps.length;
2126
- const boxW = Math.min(Math.max(cols - 2, 52), 100);
2127
- const maxFnameW = Math.max(boxW - 10, 8);
2127
+ const boxW = Math.min(Math.max(cols - 4, 44), 88);
2128
+ const maxFnameW = Math.max(boxW - 10, 12);
2128
2129
  const titleText = ` ${total} operation${total === 1 ? '' : 's'} `;
2129
- const dashCount = Math.max(boxW - 3 - titleText.length, 2);
2130
+ const dashCount = Math.max(boxW - 3 - visWidth(titleText), 2);
2130
2131
  process.stdout.write('\n ' + BC('╭─') + colors.muted(titleText) + BC('─'.repeat(dashCount) + '╮') + '\n');
2131
2132
  for (const op of readOps) {
2132
- let label;
2133
- if (op.type === 'search_code') {
2134
- label = `search: "${op.pattern}"`;
2135
- }
2136
- else if (op.type === 'read_folder') {
2137
- label = `folder: ${op.path}`;
2138
- }
2139
- else {
2140
- label = op.path;
2141
- }
2142
- const disp = label.length > maxFnameW ? '…' + label.slice(-(maxFnameW - 1)) : label;
2143
- const pad = ' '.repeat(Math.max(boxW - 7 - disp.length, 2));
2144
- process.stdout.write(' ' + BC('│') + ' ' + colors.muted('✓') + ' ' + FC(disp) + pad + BC('│') + '\n');
2133
+ const label = op.type === 'search_code'
2134
+ ? `search: "${op.pattern}"`
2135
+ : op.type === 'read_folder'
2136
+ ? `folder: ${op.path}`
2137
+ : op.path;
2138
+ const disp = clipStartVis(label, maxFnameW);
2139
+ const rowInner = padVis(` ${colors.success('✓')} ${FC(disp)}`, boxW - 2);
2140
+ process.stdout.write(' ' + BC('│') + rowInner + BC('│') + '\n');
2145
2141
  }
2146
2142
  process.stdout.write(' ' + BC('╰' + '─'.repeat(boxW - 2) + '╯') + '\n');
2147
2143
  }
@@ -2164,43 +2160,43 @@ async function generateAITitle(userMsg, aiMsg, token) {
2164
2160
  });
2165
2161
  }
2166
2162
  async function showDesignModeLoader(skills) {
2167
- const P = chalk.hex('#a78bfa');
2168
- const G = chalk.hex('#34d399');
2169
- const D = chalk.hex('#6b7280');
2170
- const W = chalk.hex('#e2e8f0');
2163
+ const P = colors.accent;
2164
+ const G = colors.success;
2165
+ const D = colors.muted;
2166
+ const W = colors.text;
2171
2167
  const FR = SPINNER_FRAMES;
2172
2168
  const items = skills.length > 0 ? skills.slice(0, 8) : ['Preparing design system...'];
2173
2169
  process.stdout.write('\n');
2174
- // ── Spinner ───────────────────────────────────────────────────
2175
- let fi = 0;
2176
- const spin = setInterval(() => {
2177
- process.stdout.write(`\r ${P(FR[fi++ % FR.length])} ${D('Loading Web Designer skill...')}`);
2178
- }, 60);
2179
- await new Promise(r => setTimeout(r, 500));
2180
- clearInterval(spin);
2181
- process.stdout.write('\r\x1b[K');
2182
- // ── Box with dynamic skill lines ─────────────────────────────
2170
+ const spin = new Spinner();
2171
+ spin.start('Loading Web Designer skill...');
2172
+ await new Promise(r => setTimeout(r, 450));
2173
+ spin.stop(true);
2183
2174
  const cols = process.stdout.columns ?? 80;
2184
- const maxW = Math.max(...items.map(s => s.length), 30);
2185
- const lineW = Math.min(maxW + 8, cols - 6);
2186
- process.stdout.write(' ' + P('╭' + '─'.repeat(lineW)) + '\n');
2175
+ const boxW = Math.min(Math.max(...items.map(s => visWidth(s)), 30) + 10, Math.max(cols - 4, 36), 74);
2176
+ const titleTag = ' ◆ Design Mode ';
2177
+ const dashes = Math.max(boxW - 3 - visWidth(titleTag), 2);
2178
+ process.stdout.write(' ' + P('╭─') + colors.primary.bold(titleTag) + P('─'.repeat(dashes) + '╮') + '\n');
2187
2179
  for (const skill of items) {
2180
+ const clipped = clipVis(skill, Math.max(boxW - 9, 12));
2188
2181
  let fi2 = 0;
2189
2182
  const sp2 = setInterval(() => {
2190
- process.stdout.write(`\r ${P('│')} ${D(FR[fi2++ % FR.length])} ${D(skill)}`);
2183
+ const f = FR[fi2++ % FR.length];
2184
+ const inner = padVis(` ${D(f)} ${D(clipped)}`, boxW - 2);
2185
+ process.stdout.write(`\r\x1b[K ${P('│')}${inner}${P('│')}`);
2191
2186
  }, 60);
2192
- await new Promise(r => setTimeout(r, 200));
2187
+ await new Promise(r => setTimeout(r, 180));
2193
2188
  clearInterval(sp2);
2194
- process.stdout.write(`\r ${P('│')} ${G('✓')} ${W(skill)}\n`);
2189
+ const doneInner = padVis(` ${G('✓')} ${W(clipped)}`, boxW - 2);
2190
+ process.stdout.write(`\r\x1b[K ${P('│')}${doneInner}${P('│')}\n`);
2195
2191
  }
2196
- process.stdout.write(' ' + P('╰' + '─'.repeat(lineW)) + '\n');
2197
- // ── Final badge ───────────────────────────────────────────────
2198
- await new Promise(r => setTimeout(r, 100));
2199
- process.stdout.write('\n ' + G('✓') + ' ' + chalk.hex('#c4b5fd').bold('Design') +
2200
- W(' mode activated') + '\n\n');
2192
+ process.stdout.write(' ' + P('╰' + '─'.repeat(boxW - 2) + '╯') + '\n');
2193
+ await new Promise(r => setTimeout(r, 80));
2194
+ process.stdout.write('\n ' + G('✓') + ' ' + colors.accent.bold('Design') + W(' mode activated') + '\n\n');
2201
2195
  }
2202
- export async function startRepl(cwd) {
2196
+ export async function startRepl(cwd, sessionMeta = {}, sharedLayout) {
2203
2197
  const alwaysAllowed = new Set();
2198
+ const layout = sharedLayout ?? new ChatLayout();
2199
+ const inputHistory = [];
2204
2200
  const token = getToken() ?? '';
2205
2201
  let SYSTEM_PROMPT = 'You are Dravix Code — an elite AI coding assistant. The server is temporarily unreachable. Use your best judgment to help the user.';
2206
2202
  if (token) {
@@ -2324,7 +2320,6 @@ Never guess or fabricate information.
2324
2320
  });
2325
2321
  const history = [buildSystemMsg(activeCwd)];
2326
2322
  let sessionId = generateId();
2327
- const PROMPT = colors.primary(' › ');
2328
2323
  let queuedResult = null;
2329
2324
  let lastUserLine = '';
2330
2325
  let lastAIResponse = '';
@@ -2341,6 +2336,7 @@ Never guess or fabricate information.
2341
2336
  let autoRetryCount = 0;
2342
2337
  let lastFailedOp = null;
2343
2338
  process.stdin.once('end', () => {
2339
+ layout.cleanup(true);
2344
2340
  console.log(colors.muted('\n Goodbye!\n'));
2345
2341
  process.exit(0);
2346
2342
  });
@@ -2365,8 +2361,8 @@ Never guess or fabricate information.
2365
2361
  catch { }
2366
2362
  };
2367
2363
  process.on('exit', resetTerminal);
2368
- process.on('SIGINT', () => { resetTerminal(); process.exit(0); });
2369
- process.on('SIGTERM', () => { resetTerminal(); process.exit(0); });
2364
+ process.on('SIGINT', () => { resetTerminal(); layout.cleanup(true); process.exit(0); });
2365
+ process.on('SIGTERM', () => { resetTerminal(); layout.cleanup(true); process.exit(0); });
2370
2366
  process.on('unhandledRejection', (reason) => { logError('unhandledRejection', reason); resetTerminal(); });
2371
2367
  process.on('uncaughtException', (err) => { logError('uncaughtException', err); resetTerminal(); });
2372
2368
  // Set raw mode ONCE — never toggle it during the session to avoid CMD getting stuck
@@ -2432,13 +2428,12 @@ Never guess or fabricate information.
2432
2428
  const q = queuedResult;
2433
2429
  queuedResult = null;
2434
2430
  result = q;
2435
- // Show queued message as if just submitted
2436
- const cols = process.stdout.columns ?? 80;
2437
- const msgBgQ = chalk.bgHex('#334155').hex('#f1f5f9');
2438
- process.stdout.write(msgBgQ((' > ' + q.text + ' ').padEnd(cols)) + '\n');
2431
+ layout.drawComposer({ focused: false, streaming: true, placeholder: 'Processing...', cwd: activeCwd, meta: sessionMeta, focusCursor: false });
2432
+ layout.enterChat();
2433
+ renderUserMessage(q.text, layout.cols);
2439
2434
  }
2440
2435
  else {
2441
- result = await readLine(PROMPT, activeCwd);
2436
+ result = await readLine(layout, activeCwd, sessionMeta, inputHistory);
2442
2437
  }
2443
2438
  if (!result)
2444
2439
  continue;
@@ -2447,7 +2442,7 @@ Never guess or fabricate information.
2447
2442
  lastUserLine = line;
2448
2443
  // ── Slash commands ──────────────────────────────────────────
2449
2444
  if (!skipInput && line.trim() === '/resume') {
2450
- const convId = await showConversationPicker(activeCwd);
2445
+ const convId = await showConversationPicker(activeCwd, layout, sessionMeta);
2451
2446
  if (convId) {
2452
2447
  const conv = loadConversation(convId, activeCwd);
2453
2448
  if (conv) {
@@ -2486,7 +2481,7 @@ Never guess or fabricate information.
2486
2481
  }, () => lastAIResponse || null, () => {
2487
2482
  if (lastUserLine)
2488
2483
  queuedResult = { text: lastUserLine, lines: [lastUserLine] };
2489
- });
2484
+ }, { layout, meta: sessionMeta });
2490
2485
  continue;
2491
2486
  }
2492
2487
  if (!skipInput) {
@@ -2575,24 +2570,21 @@ Never guess or fabricate information.
2575
2570
  catch { /* ignore */ }
2576
2571
  };
2577
2572
  process.stdin.on('data', onStreamKey);
2573
+ const onStreamResize = () => {
2574
+ layout.resize({ focused: false, streaming: true, placeholder: 'Streaming response...', cwd: activeCwd, meta: sessionMeta, focusCursor: false });
2575
+ };
2576
+ process.stdout.on('resize', onStreamResize);
2578
2577
  // ── Spinner ──────────────────────────────────────────────────
2579
- if (!skipInput)
2580
- process.stdout.write('\n');
2581
- let frameIdx = 0;
2578
+ const spin = new Spinner();
2582
2579
  const aiStart = Date.now();
2583
- const spinnerInterval = setInterval(() => {
2584
- process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[frameIdx++ % SPINNER_FRAMES.length])} ${colors.muted('Thinking...')}`);
2585
- }, 80);
2580
+ void aiStart;
2581
+ spin.start('Thinking...', { showElapsed: true });
2586
2582
  // ── Stream AI response ──────────────────────────────────────
2587
2583
  let fullResponse = '';
2588
2584
  let streamStarted = false;
2589
2585
  let inStreamingOp = false;
2590
2586
  let streamOpLabel = '';
2591
- let streamOpFrame = 0;
2592
- let streamOpInterval = null;
2593
2587
  let showingMidLoader = false;
2594
- let midStreamFrame = 0;
2595
- let midStreamInterval = null;
2596
2588
  // ── Inline op execution (write/edit/delete run inline as tags complete) ──
2597
2589
  const executedInlineOps = new Set();
2598
2590
  let inlineOpRunning = false;
@@ -2610,25 +2602,16 @@ Never guess or fabricate information.
2610
2602
  inlineOpRunning = true;
2611
2603
  try {
2612
2604
  // Clear any active streaming spinner before showing the permission dialog
2613
- if (streamOpInterval) {
2614
- clearInterval(streamOpInterval);
2615
- streamOpInterval = null;
2605
+ if (midStreamTimer) {
2606
+ clearTimeout(midStreamTimer);
2607
+ midStreamTimer = null;
2616
2608
  }
2609
+ spin.stop(true);
2617
2610
  if (inStreamingOp) {
2618
- process.stdout.write('\r\x1b[K');
2619
2611
  inStreamingOp = false;
2620
2612
  streamOpLabel = '';
2621
- streamOpFrame = 0;
2622
- }
2623
- if (midStreamTimer)
2624
- clearTimeout(midStreamTimer);
2625
- if (midStreamInterval) {
2626
- clearInterval(midStreamInterval);
2627
- midStreamInterval = null;
2628
- showingMidLoader = false;
2629
2613
  }
2630
2614
  if (showingMidLoader) {
2631
- process.stdout.write('\r\x1b[K');
2632
2615
  showingMidLoader = false;
2633
2616
  }
2634
2617
  if (hasRenderedContent && trailingNLs === 0)
@@ -2653,31 +2636,20 @@ Never guess or fabricate information.
2653
2636
  catch { /* ignore */ }
2654
2637
  }
2655
2638
  const previewLines = (!alwaysAllowed.has(key) && (op.type === 'write' || op.type === 'edit')) ? printDiffPreview(op, activeCwd) : 0;
2656
- const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines > 0, previewLines);
2639
+ const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines > 0, previewLines, layout, sessionMeta, activeCwd);
2657
2640
  executedInlineOps.add(inlineOpFingerprint(op));
2658
2641
  if (!allowed) {
2659
2642
  if (op.path)
2660
2643
  inlineSkippedPaths.add(op.path);
2661
2644
  }
2662
2645
  else {
2663
- let stageSpinInterval2 = null;
2664
- let stageSpinFrame2 = 0;
2665
- let stageSpinMsg2 = '';
2666
2646
  const opResult = await executeSingleOp(op, activeCwd, (msg) => {
2667
- stageSpinMsg2 = msg;
2668
- if (!stageSpinInterval2) {
2669
- stageSpinFrame2 = 0;
2670
- stageSpinInterval2 = setInterval(() => {
2671
- const f = SPINNER_FRAMES[stageSpinFrame2++ % SPINNER_FRAMES.length];
2672
- process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${chalk.hex('#94a3b8')(stageSpinMsg2)}`);
2673
- }, 80);
2674
- }
2647
+ if (!spin.isActive())
2648
+ spin.start(msg);
2649
+ else
2650
+ spin.update(msg);
2675
2651
  });
2676
- if (stageSpinInterval2) {
2677
- clearInterval(stageSpinInterval2);
2678
- stageSpinInterval2 = null;
2679
- }
2680
- process.stdout.write('\r\x1b[K');
2652
+ spin.stop(true);
2681
2653
  printOpResult(opResult);
2682
2654
  if (opResult.type === 'error' && op.type !== 'run') {
2683
2655
  let errMsg = `[Operation failed — ${label}]: ${opResult.message ?? 'Unknown error'}`;
@@ -2806,17 +2778,12 @@ Never guess or fabricate information.
2806
2778
  fullResponse += chunk;
2807
2779
  if (!streamStarted) {
2808
2780
  streamStarted = true;
2809
- clearInterval(spinnerInterval);
2810
- process.stdout.write('\r\x1b[K');
2781
+ spin.stop(true);
2811
2782
  trailingNLs = 1; // cursor on cleared line = effectively blank line start
2812
2783
  }
2813
2784
  // ── Clear mid-stream loader ────────────────────────────
2814
2785
  if (showingMidLoader) {
2815
- if (midStreamInterval) {
2816
- clearInterval(midStreamInterval);
2817
- midStreamInterval = null;
2818
- }
2819
- process.stdout.write('\r\x1b[K');
2786
+ spin.stop(true);
2820
2787
  showingMidLoader = false;
2821
2788
  trailingNLs = 1;
2822
2789
  }
@@ -2826,11 +2793,7 @@ Never guess or fabricate information.
2826
2793
  midStreamTimer = setTimeout(() => {
2827
2794
  if (!inStreamingOp && !inlineOpRunning) {
2828
2795
  showingMidLoader = true;
2829
- midStreamFrame = 0;
2830
- midStreamInterval = setInterval(() => {
2831
- const f = SPINNER_FRAMES[midStreamFrame++ % SPINNER_FRAMES.length];
2832
- process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${colors.muted('Processing...')}`);
2833
- }, 80);
2796
+ spin.start('Processing...', { showElapsed: true });
2834
2797
  }
2835
2798
  }, 900);
2836
2799
  // ── Visible text ────────────────────────────────────────
@@ -2838,14 +2801,9 @@ Never guess or fabricate information.
2838
2801
  const visible = stripped ? renderer.format(stripped) : '';
2839
2802
  if (visible) {
2840
2803
  if (inStreamingOp && !inlineOpRunning) {
2841
- if (streamOpInterval) {
2842
- clearInterval(streamOpInterval);
2843
- streamOpInterval = null;
2844
- }
2845
- process.stdout.write('\r\x1b[K');
2804
+ spin.stop(true);
2846
2805
  inStreamingOp = false;
2847
2806
  streamOpLabel = '';
2848
- streamOpFrame = 0;
2849
2807
  }
2850
2808
  const toPrint = hasRenderedContent ? visible : visible.replace(/^\n+/, '');
2851
2809
  if (toPrint) {
@@ -2872,44 +2830,27 @@ Never guess or fabricate information.
2872
2830
  if (currentOp && !inStreamingOp) {
2873
2831
  inStreamingOp = true;
2874
2832
  streamOpLabel = currentOp;
2875
- streamOpFrame = 0;
2876
2833
  if (hasRenderedContent && trailingNLs === 0)
2877
2834
  process.stdout.write('\n');
2878
- process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[0])} ${chalk.hex('#94a3b8')(streamOpLabel)}`);
2879
- streamOpInterval = setInterval(() => {
2880
- streamOpFrame = (streamOpFrame + 1) % SPINNER_FRAMES.length;
2881
- process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[streamOpFrame])} ${chalk.hex('#94a3b8')(streamOpLabel)}`);
2882
- }, 80);
2835
+ spin.start(streamOpLabel, { colorHex: '#818cf8' });
2883
2836
  }
2884
2837
  else if (currentOp && inStreamingOp && currentOp !== streamOpLabel) {
2885
2838
  streamOpLabel = currentOp;
2839
+ spin.update(streamOpLabel);
2886
2840
  }
2887
2841
  else if (!currentOp && inStreamingOp) {
2888
- if (streamOpInterval) {
2889
- clearInterval(streamOpInterval);
2890
- streamOpInterval = null;
2891
- }
2892
- process.stdout.write('\r\x1b[K');
2842
+ spin.stop(true);
2893
2843
  inStreamingOp = false;
2894
2844
  streamOpLabel = '';
2895
- streamOpFrame = 0;
2896
2845
  trailingNLs = 1;
2897
2846
  }
2898
2847
  }
2899
2848
  }, async () => {
2900
- clearInterval(spinnerInterval);
2901
- if (midStreamTimer)
2849
+ if (midStreamTimer) {
2902
2850
  clearTimeout(midStreamTimer);
2903
- if (midStreamInterval) {
2904
- clearInterval(midStreamInterval);
2905
- midStreamInterval = null;
2906
- }
2907
- if (streamOpInterval) {
2908
- clearInterval(streamOpInterval);
2909
- streamOpInterval = null;
2851
+ midStreamTimer = null;
2910
2852
  }
2911
- if (showingMidLoader || inStreamingOp)
2912
- process.stdout.write('\r\x1b[K');
2853
+ spin.stop(showingMidLoader || inStreamingOp || !streamStarted);
2913
2854
  showingMidLoader = false;
2914
2855
  inStreamingOp = false;
2915
2856
  const tail = stripper.flush();
@@ -2926,8 +2867,7 @@ Never guess or fabricate information.
2926
2867
  process.stdout.write(rest);
2927
2868
  }
2928
2869
  if (!streamStarted) {
2929
- clearInterval(spinnerInterval);
2930
- process.stdout.write('\r\x1b[K\n');
2870
+ process.stdout.write('\n');
2931
2871
  }
2932
2872
  // ── Cancelled by user (Ctrl+C) ────────────────────────
2933
2873
  if (streamCancelled) {
@@ -3078,61 +3018,28 @@ Never guess or fabricate information.
3078
3018
  return;
3079
3019
  }
3080
3020
  const cols = process.stdout.columns ?? 80;
3081
- const boxW = Math.min(Math.max(cols - 6, 40), 60);
3082
- const BC = colors.dim;
3021
+ const boxW = Math.min(Math.max(cols - 4, 46), 88);
3022
+ const BC = colors.border;
3083
3023
  const FC = colors.text;
3084
- const RIGHT_W = 8;
3085
- const LABEL_W = Math.max(boxW - 11 - RIGHT_W, 10);
3086
3024
  // Helper: shorten file path (remove common prefixes)
3087
3025
  const shortenPath = (p) => {
3088
- // Remove drive letter and common prefixes
3089
3026
  let short = p.replace(/^[A-Z]:\\[^\\]+\\[^\\]+\\/i, '');
3090
- // If still too long, show only last 2 parts
3091
- if (short.length > 30) {
3027
+ if (short.length > 42) {
3092
3028
  const parts = short.split(/[/\\]/);
3093
- short = '...' + parts.slice(-2).join('/');
3029
+ short = '…/' + parts.slice(-3).join('/');
3094
3030
  }
3095
3031
  return short;
3096
3032
  };
3097
- // Helper: truncate long file names
3098
- const truncateName = (name, maxLen) => {
3099
- if (name.length <= maxLen)
3100
- return name;
3101
- const ext = name.lastIndexOf('.');
3102
- if (ext > 0) {
3103
- const base = name.slice(0, ext);
3104
- const fileExt = name.slice(ext);
3105
- return base.slice(0, maxLen - fileExt.length - 3) + '...' + fileExt;
3106
- }
3107
- return name.slice(0, maxLen - 3) + '...';
3108
- };
3109
3033
  const results = [];
3110
3034
  for (const op of validOps) {
3111
- let spinLabel = '';
3112
- let spinColor = chalk.hex('#818cf8');
3113
- if (op.type === 'search_code') {
3114
- spinLabel = `Searching ${chalk.white('"' + (op.pattern ?? '') + '"')}`;
3115
- spinColor = chalk.hex('#f59e0b');
3116
- }
3117
- else if (op.type === 'read_folder') {
3118
- spinLabel = `Reading ${chalk.white(op.path ?? '')}`;
3119
- spinColor = chalk.hex('#818cf8');
3120
- }
3121
- else {
3122
- spinLabel = `Reading ${chalk.white(op.path ?? '')}`;
3123
- spinColor = chalk.hex('#818cf8');
3124
- }
3125
- let rfFrame = 0;
3126
- const spinLine = () => `\r\x1b[K ${colors.muted(SPINNER_FRAMES[rfFrame])} ${spinColor(spinLabel)}`;
3127
- process.stdout.write(spinLine());
3128
- const rfInterval = setInterval(() => {
3129
- rfFrame = (rfFrame + 1) % SPINNER_FRAMES.length;
3130
- process.stdout.write(spinLine());
3131
- }, 80);
3035
+ const spinText = op.type === 'search_code'
3036
+ ? `Searching "${op.pattern ?? ''}"`
3037
+ : `Reading ${op.path ?? ''}`;
3038
+ spin.start(spinText, { colorHex: op.type === 'search_code' ? '#fbbf24' : '#818cf8' });
3132
3039
  const t0 = Date.now();
3133
3040
  const res = await executeSingleOp(op, activeCwd);
3134
3041
  const ms = Date.now() - t0;
3135
- clearInterval(rfInterval);
3042
+ spin.stop(true);
3136
3043
  if (res.type === 'run') {
3137
3044
  let ctxLabel = '';
3138
3045
  let displayLabel = '';
@@ -3203,7 +3110,7 @@ Never guess or fabricate information.
3203
3110
  }
3204
3111
  }
3205
3112
  // ── Phase 2: summary box ────────────────────────────────
3206
- process.stdout.write('\r\x1b[K');
3113
+ spin.stop(true);
3207
3114
  const hasSearch = validOps.some(o => o.type === 'search_code');
3208
3115
  const hasFolder = validOps.some(o => o.type === 'read_folder');
3209
3116
  const hasFiles = validOps.some(o => o.type === 'read_file');
@@ -3215,16 +3122,18 @@ Never guess or fabricate information.
3215
3122
  if (hasFiles)
3216
3123
  titleParts.push(total === 1 ? '1 file' : `${total} files`);
3217
3124
  const titleText = ` ${titleParts.join(' · ')} `;
3218
- const dashCount = Math.max(boxW - 3 - titleText.length, 2);
3125
+ const dashCount = Math.max(boxW - 3 - visWidth(titleText), 2);
3126
+ const rightW = Math.min(Math.max(...results.map(r => visWidth(r.right)), 6), 20);
3127
+ const labelW = Math.max(boxW - 11 - rightW, 12);
3219
3128
  process.stdout.write(` ` + BC('╭─') + colors.primary.bold(titleText) + BC('─'.repeat(dashCount) + '╮') + `\n`);
3220
3129
  for (const r of results) {
3221
3130
  const icon = r.ok ? colors.success('✓') : colors.error('✗');
3222
3131
  const shortLabel = shortenPath(r.label);
3223
- const disp = truncateName(shortLabel, LABEL_W);
3224
- const labelPad = ' '.repeat(Math.max(LABEL_W - disp.length, 0));
3225
- const rightVis = stripAnsi(r.right);
3226
- const rightPad = ' '.repeat(Math.max(RIGHT_W - rightVis.length, 0));
3227
- process.stdout.write(` ` + BC('│') + ` ` + icon + ` ` + FC(disp) + labelPad + ` ` + r.right + rightPad + ` ` + BC('│') + `\n`);
3132
+ const disp = clipStartVis(shortLabel, labelW);
3133
+ const rightClip = clipVis(stripAnsi(r.right), rightW);
3134
+ const rightStyled = r.ok ? colors.muted(rightClip) : colors.error(rightClip);
3135
+ const rowInner = padVis(` ${icon} ${padVis(FC(disp), labelW)} ${rightStyled}`, boxW - 2);
3136
+ process.stdout.write(` ` + BC('│') + rowInner + BC('│') + `\n`);
3228
3137
  }
3229
3138
  process.stdout.write(` ` + BC('╰' + '─'.repeat(boxW - 2) + '╯') + `\n`);
3230
3139
  readFileContinue = true;
@@ -3255,7 +3164,7 @@ Never guess or fabricate information.
3255
3164
  }
3256
3165
  }
3257
3166
  const previewLines2 = (!alwaysAllowed.has(key) && (op.type === 'write' || op.type === 'edit')) ? printDiffPreview(op, activeCwd) : 0;
3258
- const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines2 > 0, previewLines2);
3167
+ const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines2 > 0, previewLines2, layout, sessionMeta, activeCwd);
3259
3168
  if (!allowed) {
3260
3169
  if (op.path)
3261
3170
  skippedPaths.add(op.path);
@@ -3263,24 +3172,13 @@ Never guess or fabricate information.
3263
3172
  declinedCmds.push(op.command);
3264
3173
  continue;
3265
3174
  }
3266
- let stageSpinInterval = null;
3267
- let stageSpinFrame = 0;
3268
- let stageSpinMsg = '';
3269
3175
  const opResult = await executeSingleOp(op, activeCwd, (stageMsg) => {
3270
- stageSpinMsg = stageMsg;
3271
- if (!stageSpinInterval) {
3272
- stageSpinFrame = 0;
3273
- stageSpinInterval = setInterval(() => {
3274
- const f = SPINNER_FRAMES[stageSpinFrame++ % SPINNER_FRAMES.length];
3275
- process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${colors.subtext(stageSpinMsg)}`);
3276
- }, 80);
3277
- }
3176
+ if (!spin.isActive())
3177
+ spin.start(stageMsg);
3178
+ else
3179
+ spin.update(stageMsg);
3278
3180
  });
3279
- if (stageSpinInterval) {
3280
- clearInterval(stageSpinInterval);
3281
- stageSpinInterval = null;
3282
- }
3283
- process.stdout.write('\r\x1b[K');
3181
+ spin.stop(true);
3284
3182
  printOpResult(opResult);
3285
3183
  // Collect file operation errors for AI feedback
3286
3184
  if (opResult.type === 'error' && op.type !== 'run') {
@@ -3381,18 +3279,11 @@ Never guess or fabricate information.
3381
3279
  resolve();
3382
3280
  }
3383
3281
  }, (err) => {
3384
- clearInterval(spinnerInterval);
3385
- if (midStreamTimer)
3282
+ if (midStreamTimer) {
3386
3283
  clearTimeout(midStreamTimer);
3387
- if (midStreamInterval) {
3388
- clearInterval(midStreamInterval);
3389
- midStreamInterval = null;
3390
- }
3391
- if (streamOpInterval) {
3392
- clearInterval(streamOpInterval);
3393
- streamOpInterval = null;
3284
+ midStreamTimer = null;
3394
3285
  }
3395
- process.stdout.write('\r\x1b[K');
3286
+ spin.stop(true);
3396
3287
  const raw = err.message;
3397
3288
  const msg = raw.includes('timed out')
3398
3289
  ? 'Connection timed out — check your internet and try again'
@@ -3407,8 +3298,9 @@ Never guess or fabricate information.
3407
3298
  resolve();
3408
3299
  }, streamAbort.signal, FLASH_MODEL);
3409
3300
  });
3410
- // ── Remove streaming key listener ─────────────────────────
3301
+ // ── Remove streaming listeners ────────────────────────────
3411
3302
  process.stdin.removeListener('data', onStreamKey);
3303
+ process.stdout.removeListener('resize', onStreamResize);
3412
3304
  // ── Accumulate token usage (deferred — report on next user turn) ──
3413
3305
  if (cliTok && fullResponse) {
3414
3306
  pendingOutputTokens += estimateTokens(normalizeResponse(fullResponse));