minicode-ai 0.11.1 → 0.13.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.
Files changed (222) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/minicode.js +6 -0
  15. package/cli/recovery-warning.ts +115 -0
  16. package/cli/router.ts +32 -1
  17. package/cli/setup.ts +2332 -171
  18. package/cli/tui.ts +113 -7
  19. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  20. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  21. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  22. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  23. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  24. package/docs/OUTPUT_UX_RULES.md +449 -0
  25. package/docs/PLAN_UIUX_V6.md +2 -2
  26. package/docs/README.md +4 -3
  27. package/docs/TERMINAL_CONTRACT.md +278 -71
  28. package/docs/architecture.md +89 -7
  29. package/docs/changelog.md +1 -1
  30. package/docs/choosing-mode.md +2 -2
  31. package/docs/cli.md +9 -5
  32. package/docs/concepts.md +1 -1
  33. package/docs/contributing.md +9 -2
  34. package/docs/environment.md +6 -2
  35. package/docs/exec.md +46 -5
  36. package/docs/memory-sessions.md +2 -0
  37. package/docs/policy-sandbox.md +1 -1
  38. package/docs/pricing-budget.md +1 -1
  39. package/docs/quickstart.md +2 -2
  40. package/docs/repl.md +6 -2
  41. package/docs/security-model.md +1 -1
  42. package/docs/security.md +1 -1
  43. package/docs/skills.md +2 -2
  44. package/docs/terminal.md +9 -5
  45. package/docs/tools.md +1 -1
  46. package/package.json +36 -6
  47. package/src/app/session.ts +261 -15
  48. package/src/app/tool-layer.ts +94 -7
  49. package/src/daemon/approvals.ts +361 -0
  50. package/src/daemon/capability.ts +145 -0
  51. package/src/daemon/children.ts +142 -0
  52. package/src/daemon/client.ts +267 -0
  53. package/src/daemon/control.ts +350 -0
  54. package/src/daemon/discovery.ts +234 -0
  55. package/src/daemon/feed.ts +155 -0
  56. package/src/daemon/framing.ts +94 -0
  57. package/src/daemon/host.ts +316 -0
  58. package/src/daemon/protocol.ts +217 -0
  59. package/src/daemon/resource.ts +170 -0
  60. package/src/daemon/sanitize.ts +57 -0
  61. package/src/daemon/server.ts +627 -0
  62. package/src/daemon/store.ts +317 -0
  63. package/src/daemon/subscription.ts +270 -0
  64. package/src/daemon/telemetry.ts +81 -0
  65. package/src/hooks/run.ts +12 -1
  66. package/src/lib/atomic-write.ts +29 -3
  67. package/src/lib/db-path.ts +26 -0
  68. package/src/lib/keystore.ts +544 -42
  69. package/src/lib/net.ts +43 -1
  70. package/src/lib/safe-open.ts +116 -1
  71. package/src/lib/session-id.ts +15 -0
  72. package/src/lsp/client.ts +123 -5
  73. package/src/mcp/client.ts +139 -17
  74. package/src/mcp/server.ts +177 -50
  75. package/src/mcp/transport.ts +16 -19
  76. package/src/memory/vector.ts +770 -55
  77. package/src/policy/allowlist.ts +14 -2
  78. package/src/policy/bash-guard.ts +105 -10
  79. package/src/policy/compaction.ts +82 -5
  80. package/src/policy/consequence-engine.ts +220 -0
  81. package/src/policy/context.ts +132 -0
  82. package/src/policy/executor.ts +187 -121
  83. package/src/policy/no-progress.ts +559 -0
  84. package/src/policy/permission.ts +4 -8
  85. package/src/policy/pricing.ts +17 -3
  86. package/src/policy/scrub.ts +69 -2
  87. package/src/policy/tool-contract.ts +515 -0
  88. package/src/policy/usage.ts +310 -24
  89. package/src/policy/verifier.ts +6 -3
  90. package/src/policy/work-mode.ts +182 -0
  91. package/src/presentation/adapter.ts +533 -26
  92. package/src/presentation/events.ts +151 -0
  93. package/src/presentation/model.ts +180 -27
  94. package/src/presentation/projection.ts +858 -0
  95. package/src/presentation/reducer.ts +645 -310
  96. package/src/presentation/store.ts +12 -7
  97. package/src/providers/anthropic.ts +18 -10
  98. package/src/providers/responses.ts +2 -2
  99. package/src/runtime/capability.ts +409 -0
  100. package/src/runtime/child-execution.ts +274 -0
  101. package/src/runtime/composition.ts +958 -0
  102. package/src/runtime/dispatch.ts +591 -0
  103. package/src/runtime/execution-backend.ts +632 -0
  104. package/src/runtime/execution-events.ts +272 -0
  105. package/src/runtime/execution-id.ts +230 -0
  106. package/src/runtime/execution-journal.ts +926 -0
  107. package/src/runtime/execution-kernel.ts +456 -0
  108. package/src/runtime/execution-registry.ts +379 -0
  109. package/src/runtime/process-supervision.ts +276 -0
  110. package/src/runtime/production-execution.ts +551 -0
  111. package/src/runtime/production-runtime.ts +217 -0
  112. package/src/runtime/recovery-safety.ts +70 -0
  113. package/src/runtime/recovery.ts +477 -0
  114. package/src/runtime/runtime-capabilities.ts +179 -0
  115. package/src/runtime/runtime-diagnostics.ts +141 -0
  116. package/src/runtime/runtime-host.ts +365 -0
  117. package/src/runtime/runtime-status-facts.ts +222 -0
  118. package/src/runtime/runtime-status-provider.ts +74 -0
  119. package/src/runtime/runtime-status.ts +459 -0
  120. package/src/runtime/runtime-task-admission.ts +101 -0
  121. package/src/runtime/supervisor.ts +444 -0
  122. package/src/session/authority.ts +168 -0
  123. package/src/session/checkpoint.ts +88 -1
  124. package/src/session/context-adapter.ts +251 -0
  125. package/src/session/context-assembly.ts +242 -0
  126. package/src/session/context-identity.ts +389 -0
  127. package/src/session/context-projection.ts +248 -0
  128. package/src/session/context-selector.ts +500 -0
  129. package/src/session/cross-session-adoption.ts +249 -0
  130. package/src/session/full-history-fold.ts +171 -0
  131. package/src/session/identity.ts +192 -0
  132. package/src/session/journal.ts +805 -102
  133. package/src/session/open-work-intent.ts +732 -0
  134. package/src/session/open-work.ts +767 -0
  135. package/src/session/pending-tools.ts +94 -0
  136. package/src/session/persistence.ts +3569 -127
  137. package/src/session/runtime-header.ts +208 -0
  138. package/src/session/shadow-git.ts +13 -5
  139. package/src/session/verification.ts +1623 -0
  140. package/src/task/assignment.ts +136 -0
  141. package/src/task/autonomous-adapter.ts +168 -0
  142. package/src/task/autonomous-context.ts +630 -0
  143. package/src/task/autonomous-policy.ts +490 -0
  144. package/src/task/continuity.ts +179 -0
  145. package/src/task/execution-cancellation.ts +165 -0
  146. package/src/task/graph-validate.ts +379 -0
  147. package/src/task/graph.ts +305 -0
  148. package/src/task/identity.ts +230 -0
  149. package/src/task/model.ts +417 -0
  150. package/src/task/production-scheduler.ts +293 -0
  151. package/src/task/readiness.ts +229 -0
  152. package/src/task/scheduler-observability.ts +387 -0
  153. package/src/task/scheduler.ts +1197 -0
  154. package/src/task/scheduling-policy.ts +165 -0
  155. package/src/task/session-authority.ts +148 -0
  156. package/src/task/session-ownership.ts +211 -0
  157. package/src/task/store.ts +2887 -0
  158. package/src/task/sync.ts +343 -0
  159. package/src/task/trigger.ts +260 -0
  160. package/src/tools/bash.ts +377 -211
  161. package/src/tools/code_run.ts +1 -1
  162. package/src/tools/delete_file.ts +1 -1
  163. package/src/tools/edit.ts +33 -6
  164. package/src/tools/evidence.ts +30 -0
  165. package/src/tools/git.ts +4 -4
  166. package/src/tools/glob.ts +12 -3
  167. package/src/tools/grep.ts +1 -1
  168. package/src/tools/lsp.ts +4 -4
  169. package/src/tools/mcp_call.ts +11 -4
  170. package/src/tools/memory.ts +153 -18
  171. package/src/tools/move_file.ts +1 -1
  172. package/src/tools/patch.ts +1 -1
  173. package/src/tools/read_file.ts +1 -1
  174. package/src/tools/read_image.ts +1 -1
  175. package/src/tools/submit_result.ts +1 -1
  176. package/src/tools/task.ts +437 -41
  177. package/src/tools/todo.ts +662 -35
  178. package/src/tools/web_fetch.ts +4 -2
  179. package/src/tools/web_search.ts +9 -3
  180. package/src/tools/write_file.ts +1 -1
  181. package/src/ui/assistant/simple.ts +123 -50
  182. package/src/ui/assistant/turn-status.ts +17 -3
  183. package/src/ui/contract.ts +184 -0
  184. package/src/ui/footer.ts +52 -19
  185. package/src/ui/i18n/en.ts +58 -6
  186. package/src/ui/i18n/id.ts +58 -6
  187. package/src/ui/input/prompt-engine.ts +120 -25
  188. package/src/ui/render/errors.ts +39 -1
  189. package/src/ui/render/markdown-table.ts +455 -0
  190. package/src/ui/render/markdown.ts +22 -1
  191. package/src/ui/render/table-grid.ts +184 -0
  192. package/src/ui/render/table.ts +15 -76
  193. package/src/ui/runtime/screen.ts +7 -2
  194. package/src/ui/runtime/statusline.ts +25 -6
  195. package/src/ui/tui/app.ts +507 -169
  196. package/src/ui/tui/transcript.ts +531 -89
  197. package/vendor/minicore/VENDOR.md +1 -1
  198. package/vendor/minicore/src/core/budget.ts +25 -25
  199. package/vendor/minicore/src/core/compact.ts +75 -75
  200. package/vendor/minicore/src/core/errors.ts +59 -59
  201. package/vendor/minicore/src/core/events.ts +73 -73
  202. package/vendor/minicore/src/core/executor.ts +139 -139
  203. package/vendor/minicore/src/core/history.ts +31 -31
  204. package/vendor/minicore/src/core/index.ts +41 -41
  205. package/vendor/minicore/src/core/loop.ts +355 -355
  206. package/vendor/minicore/src/core/permission.ts +22 -22
  207. package/vendor/minicore/src/core/provider.ts +39 -39
  208. package/vendor/minicore/src/core/recovery.ts +35 -35
  209. package/vendor/minicore/src/core/session.ts +327 -327
  210. package/vendor/minicore/src/core/snapshot.ts +146 -146
  211. package/vendor/minicore/src/core/tokens.ts +107 -107
  212. package/vendor/minicore/src/core/tool.ts +115 -115
  213. package/vendor/minicore/src/core/types.ts +50 -50
  214. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  215. package/AGENTS.md +0 -45
  216. package/PLAN.md +0 -491
  217. package/docs/ARCHITECTURE.html +0 -1248
  218. package/docs/CONTROL-PLANE-MAP.md +0 -139
  219. package/docs/HARNESS.md +0 -150
  220. package/docs/SUMMARY.md +0 -52
  221. package/docs/UI_RENDER_PIPELINE.md +0 -169
  222. package/docs/USAGE.md +0 -11
package/src/ui/tui/app.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  // Batas lapisan: semua yang berbau sesi/model/turn datang via TuiHost yang
9
9
  // di-inject dari cli/ (composition root). src/ui TAK BOLEH impor cli/.
10
10
  import type { UiBus, UiPresentationActivity } from "../contract.ts"
11
- import { type FooterStatus, renderFooter } from "../footer.ts"
11
+ import { type FooterStatus, renderFooter, type TimerHighlight } from "../footer.ts"
12
12
  import { t } from "../i18n/locale.ts"
13
13
  import {
14
14
  applyKey,
@@ -22,18 +22,19 @@ import {
22
22
  type PromptState,
23
23
  toGraphemes,
24
24
  } from "../input/prompt-engine.ts"
25
- import { sanitizeAnsiLine } from "../render/sanitize.ts"
25
+ import { formatError } from "../render/errors.ts"
26
+ import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
26
27
  import { c } from "../render/theme.ts"
27
- import { chunkByWidth, displayWidth, truncateToWidth } from "../render/width.ts"
28
- import { motionReduced } from "../runtime/motion.ts"
29
28
  import {
30
- type AltScreen,
31
- forceRestoreScreenForSignal,
32
- openAltScreen,
33
- SYNC_UPDATE_END,
34
- SYNC_UPDATE_START,
35
- } from "../runtime/screen.ts"
36
- import type { Transcript } from "./transcript.ts"
29
+ charWidth,
30
+ chunkByWidth,
31
+ displayWidth,
32
+ escapeLength,
33
+ truncateToWidth,
34
+ } from "../render/width.ts"
35
+ import { motionReduced } from "../runtime/motion.ts"
36
+ import { type AltScreen, forceRestoreScreenForSignal, openAltScreen } from "../runtime/screen.ts"
37
+ import type { Transcript, TranscriptPoint, TranscriptRow } from "./transcript.ts"
37
38
 
38
39
  export interface TuiStatusSnapshot {
39
40
  footer: FooterStatus
@@ -53,8 +54,9 @@ export interface TuiHost {
53
54
  * sebagai baris error (tak ada jalur diam).
54
55
  */
55
56
  submit(text: string): Promise<{ quit?: boolean } | undefined>
56
- /** Batalkan turn yang berjalan (Esc/Ctrl+C saat busy). */
57
+ /** Batalkan turn yang berjalan (Esc saat busy). */
57
58
  abort(): void
59
+ copySelection(text: string): boolean
58
60
  /** Putar mode permission (Tab / Shift+Tab). */
59
61
  cycleMode(dir: 1 | -1): void
60
62
  /** Toggle compact / reasoning (Ctrl+O / Ctrl+T). */
@@ -77,14 +79,55 @@ const MIN_COLS = 20
77
79
 
78
80
  const PROMPT_FIRST = "minicode › "
79
81
  const PROMPT_CONT = " · "
80
- type ActivityKind = "working" | "thinking" | "tool" | "stopping"
82
+ const TIMER_TEXT = "00.00.00"
83
+ const DOT_INTERVAL_MS = 200
84
+ const DOT_PHASES = ["...", "..", ".", ".."] as const
85
+ const MOUSE_DRAG_ON = "\x1b[?1002h\x1b[?1006h"
86
+ const MOUSE_WHEEL_ON = "\x1b[?1000h\x1b[?1006h"
87
+ const MOUSE_OFF = "\x1b[?1006l\x1b[?1002l\x1b[?1000l"
88
+ const MAX_SELECTION_CHARS = 200_000
89
+ type MouseMode = "off" | "wheel" | "drag"
90
+
91
+ function mouseSelectionEnabled(): boolean {
92
+ const value = process.env.MINICODE_MOUSE_SELECTION?.toLowerCase()
93
+ return value !== "0" && value !== "false" && value !== "off" && value !== "no"
94
+ }
95
+
96
+ export function thinkingDots(now = Date.now(), startedAt = now, reduced = motionReduced()): string {
97
+ if (reduced) return "..."
98
+ const elapsed = Math.max(0, now - startedAt)
99
+ return DOT_PHASES[Math.floor(elapsed / DOT_INTERVAL_MS) % DOT_PHASES.length]!
100
+ }
81
101
 
82
- function formatElapsed(ms: number): string {
102
+ export function formatTimer(ms: number): string {
83
103
  const seconds = Math.max(0, Math.floor(ms / 1000))
84
- if (seconds < 60) return `${seconds}s`
85
- const minutes = Math.floor(seconds / 60)
86
- if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`
87
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`
104
+ const hours = Math.floor(seconds / 3600)
105
+ const minutes = Math.floor((seconds % 3600) / 60)
106
+ const rest = seconds % 60
107
+ return `${String(hours).padStart(2, "0")}.${String(minutes).padStart(2, "0")}.${String(rest).padStart(2, "0")}`
108
+ }
109
+
110
+ export function timerHighlight(ms: number): TimerHighlight {
111
+ const seconds = Math.max(0, Math.floor(ms / 1000))
112
+ if (seconds >= 3600) return "hours"
113
+ if (seconds >= 60) return "minutes"
114
+ return "seconds"
115
+ }
116
+
117
+ interface FrameLayout {
118
+ frame: string[]
119
+ cursor: { row: number; col: number }
120
+ transcriptRows: TranscriptRow[]
121
+ transcriptTop: number
122
+ composerTop: number
123
+ composerLines: string[]
124
+ composerOffset: number
125
+ }
126
+
127
+ interface SelectionState {
128
+ anchor: TranscriptPoint
129
+ focus: TranscriptPoint
130
+ dragging: boolean
88
131
  }
89
132
 
90
133
  interface RawStdin {
@@ -96,19 +139,67 @@ interface RawStdin {
96
139
  isTTY?: boolean
97
140
  }
98
141
 
142
+ function highlightColumns(text: string, start: number, end: number): string {
143
+ if (end <= start) return text
144
+ let out = ""
145
+ let column = 0
146
+ let active = false
147
+ let i = 0
148
+ while (i < text.length) {
149
+ if (text[i] === "\x1b") {
150
+ const length = escapeLength(text, i)
151
+ if (length > 0) {
152
+ out += text.slice(i, i + length)
153
+ if (active) out += "\x1b[7m"
154
+ i += length
155
+ continue
156
+ }
157
+ }
158
+ const codePoint = text.codePointAt(i)!
159
+ const char = String.fromCodePoint(codePoint)
160
+ const width = charWidth(codePoint)
161
+ const next = column + width
162
+ const inside = column < end && next > start
163
+ if (inside && !active) {
164
+ out += "\x1b[7m"
165
+ active = true
166
+ } else if (!inside && active) {
167
+ out += "\x1b[27m"
168
+ active = false
169
+ }
170
+ out += char
171
+ column = next
172
+ i += char.length
173
+ }
174
+ if (active) out += "\x1b[27m"
175
+ return out
176
+ }
177
+
178
+ function graphemeOffsetAtColumn(text: string, column: number): number {
179
+ const target = Math.max(0, column)
180
+ let used = 0
181
+ const units = toGraphemes(text)
182
+ for (let i = 0; i < units.length; i++) {
183
+ const width = displayWidth(units[i]!)
184
+ if (target <= used + width / 2) return i
185
+ used += width
186
+ if (target <= used) return i + 1
187
+ }
188
+ return units.length
189
+ }
190
+
99
191
  export class TuiApp {
100
192
  private state: PromptState = createState()
101
193
  private scrollBack = 0
102
194
  private history: string[] = []
103
195
  private histIdx = -1
104
196
  private draft = ""
197
+ private editing = true
105
198
  private busy = false
106
- private tick = 0
199
+ private thinkingActive = false
107
200
  private turnStartedAt = 0
108
- private activityKind: ActivityKind = "working"
109
- private textSeen = false
110
201
  private activityTimer: ReturnType<typeof setTimeout> | undefined
111
- /** Timestamp abort terakhir (ms) — deteksi double-tap Esc/Ctrl+C = quit. */
202
+ /** Timestamp abort terakhir (ms) — deteksi double-tap Esc = quit. */
112
203
  private lastAbortAt = 0
113
204
  /** Hint "tekan lagi untuk keluar" tampil sekali setelah abort pertama. */
114
205
  private abortHintOn = false
@@ -137,6 +228,10 @@ export class TuiApp {
137
228
  private stdin: RawStdin | null = null
138
229
  /** True setelah releaseTerminal (spawn anak): paint/repaint ditahan. */
139
230
  private released = false
231
+ private mouseMode: MouseMode = "off"
232
+ private selection: SelectionState | null = null
233
+ private lastLayout: FrameLayout | null = null
234
+ private onExit: (() => void) | null = null
140
235
  /**
141
236
  * Langganan bus untuk repaint live (streaming jawaban, ledger tool,
142
237
  * thinking): TANPA ini layar buta selama turn — teks baru hanya tampil
@@ -228,6 +323,7 @@ export class TuiApp {
228
323
  try {
229
324
  stdin.removeListener("data", this.onData!)
230
325
  } catch {}
326
+ this.setMouseMode("off")
231
327
  forceRestoreScreenForSignal()
232
328
  // exit() eksplisit memicu handler "exit" yang tersisa (spinner,
233
329
  // turn-status) — best-effort sinkron. 128+n = konvensi "mati oleh
@@ -253,6 +349,12 @@ export class TuiApp {
253
349
  } catch {
254
350
  this.onSignalInt = null
255
351
  }
352
+ this.onExit = () => this.setMouseMode("off")
353
+ try {
354
+ process.on("exit", this.onExit)
355
+ } catch {
356
+ this.onExit = null
357
+ }
256
358
  // Repaint live mengikuti event bus (stream teks, ledger, thinking).
257
359
  // Suspend menahan repaint (popup melukis sendiri); quit menahan semua.
258
360
  const requestPaint = () => {
@@ -280,31 +382,29 @@ export class TuiApp {
280
382
  } catch {}
281
383
  }
282
384
  sub("turn:started", () => {
385
+ this.thinkingActive = false
283
386
  this.turnStartedAt = Date.now()
284
- if (this.activityKind !== "stopping") this.activityKind = "working"
285
- this.textSeen = false
387
+ this.startActivityClock()
286
388
  })
287
389
  sub("provider:extension", (event: { kind?: string }) => {
288
- if (event?.kind === "reasoning" && !this.textSeen && this.activityKind !== "stopping") {
289
- this.activityKind = "thinking"
290
- }
390
+ if (event?.kind === "reasoning") this.thinkingActive = true
291
391
  })
292
392
  sub("provider:text", () => {
293
- if (this.activityKind !== "stopping") this.activityKind = "working"
294
- this.textSeen = true
393
+ this.thinkingActive = false
295
394
  })
296
395
  sub("execution:started", () => {
297
- if (this.activityKind !== "stopping") this.activityKind = "tool"
298
- this.textSeen = false
396
+ this.thinkingActive = false
299
397
  })
300
398
  sub("execution:completed", () => {
301
- if (this.activityKind !== "stopping") this.activityKind = "working"
302
- this.textSeen = false
399
+ this.thinkingActive = false
400
+ })
401
+ sub("turn:completed", () => {
402
+ this.thinkingActive = false
303
403
  })
304
- sub("turn:completed")
305
404
  sub("context:compacted")
306
405
  this.tailSize = this.transcript.total()
307
406
  this.scrollBase = this.tailSize
407
+ this.setMouseMode(mouseSelectionEnabled() ? "drag" : "off")
308
408
  this.paint(screen)
309
409
  await done
310
410
  // Cleanup: urutan penting — lepas listener dulu agar byte liar pasca-quit
@@ -342,6 +442,12 @@ export class TuiApp {
342
442
  } catch {}
343
443
  this.onSignalInt = null
344
444
  }
445
+ if (this.onExit) {
446
+ try {
447
+ process.off("exit", this.onExit)
448
+ } catch {}
449
+ this.onExit = null
450
+ }
345
451
  this.stdin = null
346
452
  this.pump.dispose()
347
453
  this.pump = null
@@ -355,6 +461,7 @@ export class TuiApp {
355
461
  // Tutup layar AKTIF (bisa diganti reacquireTerminal setelah spawn
356
462
  // gagal — menutup handle run() yang basi akan meninggalkan alt-screen
357
463
  // yatim; close() idempoten sehingga aman dua kali).
464
+ this.setMouseMode("off")
358
465
  this.currentScreen?.close()
359
466
  } catch {}
360
467
  this.currentScreen = null
@@ -364,14 +471,13 @@ export class TuiApp {
364
471
  // ── Penanganan key ──
365
472
 
366
473
  private requestAbort(): void {
367
- if (!this.busy) return
474
+ if (!this.isBusy()) return
368
475
  try {
369
476
  this.host.abort()
370
477
  } catch {}
371
478
  const now = Date.now()
372
479
  const doubleTap = now - this.lastAbortAt < 1500
373
480
  if (!doubleTap) {
374
- this.activityKind = "stopping"
375
481
  this.abortHintOn = true
376
482
  this.startActivityClock()
377
483
  }
@@ -394,6 +500,14 @@ export class TuiApp {
394
500
  }
395
501
 
396
502
  private handleKey(key: PromptKey): void {
503
+ if (key.type === "mouse") {
504
+ this.handleMouse(key)
505
+ return
506
+ }
507
+ if (key.type === "wheelup" || key.type === "wheeldown") {
508
+ this.scrollBy(key.type === "wheelup" ? 0.5 : -0.5)
509
+ return
510
+ }
397
511
  // Scroll SELALU tersedia (menu buka/tutup, busy/idle, layar menciut) —
398
512
  // di-intercept sebelum engine supaya tak jadi histori maupun teks.
399
513
  // Dulu di bawah gate tooSmall: terminal menciut + turn busy = tak bisa
@@ -426,24 +540,34 @@ export class TuiApp {
426
540
  this.applyEngine(key)
427
541
  return
428
542
  }
429
- // Abort/batal: Esc & Ctrl+C — berlaku juga saat layar menciut (jalan
430
- // keluar saat terminal mengecil di tengah turn busy).
431
- // Jalan keluar saat abort macet (provider/tool non-kooperatif abaikan
432
- // sinyal): Esc/Ctrl+C KEDUA dalam 1.5 dtk, atau Ctrl+D baris-kosong,
433
- // = abort + quit. Tanpa ini sesi hanya bisa dibunuh kill -9 (kontrak I14).
434
- if (key.type === "esc" || key.type === "ctrl-c") {
435
- if (this.busy) {
543
+ if (key.type === "ctrl-c") {
544
+ if (this.selection && !this.selection.dragging) this.copySelection()
545
+ return
546
+ }
547
+ // Abort/batal: Esc — berlaku juga saat layar menciut (jalan keluar saat
548
+ // terminal mengecil di tengah turn busy). Jalan keluar saat abort macet
549
+ // (provider/tool non-kooperatif abaikan sinyal): Esc dua kali dalam 1.5 dtk,
550
+ // atau Ctrl+D baris-kosong, = abort + quit. Tanpa ini sesi hanya bisa
551
+ // dibunuh kill -9 (kontrak I14).
552
+ if (key.type === "esc" && this.selection) {
553
+ this.selection = null
554
+ this.paintCurrent()
555
+ return
556
+ }
557
+ if (key.type === "esc") {
558
+ if (this.isBusy()) {
436
559
  this.requestAbort()
437
560
  return
438
561
  }
439
562
  if (this.tooSmall()) return
440
- if (key.type === "esc" && this.state.menuOpen) {
563
+ if (this.state.menuOpen) {
441
564
  this.applyEngine(key)
442
565
  return
443
566
  }
444
- if (this.state.line) {
567
+ if (this.state.line || this.editing) {
445
568
  this.state = createState()
446
569
  this.histIdx = -1
570
+ this.editing = false
447
571
  this.paintCurrent()
448
572
  }
449
573
  return
@@ -455,10 +579,10 @@ export class TuiApp {
455
579
  if (key.type === "ctrl-d") this.quit()
456
580
  return
457
581
  }
458
- // Saat turn berjalan SEMUA input dibekukan kecuali abort (Esc/Ctrl+C),
459
- // scroll (PgUp/PgDn di atas), dan Ctrl+D baris-kosong (= abort + quit,
582
+ // Saat turn berjalan SEMUA input dibekukan kecuali abort (Esc), scroll
583
+ // (mouse wheel/PgUp/PgDn di atas), dan Ctrl+D baris-kosong (= abort + quit,
460
584
  // jalan keluar saat abort macet — kontrak I14).
461
- if (this.busy) {
585
+ if (this.isBusy()) {
462
586
  if (key.type === "ctrl-d" && !this.state.line) {
463
587
  try {
464
588
  this.host.abort()
@@ -530,6 +654,7 @@ export class TuiApp {
530
654
  }
531
655
 
532
656
  private applyEngine(key: PromptKey): void {
657
+ if (["char", "backspace", "delete", "enter", "ctrl-j"].includes(key.type)) this.selection = null
533
658
  const hints = (line: string) => (line.startsWith("/") ? this.host.listCommands(line) : [])
534
659
  const { state, action } = applyKey(this.state, key, hints)
535
660
  this.state = state
@@ -538,6 +663,7 @@ export class TuiApp {
538
663
  } else if (action === "cancel") {
539
664
  // Engine cancel (ctrl-c/ctrl-d) sudah ditangani di atas; tak terjangkau.
540
665
  } else if (action === "render" || action === "none") {
666
+ if (action === "render" && key.type === "char") this.editing = true
541
667
  // Ketikan baru = kembali ke ekor (I18); stream turn TIDAK me-reset
542
668
  // (user yang sedang membaca ke atas tak dirampas).
543
669
  if (key.type === "char" || key.type === "backspace" || key.type === "delete") {
@@ -551,6 +677,7 @@ export class TuiApp {
551
677
  const line = rawLine.trim()
552
678
  this.state = createState()
553
679
  this.histIdx = -1
680
+ this.editing = false
554
681
  this.followTail()
555
682
  this.abortHintOn = false
556
683
  if (!line) {
@@ -560,9 +687,8 @@ export class TuiApp {
560
687
  this.rememberHistory(line)
561
688
  this.transcript.pushUser(rawLine)
562
689
  this.busy = true
690
+ this.thinkingActive = false
563
691
  this.turnStartedAt = Date.now()
564
- this.activityKind = "working"
565
- this.textSeen = false
566
692
  this.lastAbortAt = 0
567
693
  this.startActivityClock()
568
694
  this.paintCurrent()
@@ -570,12 +696,15 @@ export class TuiApp {
570
696
  const res = await this.host.submit(line)
571
697
  if (res?.quit) this.quit()
572
698
  } catch (e) {
573
- this.transcript.pushError(e instanceof Error ? e.message : String(e))
699
+ // [P0 UI Security] Pesan error = TEKS TAK DIPERCAYA: bisa memuat body
700
+ // provider, header `Authorization: Bearer …`, atau escape ANSI. Jalur
701
+ // lama `e.message` mentah membocorkan credential ke layar TUI — kini
702
+ // lewat formatter kanonik (redaksi credential + sanitasi + pemotongan).
703
+ this.transcript.pushError(formatError(e))
574
704
  } finally {
575
705
  this.busy = false
576
- this.activityKind = "working"
706
+ this.editing = true
577
707
  this.turnStartedAt = 0
578
- this.textSeen = false
579
708
  this.stopActivityClock()
580
709
  if (!this.quitRequested) this.paintCurrent()
581
710
  }
@@ -607,6 +736,9 @@ export class TuiApp {
607
736
  suspend(): void {
608
737
  if (!this.currentScreen || this.quitRequested) return
609
738
  if (this.suspended++ > 0) return
739
+ if (this.selection) this.selection.dragging = false
740
+ this.decoder.pending = []
741
+ this.setMouseMode("wheel")
610
742
  try {
611
743
  if (this.onData) this.stdin?.removeListener("data", this.onData)
612
744
  } catch {}
@@ -628,7 +760,8 @@ export class TuiApp {
628
760
  try {
629
761
  if (this.onData) this.stdin?.on("data", this.onData)
630
762
  } catch {}
631
- if (this.busy) this.startActivityClock()
763
+ this.setMouseMode(mouseSelectionEnabled() ? "drag" : "off")
764
+ if (this.isBusy()) this.startActivityClock()
632
765
  this.paintCurrent()
633
766
  }
634
767
 
@@ -648,9 +781,11 @@ export class TuiApp {
648
781
  this.stdin?.setRawMode(false)
649
782
  } catch {}
650
783
  try {
784
+ this.setMouseMode("off")
651
785
  this.currentScreen?.close()
652
786
  } catch {}
653
787
  this.currentScreen = null
788
+ this.lastLayout = null
654
789
  this.released = true
655
790
  }
656
791
 
@@ -667,10 +802,11 @@ export class TuiApp {
667
802
  if (!screen.ok) return false
668
803
  this.currentScreen = screen
669
804
  this.released = false
805
+ this.setMouseMode(!mouseSelectionEnabled() ? "off" : this.suspended > 0 ? "wheel" : "drag")
670
806
  try {
671
807
  this.stdin?.setRawMode(true)
672
808
  } catch {}
673
- if (this.busy) this.startActivityClock()
809
+ if (this.isBusy()) this.startActivityClock()
674
810
  this.paintCurrent()
675
811
  return true
676
812
  }
@@ -702,30 +838,24 @@ export class TuiApp {
702
838
  const cols = screen.cols
703
839
  const rows = screen.rows
704
840
  const snap = this.host.getStatus()
705
- const busy = this.busy || snap.busy
706
- const statusLine =
707
- renderFooter(
708
- {
709
- ...snap.footer,
710
- activity: this.activityText(snap),
711
- sparkFrame: busy && !motionReduced() ? this.tick : 0,
712
- },
713
- cols,
714
- )[0] ?? ""
715
- const menu = this.menuRows(rows, cols)
716
- const inputAll = this.inputRows(cols)
717
- const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
718
- const viewH = Math.max(1, rows - 1 - inputH - menu.length)
719
- const body = this.transcript.view(cols, viewH, this.scrollBack)
720
- const frame: string[] = [...body, ...menu, ...inputAll.slice(-inputH), statusLine]
721
- while (frame.length < rows) frame.unshift("")
722
- const dimmed = frame.slice(-rows).map((ln) => TuiApp.applyBackdropDim(ln))
841
+ const layout = this.buildLayout(rows, cols, snap)
842
+ this.lastLayout = layout
843
+ const dimmed = layout.frame.map((ln) => TuiApp.applyBackdropDim(ln))
723
844
  try {
724
845
  screen.paint(dimmed)
725
846
  } catch {}
726
847
  this.frames++
727
848
  }
728
849
 
850
+ private isBusy(): boolean {
851
+ if (this.busy) return true
852
+ try {
853
+ return this.host.getStatus().busy
854
+ } catch {
855
+ return false
856
+ }
857
+ }
858
+
729
859
  // ── Histori prompt (memori sesi; tak persist ke berkas REPL) ──
730
860
 
731
861
  private rememberHistory(line: string): void {
@@ -775,6 +905,7 @@ export class TuiApp {
775
905
  if (r.action !== "render" && r.action !== "none") break
776
906
  }
777
907
  this.state = s
908
+ this.editing = true
778
909
  this.paintCurrent()
779
910
  }
780
911
 
@@ -840,11 +971,11 @@ export class TuiApp {
840
971
  if (this.activityTimer || this.quitRequested) return
841
972
  const tick = () => {
842
973
  this.activityTimer = undefined
843
- if (!this.busy || this.quitRequested) return
974
+ if (!this.isBusy() || this.quitRequested) return
844
975
  if (this.suspended === 0 && !this.released) this.paintCurrent()
845
976
  this.startActivityClock()
846
977
  }
847
- this.activityTimer = setTimeout(tick, 200)
978
+ this.activityTimer = setTimeout(tick, DOT_INTERVAL_MS)
848
979
  try {
849
980
  ;(this.activityTimer as unknown as { unref?: () => void }).unref?.()
850
981
  } catch {}
@@ -857,27 +988,55 @@ export class TuiApp {
857
988
  }
858
989
  }
859
990
 
860
- private activityText(snap: TuiStatusSnapshot): string | undefined {
861
- if (!this.busy && !snap.busy) return undefined
862
- const elapsedStart = this.turnStartedAt || Date.now()
863
- if (this.activityKind === "stopping") {
864
- return `${t("app.stopping")} ${formatElapsed(Date.now() - elapsedStart)}`
865
- }
991
+ private activityStatus(snap: TuiStatusSnapshot): string {
866
992
  const activity = snap.pinnedActivity
867
- if (activity) {
868
- const name = sanitizeAnsiLine(activity.name || "tool")
869
- const target = activity.target ? ` ${sanitizeAnsiLine(activity.target)}` : ""
870
- const activityStart = Number.isFinite(activity.tsStart) ? activity.tsStart : elapsedStart
871
- return `${t("app.running")} ${name}${target} ${formatElapsed(Date.now() - activityStart)}`
872
- }
873
- const label = this.activityKind === "thinking" ? t("app.thinking") : t("app.working")
874
- return `${label} ${formatElapsed(Date.now() - elapsedStart)}`
993
+ if (!activity) return ""
994
+ const name = sanitizeAnsiLine(String(activity.name ?? ""))
995
+ const target = activity.target ? ` ${sanitizeAnsiLine(String(activity.target))}` : ""
996
+ return sanitizeAnsiLine(`${name}${target}`)
997
+ }
998
+
999
+ private activityRow(content: string, cols: number): string {
1000
+ const width = Math.max(1, Math.floor(cols) - 1)
1001
+ return truncateToWidth(sanitizeAnsiLine(content), width, "")
1002
+ }
1003
+
1004
+ private composerRows(
1005
+ cols: number,
1006
+ snap: TuiStatusSnapshot,
1007
+ busy: boolean,
1008
+ now: number,
1009
+ ): string[] {
1010
+ if (busy) {
1011
+ const start = this.turnStartedAt || now
1012
+ const status = this.activityStatus(snap)
1013
+ const content = this.thinkingActive ? thinkingDots(now, start) : status
1014
+ return [this.activityRow(content, cols)]
1015
+ }
1016
+ if (!this.editing) return [""]
1017
+ return this.inputRows(cols)
1018
+ }
1019
+
1020
+ private composerHeight(cols: number, busy = this.busy): number {
1021
+ if (busy || !this.editing) return 1
1022
+ return Math.min(MAX_INPUT_ROWS, Math.max(1, this.inputRows(cols).length))
875
1023
  }
876
1024
 
877
1025
  // ── Paint ──
878
1026
 
879
1027
  private currentScreen: AltScreen | null = null
880
1028
 
1029
+ private setMouseMode(mode: MouseMode): void {
1030
+ if (this.mouseMode === mode) return
1031
+ const sequence = mode === "drag" ? MOUSE_DRAG_ON : mode === "wheel" ? MOUSE_WHEEL_ON : MOUSE_OFF
1032
+ try {
1033
+ if (mode === "off" || this.mouseMode === "off") process.stdout.write(sequence)
1034
+ else if (mode === "drag") process.stdout.write(`\x1b[?1000l${sequence}`)
1035
+ else process.stdout.write(`\x1b[?1002l${sequence}`)
1036
+ this.mouseMode = mode
1037
+ } catch {}
1038
+ }
1039
+
881
1040
  private paintCurrent(): void {
882
1041
  if (this.currentScreen) this.paint(this.currentScreen)
883
1042
  }
@@ -892,19 +1051,18 @@ export class TuiApp {
892
1051
  }
893
1052
 
894
1053
  private viewportHeight(rows: number, cols: number): number {
895
- const inputH = this.inputHeight(cols)
896
- const menuH = this.menuHeight(rows, cols)
897
- return Math.max(1, rows - 1 - inputH - menuH)
1054
+ const busy = this.isBusy()
1055
+ const inputH = this.composerHeight(cols, busy)
1056
+ const menuH = this.menuHeight(rows, cols, busy)
1057
+ return Math.max(1, rows - 2 - inputH - menuH)
898
1058
  }
899
1059
 
900
1060
  private inputRows(cols: number): string[] {
1061
+ if (!this.editing) return []
901
1062
  const w = Math.max(10, cols)
902
1063
  const out: string[] = []
903
- // Baris kosong = placeholder redup (edukasi tanpa banjir): cara keluar
904
- // selalu terlihat (Ctrl+D), tanpa menuh-menuhi transkrip.
905
1064
  if (!this.state.line) {
906
- const hint = c.faint(truncateToWidth(t("app.placeholder"), w - PROMPT_FIRST.length))
907
- out.push(`${PROMPT_FIRST}${hint}`)
1065
+ out.push(PROMPT_FIRST)
908
1066
  return out
909
1067
  }
910
1068
  const logical = this.state.line.split("\n")
@@ -912,22 +1070,17 @@ export class TuiApp {
912
1070
  const prefix = idx === 0 ? PROMPT_FIRST : PROMPT_CONT
913
1071
  const full = `${prefix}${ln}`
914
1072
  const wrapped = chunkByWidth(full, w)
915
- // Baris logis kosong tetap menempati 1 baris visual.
916
1073
  if (!wrapped.length) out.push(full)
917
1074
  else for (const r of wrapped) out.push(r)
918
1075
  })
919
1076
  return out
920
1077
  }
921
1078
 
922
- private inputHeight(cols: number): number {
923
- return Math.min(MAX_INPUT_ROWS, Math.max(1, this.inputRows(cols).length))
924
- }
925
-
926
- private menuRows(rows: number, cols: number): string[] {
927
- if (!this.state.menuOpen || !this.state.line.startsWith("/")) return []
1079
+ private menuRows(rows: number, cols: number, busy = this.isBusy()): string[] {
1080
+ if (!this.editing || busy || !this.state.menuOpen || !this.state.line.startsWith("/")) return []
928
1081
  const hints = this.host.listCommands(this.state.line)
929
1082
  if (!hints.length) return []
930
- const room = Math.max(0, rows - 1 - this.inputHeight(cols) - 3)
1083
+ const room = Math.max(0, rows - 2 - this.composerHeight(cols, busy) - 3)
931
1084
  const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
932
1085
  const w = Math.max(10, cols)
933
1086
  const out: string[] = [c.muted(t("app.menuHeader"))]
@@ -941,8 +1094,252 @@ export class TuiApp {
941
1094
  return out.map((l) => chunkByWidth(l, w)[0] ?? "")
942
1095
  }
943
1096
 
944
- private menuHeight(rows: number, cols: number): number {
945
- return this.menuRows(rows, cols).length
1097
+ private menuHeight(rows: number, cols: number, busy = this.isBusy()): number {
1098
+ return this.menuRows(rows, cols, busy).length
1099
+ }
1100
+
1101
+ private selectedRange(row: TranscriptRow): { start: number; end: number } | null {
1102
+ const selection = this.selection
1103
+ if (!selection || !row.selectable || row.sourceId < 0) return null
1104
+ const first =
1105
+ this.transcript.comparePoints(selection.anchor, selection.focus) <= 0
1106
+ ? selection.anchor
1107
+ : selection.focus
1108
+ const last = first === selection.anchor ? selection.focus : selection.anchor
1109
+ const rowStart = { id: row.sourceId, offset: row.sourceStart }
1110
+ const rowEnd = { id: row.sourceId, offset: row.sourceEnd }
1111
+ if (this.transcript.comparePoints(last, rowStart) < 0) return null
1112
+ if (this.transcript.comparePoints(first, rowEnd) > 0) return null
1113
+ const start =
1114
+ first.id === row.sourceId ? Math.max(row.sourceStart, first.offset) : row.sourceStart
1115
+ const end = last.id === row.sourceId ? Math.min(row.sourceEnd, last.offset) : row.sourceEnd
1116
+ if (end <= start) return null
1117
+ return {
1118
+ start: this.transcript.columnAtOffset(row, start),
1119
+ end: this.transcript.columnAtOffset(row, end),
1120
+ }
1121
+ }
1122
+
1123
+ private scheduleSelectionPaint(): void {
1124
+ if (this.repaintTimer !== undefined) return
1125
+ this.repaintTimer = setTimeout(() => {
1126
+ this.repaintTimer = undefined
1127
+ if (!this.quitRequested && this.suspended === 0 && !this.released) this.paintCurrent()
1128
+ }, 16)
1129
+ try {
1130
+ ;(this.repaintTimer as unknown as { unref?: () => void }).unref?.()
1131
+ } catch {}
1132
+ }
1133
+
1134
+ private movePromptCursor(
1135
+ layout: FrameLayout,
1136
+ key: Extract<PromptKey, { type: "mouse" }>,
1137
+ ): boolean {
1138
+ if (this.isBusy() || !this.editing) return false
1139
+ const relativeRow = key.y - 1 - layout.composerTop
1140
+ const targetRow = layout.composerOffset + relativeRow
1141
+ if (relativeRow < 0 || targetRow < 0) return false
1142
+ const w = Math.max(10, process.stdout.columns || 80)
1143
+ const logical = this.state.line.split("\n")
1144
+ let rowIndex = 0
1145
+ let baseCodeUnits = 0
1146
+ for (let lineIndex = 0; lineIndex < logical.length; lineIndex++) {
1147
+ const line = logical[lineIndex] ?? ""
1148
+ const prefix = lineIndex === 0 ? PROMPT_FIRST : PROMPT_CONT
1149
+ const rows = chunkByWidth(`${prefix}${line}`, w)
1150
+ if (targetRow < rowIndex + rows.length) {
1151
+ const row = rows[targetRow - rowIndex] ?? ""
1152
+ const plain = stripSgr(sanitizeAnsi(row))
1153
+ const body = plain.startsWith(prefix) ? plain.slice(prefix.length) : plain
1154
+ const targetColumn = Math.max(
1155
+ 0,
1156
+ key.x - 1 - (plain.startsWith(prefix) ? displayWidth(prefix) : 0),
1157
+ )
1158
+ const local = graphemeOffsetAtColumn(body, targetColumn)
1159
+ const base = toGraphemes(this.state.line.slice(0, baseCodeUnits)).length
1160
+ this.state = { ...this.state, cursor: base + local }
1161
+ this.histIdx = -1
1162
+ this.editing = true
1163
+ this.selection = null
1164
+ this.paintCurrent()
1165
+ return true
1166
+ }
1167
+ rowIndex += rows.length
1168
+ baseCodeUnits += line.length + 1
1169
+ }
1170
+ return false
1171
+ }
1172
+
1173
+ private handleMouse(key: Extract<PromptKey, { type: "mouse" }>): void {
1174
+ if (key.action === "move" || (key.action !== "release" && key.button !== 0)) return
1175
+ const layout = this.lastLayout
1176
+ if (!layout) return
1177
+ const rowIndex = key.y - 1 - layout.transcriptTop
1178
+ const row = rowIndex >= 0 ? layout.transcriptRows[rowIndex] : undefined
1179
+ if (key.action === "press") {
1180
+ if (!row) {
1181
+ if (this.movePromptCursor(layout, key)) return
1182
+ this.selection = null
1183
+ this.paintCurrent()
1184
+ return
1185
+ }
1186
+ const point = this.transcript.pointAt(row, key.x - 1)
1187
+ if (!point) {
1188
+ this.selection = null
1189
+ this.paintCurrent()
1190
+ return
1191
+ }
1192
+ this.selection = { anchor: point, focus: point, dragging: true }
1193
+ this.paintCurrent()
1194
+ return
1195
+ }
1196
+ if (key.action === "drag") {
1197
+ if (!this.selection?.dragging || !row) return
1198
+ const point = this.transcript.pointAt(row, key.x - 1)
1199
+ if (!point) return
1200
+ this.selection.focus = point
1201
+ this.scheduleSelectionPaint()
1202
+ return
1203
+ }
1204
+ if (key.action === "release") {
1205
+ if (!this.selection?.dragging) return
1206
+ if (row) {
1207
+ const point = this.transcript.pointAt(row, key.x - 1)
1208
+ if (point) this.selection.focus = point
1209
+ }
1210
+ this.selection.dragging = false
1211
+ this.paintCurrent()
1212
+ }
1213
+ }
1214
+
1215
+ private copySelection(): void {
1216
+ const selection = this.selection
1217
+ if (!selection) return
1218
+ const text = this.transcript.selectionText(selection.anchor, selection.focus).trim()
1219
+ if (!text) {
1220
+ this.selection = null
1221
+ this.paintCurrent()
1222
+ return
1223
+ }
1224
+ if (text.length > MAX_SELECTION_CHARS) {
1225
+ this.transcript.pushInfo([c.warning(t("tui.selectionTooLarge"))])
1226
+ this.paintCurrent()
1227
+ return
1228
+ }
1229
+ let copied = false
1230
+ try {
1231
+ copied = this.host.copySelection(text)
1232
+ } catch {}
1233
+ if (copied) this.transcript.pushInfo([c.muted(t("tui.selectionCopied"))])
1234
+ else this.transcript.pushInfo([c.muted(t("tui.selectionCopyFailed"))])
1235
+ this.paintCurrent()
1236
+ }
1237
+
1238
+ private buildLayout(rows: number, cols: number, snap: TuiStatusSnapshot): FrameLayout {
1239
+ const height = Math.max(1, Math.floor(rows))
1240
+ const width = Math.max(1, Math.floor(cols))
1241
+ const busy = this.busy || snap.busy
1242
+ const now = Date.now()
1243
+ if (busy) {
1244
+ if (!this.turnStartedAt) this.turnStartedAt = now
1245
+ this.startActivityClock()
1246
+ } else {
1247
+ this.thinkingActive = false
1248
+ this.turnStartedAt = 0
1249
+ }
1250
+ const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
1251
+ const indicator: string[] = []
1252
+ if (busy && this.abortHintOn) indicator.push(c.warning(t("app.abortHint")))
1253
+ else if (newCount > 0) indicator.push(c.muted(t("app.newBelow", { n: newCount })))
1254
+
1255
+ const allMenu = this.menuRows(height, width, busy)
1256
+ const allComposer = this.composerRows(width, snap, busy, now)
1257
+ const contentBudget = Math.max(1, height - 3 - indicator.length)
1258
+ let menu = allMenu
1259
+ let composerH = Math.min(MAX_INPUT_ROWS, Math.max(1, allComposer.length))
1260
+ if (menu.length + composerH > contentBudget) {
1261
+ menu = menu.slice(0, Math.max(0, contentBudget - 1))
1262
+ composerH = Math.max(1, contentBudget - menu.length)
1263
+ }
1264
+ const viewH = Math.max(1, height - 2 - composerH - menu.length - indicator.length)
1265
+ let viewport = this.transcript.viewport(width, viewH, this.scrollBack)
1266
+ const curWrapped = viewport.totalRows
1267
+ if (this.scrollBack > 0 && this.lastWrapped > 0) {
1268
+ const nextScrollBack = Math.max(
1269
+ 0,
1270
+ Math.min(this.scrollBack + (curWrapped - this.lastWrapped), Math.max(0, curWrapped - 1)),
1271
+ )
1272
+ if (nextScrollBack !== this.scrollBack) {
1273
+ this.scrollBack = nextScrollBack
1274
+ viewport = this.transcript.viewport(width, viewH, this.scrollBack)
1275
+ }
1276
+ }
1277
+ this.lastWrapped = curWrapped
1278
+ if (
1279
+ this.selection &&
1280
+ (!this.transcript.hasSource(this.selection.anchor.id) ||
1281
+ !this.transcript.hasSource(this.selection.focus.id) ||
1282
+ (!this.selection.dragging &&
1283
+ !this.transcript.selectionText(this.selection.anchor, this.selection.focus)))
1284
+ ) {
1285
+ this.selection = null
1286
+ }
1287
+ const bodyRows = viewport.rows
1288
+ const body = bodyRows.map((row) => {
1289
+ const selected = this.selectedRange(row)
1290
+ return selected ? highlightColumns(row.text, selected.start, selected.end) : row.text
1291
+ })
1292
+
1293
+ let shownComposer: string[]
1294
+ let cursorRow: number
1295
+ let cursorCol = 1
1296
+ let composerOffset = 0
1297
+ if (!busy && this.editing) {
1298
+ const cursor = this.cursorIndex(width)
1299
+ const winStart = Math.max(0, Math.min(allComposer.length - composerH, cursor.visIdx))
1300
+ composerOffset = winStart
1301
+ shownComposer = allComposer.slice(winStart, winStart + composerH)
1302
+ cursorRow = viewH + menu.length + indicator.length + (cursor.visIdx - winStart) + 1
1303
+ cursorCol = cursor.col
1304
+ } else {
1305
+ shownComposer = allComposer.slice(0, composerH)
1306
+ cursorRow = viewH + menu.length + indicator.length + 1
1307
+ }
1308
+
1309
+ const started = this.turnStartedAt || now
1310
+ const sparkFrame =
1311
+ busy && !motionReduced() ? Math.max(1, Math.floor((now - started) / DOT_INTERVAL_MS) + 1) : 0
1312
+ const elapsed = now - started
1313
+ const timer = busy ? formatTimer(elapsed) : TIMER_TEXT
1314
+ const footer =
1315
+ renderFooter(
1316
+ {
1317
+ ...snap.footer,
1318
+ sparkFrame,
1319
+ timer,
1320
+ timerActive: busy,
1321
+ timerHighlight: timerHighlight(elapsed),
1322
+ },
1323
+ width,
1324
+ )[0] ?? ""
1325
+ const frame = [...body, ...menu, ...indicator, ...shownComposer, "", footer]
1326
+ const rawLength = frame.length
1327
+ const crop = Math.max(0, rawLength - height)
1328
+ const topPad = Math.max(0, height - rawLength)
1329
+ while (frame.length < height) frame.unshift("")
1330
+ const out = frame.slice(-height)
1331
+ return {
1332
+ frame: out,
1333
+ cursor: {
1334
+ row: Math.max(1, Math.min(height, cursorRow + topPad - crop)),
1335
+ col: Math.max(1, cursorCol),
1336
+ },
1337
+ transcriptRows: bodyRows,
1338
+ transcriptTop: topPad - crop,
1339
+ composerTop: topPad - crop + body.length + menu.length + indicator.length,
1340
+ composerLines: allComposer,
1341
+ composerOffset,
1342
+ }
946
1343
  }
947
1344
 
948
1345
  /** True bila terminal menciut di bawah minimum TUI (MIN_ROWS/MIN_COLS). */
@@ -956,10 +1353,8 @@ export class TuiApp {
956
1353
  this.currentScreen = screen
957
1354
  const cols = screen.cols
958
1355
  const rows = screen.rows
959
- // Layar menciut tengah sesi: satu bingkai pesan jujur (tepat `rows`
960
- // baris), bukan layout rusak. Kembali normal otomatis saat resize
961
- // (onResize → paint). Gagal-di-kode-lama: wrap pecah + kursor liar.
962
1356
  if (this.tooSmall()) {
1357
+ this.lastLayout = null
963
1358
  const w = Math.max(1, cols)
964
1359
  const frame = [c.warning(truncateToWidth(t("tui.tooSmall"), w))]
965
1360
  while (frame.length < Math.max(1, rows)) frame.push("")
@@ -969,67 +1364,10 @@ export class TuiApp {
969
1364
  this.frames++
970
1365
  return
971
1366
  }
972
- const snap = this.host.getStatus()
973
- const busy = this.busy || snap.busy
974
- // MINICODE_MOTION=0 (temuan audit TUI-006): spark statis redup — status
975
- // busy tak boleh bergantung pada animasi (aksesibilitas / rec / SSH lambat).
976
- this.tick = busy ? this.tick + 1 : 0
977
- const statusLine =
978
- renderFooter(
979
- {
980
- ...snap.footer,
981
- activity: this.activityText(snap),
982
- sparkFrame: busy && !motionReduced() ? this.tick : 0,
983
- },
984
- cols,
985
- )[0] ?? ""
986
- const menu = this.menuRows(rows, cols)
987
- const inputAll = this.inputRows(cols)
988
- const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
989
- // Indikator "output baru di bawah": user membaca ke atas saat stream
990
- // masuk — tanpa ini output baru lewat diam-diam. Makan 1 baris viewport.
991
- // total() monotonik: evict cap tak membuat hitungan negatif/hilang.
992
- const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
993
- // Indikator + hint abort saling eksklusif (satu slot): scroll memakai slot
994
- // untuk "baris baru"; abort memakainya untuk petunjuk keluar.
995
- const indicator: string[] = []
996
- if (this.busy && this.abortHintOn) indicator.push(c.warning(t("app.abortHint")))
997
- else if (newCount > 0) indicator.push(c.muted(t("app.newBelow", { n: newCount })))
998
- const viewH = Math.max(1, rows - 1 - inputH - menu.length - indicator.length)
999
- // Kunci posisi baca: stream yang menambah baris saat user scroll ke atas
1000
- // ikut menggeser scrollBack agar jendela menunjuk baris absolut yang sama
1001
- // (dulu viewport merayap mengikuti ekor — kontrak I17).
1002
- const curWrapped = this.transcript.wrappedLength(cols)
1003
- if (this.scrollBack > 0 && this.lastWrapped > 0) {
1004
- this.scrollBack = Math.max(
1005
- 0,
1006
- Math.min(this.scrollBack + (curWrapped - this.lastWrapped), Math.max(0, curWrapped - 1)),
1007
- )
1008
- }
1009
- this.lastWrapped = curWrapped
1010
- const body = this.transcript.view(cols, viewH, this.scrollBack)
1011
- // Jendela input mengikuti kursor: bila kursor di atas jendela ekor
1012
- // (mis. paste 10 baris lalu Home), gulir ke atas agar kursor terlihat.
1013
- // Tanpa ini baris atas tak terjangkau visual tapi kursor diparkir di
1014
- // baris yang salah (dulu selalu slice ekor).
1015
- const cursor = this.cursorIndex(cols)
1016
- const winStart = Math.max(0, Math.min(inputAll.length - inputH, cursor.visIdx))
1017
- const shownInput = inputAll.slice(winStart, winStart + inputH)
1018
- const frame: string[] = [...body, ...menu, ...indicator, ...shownInput, statusLine]
1019
- while (frame.length < rows) frame.unshift("")
1020
- const out = frame.slice(-rows)
1367
+ const layout = this.buildLayout(rows, cols, this.host.getStatus())
1368
+ this.lastLayout = layout
1021
1369
  try {
1022
- screen.paint(out)
1023
- } catch {}
1024
- // Parkir kursor di posisi ketik (kolom terminal, bukan karakter).
1025
- // Di dalam blok sync-update yang SAMA dengan frame (temuan audit TUI-007):
1026
- // kursor yang ditulis setelah SYNC_END berpotensi tearing di emulator
1027
- // tanpa ?2026 (frame tampil, kursor satu posisi lama).
1028
- const cursorRow = viewH + menu.length + indicator.length + (cursor.visIdx - winStart) + 1
1029
- try {
1030
- process.stdout.write(
1031
- `${SYNC_UPDATE_START}\x1b[?25l\x1b[${Math.max(1, cursorRow)};${Math.max(1, cursor.col)}H\x1b[?25h${SYNC_UPDATE_END}`,
1032
- )
1370
+ screen.paint(layout.frame, layout.cursor)
1033
1371
  } catch {}
1034
1372
  this.frames++
1035
1373
  }