minicode-ai 0.15.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +6 -4
  2. package/cli/commands/exec.ts +3 -2
  3. package/cli/commands/openwork.ts +1 -1
  4. package/cli/commands.ts +6 -6
  5. package/cli/index.ts +4 -4
  6. package/cli/model-manager.ts +1 -1
  7. package/cli/setup.ts +57 -30
  8. package/cli/tui.ts +106 -11
  9. package/docs/CONTROL-PLANE-MAP.md +6 -4
  10. package/docs/OUTPUT_EVENT_MODEL.md +4 -3
  11. package/docs/OUTPUT_PROTOCOL_SPEC.md +1 -1
  12. package/docs/OUTPUT_RENDERING_SPEC.md +16 -4
  13. package/docs/OUTPUT_UX_RULES.md +38 -32
  14. package/docs/P14_OPEN_WORK.md +290 -0
  15. package/docs/README.md +1 -1
  16. package/docs/SUMMARY.md +36 -22
  17. package/docs/TERMINAL_CONTRACT.md +54 -7
  18. package/docs/UI_RENDER_PIPELINE.md +47 -8
  19. package/docs/agents.md +1 -1
  20. package/docs/architecture.md +9 -8
  21. package/docs/autonomous-scheduler.md +142 -0
  22. package/docs/choosing-mode.md +2 -2
  23. package/docs/cli.md +4 -4
  24. package/docs/concepts.md +5 -5
  25. package/docs/config-providers.md +3 -3
  26. package/docs/contributing.md +7 -9
  27. package/docs/environment.md +5 -4
  28. package/docs/getting-started.md +4 -4
  29. package/docs/mcp-lsp.md +2 -2
  30. package/docs/memory-sessions.md +1 -1
  31. package/docs/policy-sandbox.md +7 -4
  32. package/docs/pricing-budget.md +3 -3
  33. package/docs/quickstart.md +1 -1
  34. package/docs/repl.md +5 -5
  35. package/docs/security-model.md +1 -1
  36. package/docs/security.md +9 -8
  37. package/docs/skills.md +2 -2
  38. package/docs/terminal.md +10 -2
  39. package/docs/tools.md +4 -4
  40. package/docs/troubleshooting.md +3 -3
  41. package/docs/verify-benchmark.md +0 -3
  42. package/package.json +9 -18
  43. package/src/app/session.ts +40 -7
  44. package/src/constants.ts +31 -0
  45. package/src/hooks/run.ts +5 -6
  46. package/src/mcp/http-transport.ts +1 -1
  47. package/src/policy/bash-guard.ts +26 -6
  48. package/src/policy/compaction.ts +107 -17
  49. package/src/policy/consequence-engine.ts +3 -3
  50. package/src/policy/context-window.ts +24 -1
  51. package/src/policy/context.ts +16 -4
  52. package/src/policy/permission.ts +219 -4
  53. package/src/presentation/adapter.ts +1 -1
  54. package/src/presentation/events.ts +2 -2
  55. package/src/presentation/label.ts +3 -3
  56. package/src/presentation/model.ts +4 -0
  57. package/src/presentation/store.ts +2 -2
  58. package/src/runtime/child-execution.ts +1 -1
  59. package/src/runtime/composition.ts +5 -5
  60. package/src/runtime/execution-registry.ts +1 -1
  61. package/src/runtime/production-execution.ts +3 -3
  62. package/src/runtime/production-runtime.ts +2 -2
  63. package/src/runtime/runtime-capabilities.ts +1 -1
  64. package/src/runtime/runtime-status-facts.ts +1 -1
  65. package/src/runtime/runtime-task-admission.ts +2 -2
  66. package/src/session/context-assembly.ts +8 -1
  67. package/src/session/context-identity.ts +2 -2
  68. package/src/session/context-projection.ts +36 -11
  69. package/src/session/persistence.ts +1 -1
  70. package/src/task/autonomous-context.ts +2 -2
  71. package/src/task/autonomous-policy.ts +3 -3
  72. package/src/task/model.ts +2 -2
  73. package/src/task/production-scheduler.ts +2 -2
  74. package/src/task/scheduler.ts +3 -2
  75. package/src/task/scheduling-policy.ts +2 -1
  76. package/src/task/trigger.ts +5 -5
  77. package/src/tools/read_image.ts +2 -1
  78. package/src/tools/task.ts +1 -1
  79. package/src/ui/assistant/simple.ts +33 -30
  80. package/src/ui/footer.ts +48 -9
  81. package/src/ui/i18n/en.ts +1 -0
  82. package/src/ui/i18n/id.ts +1 -0
  83. package/src/ui/input/prompt-engine.ts +36 -10
  84. package/src/ui/render/cells.ts +320 -0
  85. package/src/ui/render/composer-wrap.ts +73 -0
  86. package/src/ui/render/detail.ts +2 -2
  87. package/src/ui/render/ledger.ts +47 -0
  88. package/src/ui/render/theme.ts +32 -4
  89. package/src/ui/render/width.ts +2 -2
  90. package/src/ui/render/wrap.ts +5 -3
  91. package/src/ui/runtime/screen.ts +84 -7
  92. package/src/ui/runtime/statusline.ts +26 -0
  93. package/src/ui/screens/model-manager.ts +1 -1
  94. package/src/ui/tui/app.ts +336 -65
  95. package/src/ui/tui/transcript.ts +247 -88
  96. package/vendor/minicore/VENDOR.md +15 -11
  97. package/vendor/minicore/src/core/events.ts +1 -0
  98. package/vendor/minicore/src/core/loop.ts +10 -0
  99. package/vendor/minicore/src/core/session.ts +39 -0
package/src/ui/tui/app.ts CHANGED
@@ -20,8 +20,10 @@ import {
20
20
  type KeyStreamPump,
21
21
  type PromptKey,
22
22
  type PromptState,
23
+ pointLength,
23
24
  toGraphemes,
24
25
  } from "../input/prompt-engine.ts"
26
+ import { appendWrapped, shaveWrapped } from "../render/composer-wrap.ts"
25
27
  import { formatError } from "../render/errors.ts"
26
28
  import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
27
29
  import { c } from "../render/theme.ts"
@@ -82,6 +84,25 @@ const MOUSE_DRAG_ON = "\x1b[?1002h\x1b[?1006h"
82
84
  const MOUSE_WHEEL_ON = "\x1b[?1000h\x1b[?1006h"
83
85
  const MOUSE_OFF = "\x1b[?1006l\x1b[?1002l\x1b[?1000l"
84
86
  const MAX_SELECTION_CHARS = 200_000
87
+ /** Batas byte UTF-8 payload salin (selaras `MAX_CLIPBOARD_BYTES` OSC 52 di
88
+ * `assistant/simple.ts`): 200k char CJK bisa 600 KB byte, jadi cek char saja
89
+ * tidak cukup sebelum menulis OSC 52. */
90
+ const MAX_SELECTION_BYTES = 256 * 1024
91
+
92
+ /** Panjang UTF-8 (byte) tanpa alokasi — untuk guard ukuran payload salin. */
93
+ function utf8ByteLength(text: string): number {
94
+ let bytes = 0
95
+ for (let i = 0; i < text.length; i++) {
96
+ const code = text.charCodeAt(i)
97
+ if (code < 0x80) bytes += 1
98
+ else if (code < 0x800) bytes += 2
99
+ else if (code >= 0xd800 && code <= 0xdbff) {
100
+ bytes += 4
101
+ i++
102
+ } else bytes += 3
103
+ }
104
+ return bytes
105
+ }
85
106
  type MouseMode = "off" | "wheel" | "drag"
86
107
 
87
108
  function mouseSelectionEnabled(): boolean {
@@ -120,6 +141,15 @@ interface FrameLayout {
120
141
  composerOffset: number
121
142
  }
122
143
 
144
+ /** Baris visual composer + posisi kursor (indeks baris 0-based, kolom 1-based). */
145
+ interface ComposerLayout {
146
+ rows: string[]
147
+ visIdx: number
148
+ col: number
149
+ }
150
+
151
+ const EMPTY_COMPOSER_LAYOUT: ComposerLayout = { rows: [], visIdx: 0, col: 1 }
152
+
123
153
  interface SelectionState {
124
154
  anchor: TranscriptPoint
125
155
  focus: TranscriptPoint
@@ -203,6 +233,13 @@ export class TuiApp {
203
233
  /** Hint "tekan lagi untuk keluar" tampil sekali setelah abort pertama. */
204
234
  private abortHintOn = false
205
235
  private frames = 0
236
+ /**
237
+ * Kedalaman batch input. Selama >0 paint ditunda lalu digabung jadi SATU
238
+ * frame per chunk stdin: burst/paste 500 karakter tidak lagi melukis 500
239
+ * frame (O(N²) diff-write). Key tunggal tetap melukis langsung.
240
+ */
241
+ private paintBatchDepth = 0
242
+ private paintPending = false
206
243
  private quitRequested = false
207
244
  private finish: (() => void) | null = null
208
245
  private runtimeFailure: { error: unknown } | null = null
@@ -233,6 +270,19 @@ export class TuiApp {
233
270
  private mouseMode: MouseMode = "off"
234
271
  private selection: SelectionState | null = null
235
272
  private lastLayout: FrameLayout | null = null
273
+ /**
274
+ * Cache layout composer: satu paint memanggil tinggi, isi, dan posisi
275
+ * kursor untuk state yang SAMA. Dulu tiap panggilan me-wrap ulang seluruh
276
+ * teks (3×), jadi ketikan panjang membayar wrap berulang. Key memuat line,
277
+ * kursor, lebar efektif, dan mode editing agar tak menyajikan frame basi.
278
+ */
279
+ private composerCache: {
280
+ line: string
281
+ cursor: number
282
+ cols: number
283
+ editing: boolean
284
+ layout: ComposerLayout
285
+ } | null = null
236
286
  private onExit: (() => void) | null = null
237
287
  /**
238
288
  * Langganan bus untuk repaint live (streaming jawaban, ledger tool,
@@ -248,6 +298,12 @@ export class TuiApp {
248
298
  private scrollBase = 0
249
299
  /** Panjang visual terakhir (kunci posisi baca agar stream tak merampasnya). */
250
300
  private lastWrapped = 0
301
+ /** Auto-scroll saat drag seleksi menempel di tepi viewport (feature). */
302
+ private autoScrollTimer: ReturnType<typeof setInterval> | undefined
303
+ /** +1 = tepi ATAS (gulir ke konten lama); -1 = tepi BAWAH (ke konten baru). */
304
+ private autoScrollDir: 1 | -1 = 1
305
+ /** Kolom x yang ditambatkan fokus seleksi selama auto-scroll. */
306
+ private autoScrollCol = 0
251
307
 
252
308
  constructor(
253
309
  private readonly transcript: Transcript,
@@ -461,6 +517,7 @@ export class TuiApp {
461
517
  this.repaintTimer = undefined
462
518
  }
463
519
  this.stopActivityClock()
520
+ this.stopAutoScroll()
464
521
  for (const unsubscribe of this.busUnsubs.splice(0)) {
465
522
  try {
466
523
  unsubscribe()
@@ -547,11 +604,26 @@ export class TuiApp {
547
604
  // Tanpa ini repaint penuh App 50ms kemudian menimpa region popup +
548
605
  // memutasi state di belakang view. Gagal-di-kode-lama.
549
606
  if (this.suspended > 0) return false
550
- for (const { key } of keys) {
551
- if (this.quitRequested) return true
552
- this.handleKey(key)
607
+ // Satu chunk stdin = satu key-event di decoder (burst/paste), jadi semua
608
+ // key di sini digabung menjadi satu paint. finally WAJIB menurunkan depth
609
+ // walau handler melempar, supaya paint berikutnya tidak tertahan selamanya.
610
+ this.paintBatchDepth++
611
+ try {
612
+ for (const { key } of keys) {
613
+ if (this.quitRequested) return true
614
+ this.handleKey(key)
615
+ }
616
+ return this.quitRequested
617
+ } finally {
618
+ this.paintBatchDepth--
619
+ if (this.paintBatchDepth === 0) this.flushPendingPaint()
553
620
  }
554
- return this.quitRequested
621
+ }
622
+
623
+ private flushPendingPaint(): void {
624
+ if (this.paintBatchDepth > 0 || !this.paintPending) return
625
+ this.paintPending = false
626
+ this.paintCurrent()
555
627
  }
556
628
 
557
629
  private handleKey(key: PromptKey): void {
@@ -711,7 +783,19 @@ export class TuiApp {
711
783
  private applyEngine(key: PromptKey): void {
712
784
  if (["char", "backspace", "delete", "enter", "ctrl-j"].includes(key.type)) this.selection = null
713
785
  const hints = (line: string) => (line.startsWith("/") ? this.host.listCommands(line) : [])
786
+ // Fast path kursor: panah/Home/End hanya memindahkan kursor — isi frame
787
+ // (transkrip, menu, footer) tak berubah satu sel pun. Menyusun ulang frame
788
+ // penuh + diff per sel hanya untuk menggeser kursor membuang kerja O(frame).
789
+ // Tangkap visIdx SEBELUM key supaya posisi baris kursor baru bisa dihitung
790
+ // dari layout lama tanpa buildLayout.
791
+ const cursorOnly =
792
+ key.type === "left" || key.type === "right" || key.type === "home" || key.type === "end"
793
+ const prevVisIdx =
794
+ cursorOnly && this.editing && this.currentScreen?.ok
795
+ ? this.composerLayout(Math.max(10, this.currentScreen.cols)).visIdx
796
+ : -1
714
797
  const { state, action } = applyKey(this.state, key, hints)
798
+ const lineUnchanged = state.line === this.state.line
715
799
  this.state = state
716
800
  if (action === "submit") {
717
801
  void this.doSubmit(state.line)
@@ -719,6 +803,16 @@ export class TuiApp {
719
803
  // Engine cancel (ctrl-c/ctrl-d) sudah ditangani di atas; tak terjangkau.
720
804
  } else if (action === "render" || action === "none") {
721
805
  if (action === "render" && key.type === "char") this.editing = true
806
+ if (
807
+ cursorOnly &&
808
+ action === "render" &&
809
+ lineUnchanged &&
810
+ prevVisIdx >= 0 &&
811
+ this.canCursorPaint()
812
+ ) {
813
+ this.paintCursorOnly(prevVisIdx)
814
+ return
815
+ }
722
816
  // Ketikan baru = kembali ke ekor (I18); stream turn TIDAK me-reset
723
817
  // (user yang sedang membaca ke atas tak dirampas).
724
818
  if (key.type === "char" || key.type === "backspace" || key.type === "delete") {
@@ -728,6 +822,45 @@ export class TuiApp {
728
822
  }
729
823
  }
730
824
 
825
+ /** Siap melukis kursor-saja? Butuh layout terakhir + layar sehat. */
826
+ private canCursorPaint(): boolean {
827
+ return (
828
+ !this.quitRequested &&
829
+ !this.released &&
830
+ this.suspended === 0 &&
831
+ this.paintBatchDepth === 0 &&
832
+ !this.tooSmall() &&
833
+ this.editing &&
834
+ this.lastLayout !== null
835
+ )
836
+ }
837
+
838
+ /**
839
+ * Geser KURSOR saja memakai layout lama. `prevVisIdx` = visIdx composer
840
+ * sebelum key; delta baris kursor = delta visIdx (geometri atas tak berubah).
841
+ */
842
+ private paintCursorOnly(prevVisIdx: number): void {
843
+ const layout = this.lastLayout
844
+ const screen = this.currentScreen
845
+ if (!layout || !screen?.ok) {
846
+ this.paintCurrent()
847
+ return
848
+ }
849
+ const composer = this.composerLayout(Math.max(10, screen.cols))
850
+ const row = Math.max(1, layout.cursor.row + (composer.visIdx - prevVisIdx))
851
+ const col = Math.max(1, composer.col)
852
+ try {
853
+ screen.moveCursor(row, col)
854
+ } catch (error) {
855
+ this.stopAfterRuntimeError(error)
856
+ return
857
+ }
858
+ // Simpan posisi kursor baru supaya paint berikutnya tak mengira kursor
859
+ // masih di tempat lama (mis. mouse-hit-test memakai lastLayout).
860
+ this.lastLayout = { ...layout, cursor: { row, col } }
861
+ this.frames++
862
+ }
863
+
731
864
  private async doSubmit(rawLine: string): Promise<void> {
732
865
  const line = rawLine.trim()
733
866
  this.state = createState()
@@ -964,6 +1097,12 @@ export class TuiApp {
964
1097
  s = r.state
965
1098
  if (r.action !== "render" && r.action !== "none") break
966
1099
  }
1100
+ // Recall (history ↑↓ / Ctrl+R) BUKAN mengetik "/" — menu command hanya
1101
+ // boleh terbuka saat user AKTIF mengetik (via applyEngine). `withLine` di
1102
+ // engine menyetel menuOpen = line.startsWith("/"), jadi recall entri command
1103
+ // (/model) akan membuka menu; tanpa koreksi ini, ↑↓ berikutnya dinavigasi ke
1104
+ // menu (sel), bukan history, dan user terkunci tak bisa melewati entri command.
1105
+ s = { ...s, menuOpen: false, sel: -1 }
967
1106
  this.state = s
968
1107
  this.editing = true
969
1108
  this.paintCurrent()
@@ -987,6 +1126,27 @@ export class TuiApp {
987
1126
  this.paintCurrent()
988
1127
  }
989
1128
 
1129
+ /**
1130
+ * Scroll per BARIS (bukan per halaman) — dipakai auto-scroll seleksi agar
1131
+ * gulirnya halus & presisi. `n` = baris terbungkus (+ = ke atas/lama,
1132
+ * - = ke bawah/baru); di-clamp ke [0, wrapped - viewH]. Menjaga basis
1133
+ * `tailSize`/`scrollBase` sama seperti `scrollBy`.
1134
+ */
1135
+ private scrollRows(n: number): void {
1136
+ const cols = process.stdout.columns || 80
1137
+ const rows = process.stdout.rows || 24
1138
+ const viewH = Math.max(1, this.viewportHeight(rows, cols) - 1)
1139
+ const wrapped = this.transcript.wrappedLength(cols)
1140
+ const maxBack = Math.max(0, wrapped - viewH)
1141
+ if (this.scrollBack === 0 && n > 0) this.scrollBase = this.transcript.total()
1142
+ this.scrollBack = Math.max(0, Math.min(this.scrollBack + n, maxBack))
1143
+ if (this.scrollBack === 0) {
1144
+ this.tailSize = this.transcript.total()
1145
+ this.scrollBase = this.tailSize
1146
+ }
1147
+ this.paintCurrent()
1148
+ }
1149
+
990
1150
  /**
991
1151
  * Lompat ke ujung transkrip (temuan audit TUI-002): Home = baris teratas
992
1152
  * (scrollBack maksimum), End = ekor. `lastWrapped` dinetralkan SEBELUM
@@ -1075,12 +1235,12 @@ export class TuiApp {
1075
1235
  return [this.activityRow(content, cols)]
1076
1236
  }
1077
1237
  if (!this.editing) return [""]
1078
- return this.inputRows(cols)
1238
+ return this.composerLayout(cols).rows
1079
1239
  }
1080
1240
 
1081
1241
  private composerHeight(cols: number, busy = this.busy): number {
1082
1242
  if (busy || !this.editing) return 1
1083
- return Math.min(MAX_INPUT_ROWS, Math.max(1, this.inputRows(cols).length))
1243
+ return Math.min(MAX_INPUT_ROWS, Math.max(1, this.composerLayout(cols).rows.length))
1084
1244
  }
1085
1245
 
1086
1246
  // ── Paint ──
@@ -1099,6 +1259,10 @@ export class TuiApp {
1099
1259
  }
1100
1260
 
1101
1261
  private paintCurrent(): void {
1262
+ if (this.paintBatchDepth > 0) {
1263
+ this.paintPending = true
1264
+ return
1265
+ }
1102
1266
  if (!this.currentScreen || this.quitRequested) return
1103
1267
  try {
1104
1268
  this.paint(this.currentScreen)
@@ -1123,23 +1287,113 @@ export class TuiApp {
1123
1287
  return Math.max(1, rows - 2 - inputH - menuH)
1124
1288
  }
1125
1289
 
1126
- private inputRows(cols: number): string[] {
1127
- if (!this.editing) return []
1290
+ private composerLayout(cols: number): ComposerLayout {
1291
+ if (!this.editing) return EMPTY_COMPOSER_LAYOUT
1128
1292
  const w = Math.max(10, cols)
1129
- const out: string[] = []
1130
- if (!this.state.line) {
1131
- out.push(PROMPT_FIRST)
1132
- return out
1293
+ const line = this.state.line
1294
+ const cursor = this.state.cursor
1295
+ const cached = this.composerCache
1296
+ if (cached?.editing && cached.cols === w && cached.cursor === cursor && cached.line === line) {
1297
+ return cached.layout
1133
1298
  }
1134
- const logical = this.state.line.split("\n")
1135
- logical.forEach((ln, idx) => {
1136
- const prefix = idx === 0 ? PROMPT_FIRST : PROMPT_CONT
1137
- const full = `${prefix}${ln}`
1299
+ const layout =
1300
+ this.incrementalComposerLayout(cached, line, cursor, w) ??
1301
+ this.layoutComposer(line, cursor, w)
1302
+ this.composerCache = { line, cursor, cols: w, editing: true, layout }
1303
+ return layout
1304
+ }
1305
+
1306
+ /**
1307
+ * Coba wrap inkremental untuk ketikan/silang di UJUNG baris. `null` =
1308
+ * pemanggil membungkus ulang penuh (`layoutComposer`). Aman: hanya menerima
1309
+ * state yang benar-benar perubahan-ujung; bentuk lain jatuh balik.
1310
+ */
1311
+ private incrementalComposerLayout(
1312
+ cached: {
1313
+ line: string
1314
+ cursor: number
1315
+ cols: number
1316
+ editing: boolean
1317
+ layout: ComposerLayout
1318
+ } | null,
1319
+ line: string,
1320
+ cursor: number,
1321
+ w: number,
1322
+ ): ComposerLayout | null {
1323
+ if (!cached?.editing || cached.cols !== w || !line) return null
1324
+ const prevLine = cached.line
1325
+ if (prevLine === line) return null
1326
+ const prevRows = cached.layout.rows
1327
+ if (!prevRows.length) return null
1328
+ // Kedua sisi harus ber-kursor di ujung: itulah syarat baris sebelumnya
1329
+ // sudah jenuh sehingga hanya baris terakhir yang berubah.
1330
+ if (cursor !== pointLength(line) || cached.cursor !== pointLength(prevLine)) return null
1331
+ let rows: string[] | null
1332
+ if (line.startsWith(prevLine)) {
1333
+ rows = appendWrapped(prevRows, line.slice(prevLine.length), w)
1334
+ } else if (prevLine.startsWith(line)) {
1335
+ rows = shaveWrapped(prevRows, prevLine.slice(line.length), w)
1336
+ } else {
1337
+ return null
1338
+ }
1339
+ if (!rows) return null
1340
+ if (rows.length === 0) return null
1341
+ const lastRow = rows[rows.length - 1] ?? ""
1342
+ return { rows, visIdx: rows.length - 1, col: displayWidth(lastRow) + 1 }
1343
+ }
1344
+
1345
+ /**
1346
+ * Wrap composer + posisi kursor dalam SATU lintasan. Semantiknya sama
1347
+ * dengan gabungan inputRows + cursorIndex lama: prefix per baris logis,
1348
+ * potong per kolom, kursor di baris visual yang memuat targetWidth.
1349
+ */
1350
+ private layoutComposer(line: string, cursor: number, w: number): ComposerLayout {
1351
+ // Prompt kosong SELALU satu baris utuh — sama dengan jalur lama. Tanpa
1352
+ // special-case, terminal sempit (w < lebar prefix) memecah prefix jadi dua
1353
+ // baris dan menggeser kursor; MIN_COLS membuatnya tak terjangkau di app,
1354
+ // tapi helper ini juga dipakai layout lain/test.
1355
+ if (!line) return { rows: [PROMPT_FIRST], visIdx: 0, col: displayWidth(PROMPT_FIRST) + 1 }
1356
+ // Kursor dinormalisasi ke batas grapheme supaya emoji tak terbelah saat
1357
+ // dihitung (targetWidth memakai teks sebelum kursor).
1358
+ const units = toGraphemes(line)
1359
+ const safeCursor = Math.max(0, Math.min(cursor, units.length))
1360
+ const before = units.slice(0, safeCursor).join("")
1361
+ const beforeLines = before.split("\n")
1362
+ const logicalIdx = beforeLines.length - 1
1363
+ const lastLine = beforeLines[logicalIdx] ?? ""
1364
+ const targetWidth =
1365
+ displayWidth(logicalIdx === 0 ? PROMPT_FIRST : PROMPT_CONT) + displayWidth(lastLine)
1366
+
1367
+ const rows: string[] = []
1368
+ const logical = line.split("\n")
1369
+ let visIdx = 0
1370
+ let col = 1
1371
+ let cursorRowFound = false
1372
+ for (let li = 0; li < logical.length; li++) {
1373
+ const prefix = li === 0 ? PROMPT_FIRST : PROMPT_CONT
1374
+ const full = `${prefix}${logical[li] ?? ""}`
1138
1375
  const wrapped = chunkByWidth(full, w)
1139
- if (!wrapped.length) out.push(full)
1140
- else for (const r of wrapped) out.push(r)
1141
- })
1142
- return out
1376
+ for (const row of wrapped) rows.push(row)
1377
+ if (li < logicalIdx) {
1378
+ visIdx += wrapped.length
1379
+ continue
1380
+ }
1381
+ if (li !== logicalIdx || cursorRowFound) continue
1382
+ // Baris kursor: baris visual pertama yang memuat targetWidth (atau
1383
+ // baris terakhir bila kursor tepat di ujung wrap).
1384
+ let acc = 0
1385
+ for (let wi = 0; wi < wrapped.length; wi++) {
1386
+ const ww = displayWidth(wrapped[wi] ?? "")
1387
+ if (targetWidth < acc + ww || wi === wrapped.length - 1) {
1388
+ visIdx += wi
1389
+ col = Math.max(1, targetWidth - acc + 1)
1390
+ cursorRowFound = true
1391
+ break
1392
+ }
1393
+ acc += ww
1394
+ }
1395
+ }
1396
+ return { rows, visIdx, col }
1143
1397
  }
1144
1398
 
1145
1399
  private menuRows(rows: number, cols: number, busy = this.isBusy()): string[] {
@@ -1254,6 +1508,7 @@ export class TuiApp {
1254
1508
  return
1255
1509
  }
1256
1510
  this.selection = { anchor: point, focus: point, dragging: true }
1511
+ this.updateAutoScroll(layout, key)
1257
1512
  this.paintCurrent()
1258
1513
  return
1259
1514
  }
@@ -1262,6 +1517,7 @@ export class TuiApp {
1262
1517
  const point = this.transcript.pointAt(row, key.x - 1)
1263
1518
  if (!point) return
1264
1519
  this.selection.focus = point
1520
+ this.updateAutoScroll(layout, key)
1265
1521
  this.scheduleSelectionPaint()
1266
1522
  return
1267
1523
  }
@@ -1272,10 +1528,67 @@ export class TuiApp {
1272
1528
  if (point) this.selection.focus = point
1273
1529
  }
1274
1530
  this.selection.dragging = false
1531
+ this.stopAutoScroll()
1275
1532
  this.paintCurrent()
1276
1533
  }
1277
1534
  }
1278
1535
 
1536
+ // ── Auto-scroll saat drag seleksi menempel di tepi ──
1537
+
1538
+ /** Mulai/teruskan auto-scroll seleksi ke arah `dir` pada kolom `col`. */
1539
+ private startAutoScroll(dir: 1 | -1, col: number): void {
1540
+ if (this.autoScrollTimer !== undefined && this.autoScrollDir === dir) return
1541
+ this.stopAutoScroll()
1542
+ this.autoScrollDir = dir
1543
+ this.autoScrollCol = col
1544
+ this.autoScrollTimer = setInterval(() => {
1545
+ const sel = this.selection
1546
+ if (!sel?.dragging || this.suspended > 0 || this.released) {
1547
+ this.stopAutoScroll()
1548
+ return
1549
+ }
1550
+ const layout = this.lastLayout
1551
+ if (!layout || layout.transcriptRows.length === 0) return
1552
+ // Tautkan fokus ke baris tepi SEBELUM menggulir, supaya tiap tick seleksi
1553
+ // meluas searah scroll; scrollRows() berikutnya menampilkan baris tetangga.
1554
+ const rows = layout.transcriptRows
1555
+ const edgeRow = this.autoScrollDir === 1 ? rows[0] : rows[rows.length - 1]
1556
+ if (edgeRow?.selectable) {
1557
+ const p = this.transcript.pointAt(edgeRow, this.autoScrollCol - 1)
1558
+ if (p) sel.focus = p
1559
+ }
1560
+ // +1 baris/ke atas (konten lama), -1/ke bawah (konten baru).
1561
+ this.scrollRows(this.autoScrollDir)
1562
+ }, 60)
1563
+ try {
1564
+ ;(this.autoScrollTimer as unknown as { unref?: () => void }).unref?.()
1565
+ } catch {}
1566
+ }
1567
+
1568
+ private stopAutoScroll(): void {
1569
+ if (this.autoScrollTimer !== undefined) {
1570
+ clearInterval(this.autoScrollTimer)
1571
+ this.autoScrollTimer = undefined
1572
+ }
1573
+ }
1574
+
1575
+ /** Deteksi tepi viewport dari posisi mouse dan nyalakan/matikan auto-scroll. */
1576
+ private updateAutoScroll(layout: FrameLayout, key: Extract<PromptKey, { type: "mouse" }>): void {
1577
+ if (!this.selection?.dragging) {
1578
+ this.stopAutoScroll()
1579
+ return
1580
+ }
1581
+ const n = layout.transcriptRows.length
1582
+ if (n === 0) {
1583
+ this.stopAutoScroll()
1584
+ return
1585
+ }
1586
+ const rowIndex = key.y - 1 - layout.transcriptTop
1587
+ if (rowIndex <= 0) this.startAutoScroll(1, key.x)
1588
+ else if (rowIndex >= n - 1) this.startAutoScroll(-1, key.x)
1589
+ else this.stopAutoScroll()
1590
+ }
1591
+
1279
1592
  private copySelection(): void {
1280
1593
  const selection = this.selection
1281
1594
  if (!selection) return
@@ -1285,7 +1598,7 @@ export class TuiApp {
1285
1598
  this.paintCurrent()
1286
1599
  return
1287
1600
  }
1288
- if (text.length > MAX_SELECTION_CHARS) {
1601
+ if (text.length > MAX_SELECTION_CHARS || utf8ByteLength(text) > MAX_SELECTION_BYTES) {
1289
1602
  this.transcript.pushInfo([c.warning(t("tui.selectionTooLarge"))])
1290
1603
  this.paintCurrent()
1291
1604
  return
@@ -1344,7 +1657,7 @@ export class TuiApp {
1344
1657
  (!this.transcript.hasSource(this.selection.anchor.id) ||
1345
1658
  !this.transcript.hasSource(this.selection.focus.id) ||
1346
1659
  (!this.selection.dragging &&
1347
- !this.transcript.selectionText(this.selection.anchor, this.selection.focus)))
1660
+ this.transcript.selectionIsEmpty(this.selection.anchor, this.selection.focus)))
1348
1661
  ) {
1349
1662
  this.selection = null
1350
1663
  }
@@ -1359,7 +1672,7 @@ export class TuiApp {
1359
1672
  let cursorCol = 1
1360
1673
  let composerOffset = 0
1361
1674
  if (!busy && this.editing) {
1362
- const cursor = this.cursorIndex(width)
1675
+ const cursor = this.composerLayout(width)
1363
1676
  const winStart = Math.max(0, Math.min(allComposer.length - composerH, cursor.visIdx))
1364
1677
  composerOffset = winStart
1365
1678
  shownComposer = allComposer.slice(winStart, winStart + composerH)
@@ -1431,46 +1744,4 @@ export class TuiApp {
1431
1744
  screen.paint(layout.frame, layout.cursor)
1432
1745
  this.frames++
1433
1746
  }
1434
-
1435
- /**
1436
- * Indeks baris visual kursor (koordinat PENUH inputAll) + kolom 1-based.
1437
- * Wrap-aware; CJK/emoji dihitung per kolom via displayWidth.
1438
- */
1439
- private cursorIndex(cols: number): { visIdx: number; col: number } {
1440
- // Baris kursor dalam teks logis → petakan ke baris visual (wrap-aware).
1441
- const units = toGraphemes(this.state.line)
1442
- const before = units.slice(0, Math.max(0, Math.min(this.state.cursor, units.length))).join("")
1443
- const logicalIdx = before.split("\n").length - 1
1444
- const lastLine = before.split("\n").pop() ?? ""
1445
- const prefix = logicalIdx === 0 ? PROMPT_FIRST : PROMPT_CONT
1446
- const targetWidth = displayWidth(prefix) + displayWidth(lastLine)
1447
- const w = Math.max(10, cols)
1448
- // Baris visual ke berapa (dari atas blok input) posisi kursor berada.
1449
- let visIdx = 0
1450
- const logical = this.state.line.split("\n")
1451
- for (let li = 0; li < logical.length; li++) {
1452
- const full = `${li === 0 ? PROMPT_FIRST : PROMPT_CONT}${logical[li] ?? ""}`
1453
- const wrapped = chunkByWidth(full, w)
1454
- const n = Math.max(1, wrapped.length)
1455
- if (li < logicalIdx) {
1456
- visIdx += n
1457
- continue
1458
- }
1459
- // Baris kursor: kolom ke-n dalam wrap.
1460
- let acc = 0
1461
- for (let wi = 0; wi < n; wi++) {
1462
- const ww = displayWidth(wrapped[wi] ?? "")
1463
- if (targetWidth < acc + ww || wi === n - 1) {
1464
- visIdx += wi
1465
- // Kolom 1-based dalam baris visual — SAMA untuk baris tengah
1466
- // maupun terakhir (dulu baris tengah selalu diparkir di EOL).
1467
- return { visIdx, col: Math.max(1, targetWidth - acc + 1) }
1468
- }
1469
- acc += ww
1470
- }
1471
- visIdx += n - 1
1472
- break
1473
- }
1474
- return { visIdx, col: 1 }
1475
- }
1476
1747
  }