minicode-ai 0.9.29 → 0.11.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.
- package/AGENTS.md +45 -0
- package/CHANGELOG.md +79 -1
- package/PLAN.md +491 -0
- package/README.md +2 -2
- package/cli/args.ts +1 -0
- package/cli/commands/acp.ts +485 -0
- package/cli/commands/auth.ts +7 -4
- package/cli/commands/config.ts +41 -27
- package/cli/commands/exec.ts +33 -12
- package/cli/commands/mcp.ts +3 -2
- package/cli/commands/memory.ts +1 -1
- package/cli/commands/pricing.ts +6 -4
- package/cli/commands/providers.ts +18 -8
- package/cli/commands/sessions.ts +11 -4
- package/cli/commands/skills.ts +3 -3
- package/cli/commands/stats.ts +3 -1
- package/cli/commands.ts +225 -103
- package/cli/index.ts +89 -62
- package/cli/model-manager.ts +8 -8
- package/cli/provider-manager.ts +13 -13
- package/cli/router.ts +7 -0
- package/cli/setup.ts +349 -4
- package/cli/tui.ts +542 -0
- package/cli/wizard.ts +2 -1
- package/docs/ARCHITECTURE.html +62 -36
- package/docs/CONTROL-PLANE-MAP.md +139 -0
- package/docs/HARNESS.md +150 -0
- package/docs/PLAN_UIUX_V6.md +209 -0
- package/docs/README.md +1 -1
- package/docs/SUMMARY.md +52 -0
- package/docs/TERMINAL_CONTRACT.md +367 -0
- package/docs/UI_RENDER_PIPELINE.md +165 -0
- package/docs/USAGE.md +11 -0
- package/docs/agents.md +31 -0
- package/docs/architecture.md +3 -3
- package/docs/choosing-mode.md +34 -0
- package/docs/cli.md +130 -0
- package/docs/concepts.md +53 -0
- package/docs/config-providers.md +87 -0
- package/docs/config.md +63 -0
- package/docs/contributing.md +79 -0
- package/docs/environment.md +95 -0
- package/docs/exec.md +73 -0
- package/docs/getting-started.md +102 -0
- package/docs/glossary.md +37 -0
- package/docs/mcp-lsp.md +54 -0
- package/docs/memory-sessions.md +63 -0
- package/docs/policy-sandbox.md +72 -0
- package/docs/pricing-budget.md +49 -0
- package/docs/quickstart.md +60 -0
- package/docs/repl.md +67 -0
- package/docs/security-model.md +95 -0
- package/docs/security.md +91 -0
- package/docs/skills.md +48 -0
- package/docs/terminal.md +79 -0
- package/docs/tools.md +123 -0
- package/docs/troubleshooting.md +40 -0
- package/docs/verify-benchmark.md +58 -0
- package/package.json +8 -5
- package/src/app/provider-layer.ts +12 -4
- package/src/app/rag-layer.ts +7 -2
- package/src/app/session.ts +6 -0
- package/src/app/tool-layer.ts +2 -1
- package/src/config.ts +30 -1
- package/src/constants.ts +35 -0
- package/src/lib/net.ts +6 -1
- package/src/lsp/client.ts +41 -8
- package/src/mcp/http-transport.ts +52 -15
- package/src/mcp/transport.ts +32 -1
- package/src/memory/files.ts +6 -5
- package/src/policy/allowlist.ts +1 -1
- package/src/policy/bash-guard.ts +213 -17
- package/src/policy/compaction.ts +57 -3
- package/src/policy/context.ts +4 -0
- package/src/policy/jail.ts +49 -4
- package/src/policy/permission.ts +152 -12
- package/src/policy/pricing.ts +12 -9
- package/src/policy/update-check.ts +4 -1
- package/src/presentation/adapter.ts +721 -0
- package/src/presentation/events.ts +324 -0
- package/src/presentation/label.ts +140 -0
- package/src/presentation/model.ts +172 -0
- package/src/presentation/reducer.ts +486 -0
- package/src/presentation/store.ts +256 -0
- package/src/providers/anthropic.ts +22 -4
- package/src/providers/detect.ts +2 -1
- package/src/providers/router.ts +13 -0
- package/src/repo/repomap.ts +2 -29
- package/src/session/checkpoint.ts +27 -9
- package/src/session/journal.ts +27 -5
- package/src/skills/loader.ts +88 -5
- package/src/telemetry/trace.ts +36 -15
- package/src/tools/ask_user.ts +73 -4
- package/src/tools/bash.ts +23 -17
- package/src/tools/glob.ts +10 -11
- package/src/tools/lsp.ts +3 -56
- package/src/tools/memory.ts +13 -12
- package/src/tools/task.ts +7 -1
- package/src/tools/web_fetch.ts +11 -2
- package/src/tools/web_search.ts +4 -1
- package/src/ui/approval/prompt.ts +96 -22
- package/src/ui/assistant/simple.ts +188 -44
- package/src/ui/assistant/turn-status.ts +32 -10
- package/src/ui/contract.ts +119 -0
- package/src/ui/footer.ts +35 -14
- package/src/ui/i18n/en.ts +253 -0
- package/src/ui/i18n/id.ts +255 -0
- package/src/ui/i18n/locale.ts +68 -0
- package/src/ui/input/input.ts +189 -81
- package/src/ui/input/prompt-engine.ts +139 -4
- package/src/ui/render/collapse.ts +20 -13
- package/src/ui/render/diff.ts +7 -2
- package/src/ui/render/errors.ts +75 -50
- package/src/ui/render/format.ts +26 -8
- package/src/ui/render/highlight.ts +12 -5
- package/src/ui/render/markdown.ts +5 -1
- package/src/ui/render/sanitize.ts +29 -2
- package/src/ui/render/table.ts +12 -6
- package/src/ui/render/theme.ts +23 -4
- package/src/ui/render/width.ts +104 -17
- package/src/ui/runtime/motion.ts +16 -0
- package/src/ui/runtime/screen.ts +242 -0
- package/src/ui/runtime/spinner.ts +50 -4
- package/src/ui/runtime/statusline.ts +50 -1
- package/src/ui/screens/dialog.ts +174 -0
- package/src/ui/screens/form.ts +486 -0
- package/src/ui/screens/model-manager.ts +289 -134
- package/src/ui/screens/picker.ts +264 -109
- package/src/ui/screens/provider-manager.ts +385 -172
- package/src/ui/screens/wizard.ts +165 -102
- package/src/ui/tui/app.ts +951 -0
- package/src/ui/tui/transcript.ts +475 -0
- package/vendor/minicore/LICENSE +21 -0
- package/vendor/minicore/VENDOR.md +6 -3
- package/vendor/minicore/package.json +6 -3
- package/vendor/minicore/src/core/loop.ts +12 -2
- package/vendor/minicore/src/core/snapshot.ts +4 -0
- package/vendor/minicore/src/providers/openai-compat.ts +76 -25
- package/cli/repl.ts +0 -740
- package/src/ui/runtime/chrome.ts +0 -369
- package/src/ui/screens/overlay.ts +0 -61
|
@@ -0,0 +1,951 @@
|
|
|
1
|
+
// App TUI — pemilik tunggal layar mode `--tui` (kontrak I17-I20).
|
|
2
|
+
//
|
|
3
|
+
// Arsitektur: SATU repaint sinkron per event. Tak ada painter lain yang aktif
|
|
4
|
+
// bersamaan (turn berjalan = spark pada status bar, bukan painter). Frame
|
|
5
|
+
// selalu TEPAT `rows` baris: transkrip viewport + dropdown `/` + blok input +
|
|
6
|
+
// status bar. Kursor diparkir di posisi ketik setelah paint.
|
|
7
|
+
//
|
|
8
|
+
// Batas lapisan: semua yang berbau sesi/model/turn datang via TuiHost yang
|
|
9
|
+
// di-inject dari cli/ (composition root). src/ui TAK BOLEH impor cli/.
|
|
10
|
+
import type { UiBus, UiPresentationActivity } from "../contract.ts"
|
|
11
|
+
import { type FooterStatus, renderFooter } from "../footer.ts"
|
|
12
|
+
import { t } from "../i18n/locale.ts"
|
|
13
|
+
import {
|
|
14
|
+
applyKey,
|
|
15
|
+
createDecoderState,
|
|
16
|
+
createKeyStreamPump,
|
|
17
|
+
createState,
|
|
18
|
+
cursorLineIndex,
|
|
19
|
+
type DecoderState,
|
|
20
|
+
type KeyStreamPump,
|
|
21
|
+
type PromptKey,
|
|
22
|
+
type PromptState,
|
|
23
|
+
toGraphemes,
|
|
24
|
+
} from "../input/prompt-engine.ts"
|
|
25
|
+
import { sanitizeAnsiLine } from "../render/sanitize.ts"
|
|
26
|
+
import { c } from "../render/theme.ts"
|
|
27
|
+
import { chunkByWidth, displayWidth, truncateToWidth } from "../render/width.ts"
|
|
28
|
+
import { motionReduced } from "../runtime/motion.ts"
|
|
29
|
+
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"
|
|
37
|
+
|
|
38
|
+
export interface TuiStatusSnapshot {
|
|
39
|
+
footer: FooterStatus
|
|
40
|
+
busy: boolean
|
|
41
|
+
pinnedActivity?: UiPresentationActivity
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface TuiHost {
|
|
45
|
+
bus: UiBus
|
|
46
|
+
/** Status untuk bar status (mode/model/cwd/konteks dari sumber = footer). */
|
|
47
|
+
getStatus(): TuiStatusSnapshot
|
|
48
|
+
/** Hint dropdown untuk baris "/" (slash + skill, difilter prefix). */
|
|
49
|
+
listCommands(prefix: string): string[]
|
|
50
|
+
/**
|
|
51
|
+
* Eksekusi baris yang di-submit: builtin (/exit, /clear, /help, …) atau
|
|
52
|
+
* prompt ke model. Resolve {quit:true} untuk keluar. Throw = App tampilkan
|
|
53
|
+
* sebagai baris error (tak ada jalur diam).
|
|
54
|
+
*/
|
|
55
|
+
submit(text: string): Promise<{ quit?: boolean } | undefined>
|
|
56
|
+
/** Batalkan turn yang berjalan (Esc/Ctrl+C saat busy). */
|
|
57
|
+
abort(): void
|
|
58
|
+
/** Putar mode permission (Tab / Shift+Tab). */
|
|
59
|
+
cycleMode(dir: 1 | -1): void
|
|
60
|
+
/** Toggle compact / reasoning (Ctrl+O / Ctrl+T). */
|
|
61
|
+
toggleCompact(): void
|
|
62
|
+
toggleReasoning(): void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface TuiRunResult {
|
|
66
|
+
/** False = layar tak mampu (non-TTY/dumb/sempit) — caller fallback REPL. */
|
|
67
|
+
started: boolean
|
|
68
|
+
frames: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Tinggi maksimum blok input (baris logis di-wrap, kursor selalu terlihat). */
|
|
72
|
+
const MAX_INPUT_ROWS = 5
|
|
73
|
+
/** Tinggi maksimum dropdown — sisa ruang di atas transcript minimum 3 baris. */
|
|
74
|
+
const MAX_DROPDOWN_ROWS = 8
|
|
75
|
+
const MIN_ROWS = 10
|
|
76
|
+
const MIN_COLS = 20
|
|
77
|
+
|
|
78
|
+
const PROMPT_FIRST = "minicode › "
|
|
79
|
+
const PROMPT_CONT = " · "
|
|
80
|
+
|
|
81
|
+
interface RawStdin {
|
|
82
|
+
setRawMode(v: boolean): void
|
|
83
|
+
on(e: string, fn: (c: Buffer) => void): void
|
|
84
|
+
removeListener(e: string, fn: (c: Buffer) => void): void
|
|
85
|
+
resume(): void
|
|
86
|
+
pause(): void
|
|
87
|
+
isTTY?: boolean
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class TuiApp {
|
|
91
|
+
private state: PromptState = createState()
|
|
92
|
+
private scrollBack = 0
|
|
93
|
+
private history: string[] = []
|
|
94
|
+
private histIdx = -1
|
|
95
|
+
private draft = ""
|
|
96
|
+
private busy = false
|
|
97
|
+
private tick = 0
|
|
98
|
+
/** Timestamp abort terakhir (ms) — deteksi double-tap Esc/Ctrl+C = quit. */
|
|
99
|
+
private lastAbortAt = 0
|
|
100
|
+
/** Hint "tekan lagi untuk keluar" tampil sekali setelah abort pertama. */
|
|
101
|
+
private abortHintOn = false
|
|
102
|
+
private frames = 0
|
|
103
|
+
private quitRequested = false
|
|
104
|
+
private finish: (() => void) | null = null
|
|
105
|
+
private decoder: DecoderState = createDecoderState()
|
|
106
|
+
private pump: KeyStreamPump | null = null
|
|
107
|
+
private onData: ((chunk: Buffer) => void) | null = null
|
|
108
|
+
private onResize: (() => void) | null = null
|
|
109
|
+
/**
|
|
110
|
+
* Dua wrapper sinyal terpisah — Bun tidak menyampaikan nama sinyal ke
|
|
111
|
+
* handler (argumen undefined, beda dengan Node), jadi pemetaan sinyal →
|
|
112
|
+
* exit code dilakukan lewat pemasangan per-sinyal ke core di bawah.
|
|
113
|
+
*/
|
|
114
|
+
private onSignalTerm: (() => void) | null = null
|
|
115
|
+
private onSignalHup: (() => void) | null = null
|
|
116
|
+
|
|
117
|
+
private wasRaw = false
|
|
118
|
+
/**
|
|
119
|
+
* Kedalaman suspend (popup komposit memegang fokus). >0 = listener stdin
|
|
120
|
+
* dilepas + repaint ditahan — byte masuk HANYA ke view popup.
|
|
121
|
+
*/
|
|
122
|
+
private suspended = 0
|
|
123
|
+
private stdin: RawStdin | null = null
|
|
124
|
+
/** True setelah releaseTerminal (spawn anak): paint/repaint ditahan. */
|
|
125
|
+
private released = false
|
|
126
|
+
/**
|
|
127
|
+
* Langganan bus untuk repaint live (streaming jawaban, ledger tool,
|
|
128
|
+
* thinking): TANPA ini layar buta selama turn — teks baru hanya tampil
|
|
129
|
+
* saat turn selesai / tombol ditekan. Coalesce 30ms agar burst chunk tak
|
|
130
|
+
* melukis ulang tiap byte.
|
|
131
|
+
*/
|
|
132
|
+
private busUnsubs: (() => void)[] = []
|
|
133
|
+
private repaintTimer: ReturnType<typeof setTimeout> | undefined
|
|
134
|
+
/** Ukuran transkrip saat terakhir ikut ekor (basis indikator "baru"). */
|
|
135
|
+
private tailSize = 0
|
|
136
|
+
/** Ukuran transkrip saat mulai scroll ke atas (basis hitung baris baru). */
|
|
137
|
+
private scrollBase = 0
|
|
138
|
+
/** Panjang visual terakhir (kunci posisi baca agar stream tak merampasnya). */
|
|
139
|
+
private lastWrapped = 0
|
|
140
|
+
|
|
141
|
+
constructor(
|
|
142
|
+
private readonly transcript: Transcript,
|
|
143
|
+
private readonly host: TuiHost,
|
|
144
|
+
) {}
|
|
145
|
+
|
|
146
|
+
/** Jalan sampai quit. Alt-screen enter/exit SELALU berpasangan (I17). */
|
|
147
|
+
async run(): Promise<TuiRunResult> {
|
|
148
|
+
// Cek ukuran SEBELUM enter: terminal sempit langsung fallback tanpa
|
|
149
|
+
// flicker masuk-keluar alt-screen (kontrak residual #7).
|
|
150
|
+
const preRows = process.stdout.rows || 0
|
|
151
|
+
const preCols = process.stdout.columns || 0
|
|
152
|
+
if (preRows < MIN_ROWS || preCols < MIN_COLS) return { started: false, frames: 0 }
|
|
153
|
+
const screen = openAltScreen()
|
|
154
|
+
if (!screen.ok || screen.rows < MIN_ROWS || screen.cols < MIN_COLS) {
|
|
155
|
+
try {
|
|
156
|
+
screen.close()
|
|
157
|
+
} catch {}
|
|
158
|
+
return { started: false, frames: 0 }
|
|
159
|
+
}
|
|
160
|
+
const stdin = process.stdin as unknown as RawStdin
|
|
161
|
+
this.stdin = stdin
|
|
162
|
+
try {
|
|
163
|
+
this.wasRaw =
|
|
164
|
+
(stdin as unknown as { isRaw?: boolean }).isRaw ??
|
|
165
|
+
(process.stdin as unknown as { isRaw?: boolean }).isRaw ??
|
|
166
|
+
false
|
|
167
|
+
} catch {
|
|
168
|
+
this.wasRaw = false
|
|
169
|
+
}
|
|
170
|
+
const done = new Promise<void>((resolve) => (this.finish = resolve))
|
|
171
|
+
this.pump = createKeyStreamPump({
|
|
172
|
+
state: this.decoder,
|
|
173
|
+
onKeys: (keys) => this.handleKeys(keys),
|
|
174
|
+
})
|
|
175
|
+
this.onData = (chunk: Buffer) => this.pump?.push(new Uint8Array(chunk))
|
|
176
|
+
this.onResize = () => {
|
|
177
|
+
// Saat popup fokus, view popup yang melukis ulang regionnya sendiri;
|
|
178
|
+
// repaint penuh App akan menghapus popup dari layar.
|
|
179
|
+
if (this.suspended > 0) return
|
|
180
|
+
// Lukis layar AKTIF (bukan handle `screen` run() yang basi setelah
|
|
181
|
+
// release+reacquire gagal — dulu repaint/resize melukis ke handle
|
|
182
|
+
// tertutup sekaligus menimpa currentScreen baru dengannya).
|
|
183
|
+
this.paintCurrent()
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
stdin.setRawMode(true)
|
|
187
|
+
} catch {}
|
|
188
|
+
try {
|
|
189
|
+
stdin.resume()
|
|
190
|
+
} catch {}
|
|
191
|
+
stdin.on("data", this.onData)
|
|
192
|
+
const stdout = process.stdout as unknown as {
|
|
193
|
+
on(e: string, fn: () => void): void
|
|
194
|
+
removeListener(e: string, fn: () => void): void
|
|
195
|
+
}
|
|
196
|
+
stdout.on("resize", this.onResize)
|
|
197
|
+
// Sinyal fatal (temuan audit TUI-001): default kernel-kill TIDAK
|
|
198
|
+
// menjalankan handler "exit" Node — terminal bisa tertinggal alt-screen
|
|
199
|
+
// + raw mode. Dipasang per-run, dilepas di cleanup (pasangan ketat).
|
|
200
|
+
// Handler TERPISAH per sinyal: Bun TIDAK menyampaikan nama sinyal ke
|
|
201
|
+
// handler (argumen undefined — beda dengan Node), jadi satu handler
|
|
202
|
+
// bersama tak bisa membedakan TERM vs HUP dari parameternya.
|
|
203
|
+
// WAJIB tetap di blok sinkron yang sama dengan openAltScreen() di atas
|
|
204
|
+
// (tanpa await di antaranya): sinyal hanya disampaikan antar-tick event
|
|
205
|
+
// loop, jadi tak ada jendela nyata; sisipkan await di antara keduanya =
|
|
206
|
+
// membuka race SIGTERM sebelum handler terpasang.
|
|
207
|
+
const restoreAndExit = (code: number) => {
|
|
208
|
+
try {
|
|
209
|
+
stdin.setRawMode(false)
|
|
210
|
+
} catch {}
|
|
211
|
+
try {
|
|
212
|
+
stdin.pause()
|
|
213
|
+
} catch {}
|
|
214
|
+
try {
|
|
215
|
+
stdin.removeListener("data", this.onData!)
|
|
216
|
+
} catch {}
|
|
217
|
+
forceRestoreScreenForSignal()
|
|
218
|
+
// exit() eksplisit memicu handler "exit" yang tersisa (spinner,
|
|
219
|
+
// turn-status) — best-effort sinkron. 128+n = konvensi "mati oleh
|
|
220
|
+
// sinyal n" (SIGTERM=15 → 143, SIGHUP=1 → 129) agar automation
|
|
221
|
+
// tetap bisa membedakan sebab.
|
|
222
|
+
process.exit(code)
|
|
223
|
+
}
|
|
224
|
+
this.onSignalTerm = () => restoreAndExit(143)
|
|
225
|
+
this.onSignalHup = () => restoreAndExit(129)
|
|
226
|
+
try {
|
|
227
|
+
process.on("SIGTERM", this.onSignalTerm)
|
|
228
|
+
process.on("SIGHUP", this.onSignalHup)
|
|
229
|
+
} catch {
|
|
230
|
+
this.onSignalTerm = null
|
|
231
|
+
this.onSignalHup = null
|
|
232
|
+
}
|
|
233
|
+
// Repaint live mengikuti event bus (stream teks, ledger, thinking).
|
|
234
|
+
// Suspend menahan repaint (popup melukis sendiri); quit menahan semua.
|
|
235
|
+
const requestPaint = () => {
|
|
236
|
+
if (this.quitRequested || this.suspended > 0 || this.released) return
|
|
237
|
+
if (this.repaintTimer !== undefined) return
|
|
238
|
+
this.repaintTimer = setTimeout(() => {
|
|
239
|
+
this.repaintTimer = undefined
|
|
240
|
+
if (!this.quitRequested && this.suspended === 0 && !this.released) this.paintCurrent()
|
|
241
|
+
}, 30)
|
|
242
|
+
try {
|
|
243
|
+
;(this.repaintTimer as unknown as { unref?: () => void }).unref?.()
|
|
244
|
+
} catch {}
|
|
245
|
+
}
|
|
246
|
+
const sub = (type: Parameters<UiBus["on"]>[0]) => {
|
|
247
|
+
try {
|
|
248
|
+
this.busUnsubs.push(this.host.bus.on(type, requestPaint))
|
|
249
|
+
} catch {}
|
|
250
|
+
}
|
|
251
|
+
sub("provider:text")
|
|
252
|
+
sub("provider:extension")
|
|
253
|
+
sub("execution:started")
|
|
254
|
+
sub("execution:completed")
|
|
255
|
+
sub("turn:started")
|
|
256
|
+
sub("turn:completed")
|
|
257
|
+
sub("context:compacted")
|
|
258
|
+
this.tailSize = this.transcript.total()
|
|
259
|
+
this.scrollBase = this.tailSize
|
|
260
|
+
this.paint(screen)
|
|
261
|
+
await done
|
|
262
|
+
// Cleanup: urutan penting — lepas listener dulu agar byte liar pasca-quit
|
|
263
|
+
// tak memicu repaint ke layar yang sudah dikembalikan.
|
|
264
|
+
stdin.removeListener("data", this.onData)
|
|
265
|
+
stdout.removeListener("resize", this.onResize)
|
|
266
|
+
if (this.repaintTimer !== undefined) {
|
|
267
|
+
clearTimeout(this.repaintTimer)
|
|
268
|
+
this.repaintTimer = undefined
|
|
269
|
+
}
|
|
270
|
+
for (const u of this.busUnsubs) {
|
|
271
|
+
try {
|
|
272
|
+
u()
|
|
273
|
+
} catch {}
|
|
274
|
+
}
|
|
275
|
+
this.busUnsubs = []
|
|
276
|
+
this.suspended = 0
|
|
277
|
+
this.released = false
|
|
278
|
+
if (this.onSignalTerm) {
|
|
279
|
+
try {
|
|
280
|
+
process.off("SIGTERM", this.onSignalTerm)
|
|
281
|
+
} catch {}
|
|
282
|
+
this.onSignalTerm = null
|
|
283
|
+
}
|
|
284
|
+
if (this.onSignalHup) {
|
|
285
|
+
try {
|
|
286
|
+
process.off("SIGHUP", this.onSignalHup)
|
|
287
|
+
} catch {}
|
|
288
|
+
this.onSignalHup = null
|
|
289
|
+
}
|
|
290
|
+
this.stdin = null
|
|
291
|
+
this.pump.dispose()
|
|
292
|
+
this.pump = null
|
|
293
|
+
try {
|
|
294
|
+
stdin.setRawMode(this.wasRaw)
|
|
295
|
+
} catch {}
|
|
296
|
+
try {
|
|
297
|
+
stdin.pause()
|
|
298
|
+
} catch {}
|
|
299
|
+
try {
|
|
300
|
+
// Tutup layar AKTIF (bisa diganti reacquireTerminal setelah spawn
|
|
301
|
+
// gagal — menutup handle run() yang basi akan meninggalkan alt-screen
|
|
302
|
+
// yatim; close() idempoten sehingga aman dua kali).
|
|
303
|
+
this.currentScreen?.close()
|
|
304
|
+
} catch {}
|
|
305
|
+
this.currentScreen = null
|
|
306
|
+
return { started: true, frames: this.frames }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ── Penanganan key ──
|
|
310
|
+
|
|
311
|
+
private handleKeys(keys: { key: PromptKey }[]): boolean {
|
|
312
|
+
// Garda suspend: timer flush lone-ESC yang dipersenjatai SEBELUM suspend
|
|
313
|
+
// tetap menembak setelah popup terbuka (listener dilepas, timer tidak).
|
|
314
|
+
// Tanpa ini repaint penuh App 50ms kemudian menimpa region popup +
|
|
315
|
+
// memutasi state di belakang view. Gagal-di-kode-lama.
|
|
316
|
+
if (this.suspended > 0) return false
|
|
317
|
+
for (const { key } of keys) {
|
|
318
|
+
if (this.quitRequested) return true
|
|
319
|
+
this.handleKey(key)
|
|
320
|
+
}
|
|
321
|
+
return this.quitRequested
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private handleKey(key: PromptKey): void {
|
|
325
|
+
// Scroll SELALU tersedia (menu buka/tutup, busy/idle, layar menciut) —
|
|
326
|
+
// di-intercept sebelum engine supaya tak jadi histori maupun teks.
|
|
327
|
+
// Dulu di bawah gate tooSmall: terminal menciut + turn busy = tak bisa
|
|
328
|
+
// scroll maupun abort (harus kill -9).
|
|
329
|
+
// Shift+PgUp/PgDn (ESC[5;2~/6;2~, didekode modifier 2 = shift) = setengah
|
|
330
|
+
// halaman (temuan audit TUI-002): halaman penuh terlalu kasar untuk
|
|
331
|
+
// transkrip panjang; Home/End = lompat top/tail (di bawah).
|
|
332
|
+
if (key.type === "pageup" || key.type === "pagedown") {
|
|
333
|
+
const mod = key.modifier ?? 0
|
|
334
|
+
if (mod === 2) {
|
|
335
|
+
this.scrollBy(key.type === "pageup" ? 0.5 : -0.5)
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
this.scrollBy(key.type === "pageup" ? 1 : -1)
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
// Home/End LOMPAT transkrip HANYA saat prompt kosong & tanpa dropdown
|
|
342
|
+
// (temuan audit TUI-002): transkrip cap 5000 baris ≈ 125 halaman —
|
|
343
|
+
// menekan PgUp 125× bukan navigasi. Home = baris teratas, End = kembali
|
|
344
|
+
// ke ekor. Baris BERISI = tombol editing (awal/akhir baris, kontrak lama);
|
|
345
|
+
// dropdown terbuka = navigasi menu (jalur engine).
|
|
346
|
+
if ((key.type === "home" || key.type === "end") && !this.state.menuOpen && !this.state.line) {
|
|
347
|
+
const logical = key.type === "home"
|
|
348
|
+
if (logical || this.scrollBack !== 0) {
|
|
349
|
+
this.jumpEdge(logical)
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
// End saat sudah di ekor: biarkan ke engine (kebiasaan editing —
|
|
353
|
+
// tidak ada yang berubah, action "none").
|
|
354
|
+
this.applyEngine(key)
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
// Abort/batal: Esc & Ctrl+C — berlaku juga saat layar menciut (jalan
|
|
358
|
+
// keluar saat terminal mengecil di tengah turn busy).
|
|
359
|
+
// Jalan keluar saat abort macet (provider/tool non-kooperatif abaikan
|
|
360
|
+
// sinyal): Esc/Ctrl+C KEDUA dalam 1.5 dtk, atau Ctrl+D baris-kosong,
|
|
361
|
+
// = abort + quit. Tanpa ini sesi hanya bisa dibunuh kill -9 (kontrak I14).
|
|
362
|
+
if (key.type === "esc" || key.type === "ctrl-c") {
|
|
363
|
+
if (this.busy) {
|
|
364
|
+
try {
|
|
365
|
+
this.host.abort()
|
|
366
|
+
} catch {}
|
|
367
|
+
const now = Date.now()
|
|
368
|
+
const doubleTap = now - this.lastAbortAt < 1500
|
|
369
|
+
// Hint "tekan lagi untuk keluar" SEKALI setelah abort pertama (temuan
|
|
370
|
+
// audit TUI-005): tanpa ini user yang menekan Esc dua kali untuk
|
|
371
|
+
// "memastikan" justru keluar sesi tanpa sengaja — transkrip TUI hilang.
|
|
372
|
+
// Hanya saat TIDAK double-tap; saat menciut indikator tak dilukis.
|
|
373
|
+
if (!doubleTap) this.abortHintOn = true
|
|
374
|
+
this.lastAbortAt = now
|
|
375
|
+
if (doubleTap) this.quit()
|
|
376
|
+
else this.paintCurrent()
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
if (this.tooSmall()) return
|
|
380
|
+
if (key.type === "esc" && this.state.menuOpen) {
|
|
381
|
+
this.applyEngine(key)
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
if (this.state.line) {
|
|
385
|
+
this.state = createState()
|
|
386
|
+
this.histIdx = -1
|
|
387
|
+
this.paintCurrent()
|
|
388
|
+
}
|
|
389
|
+
return
|
|
390
|
+
}
|
|
391
|
+
// Terminal menciut di bawah minimum: abaikan SEMUA kecuali keluar.
|
|
392
|
+
// Tanpa ini layout rusak (kolom negatif, kursor melompat) dan user
|
|
393
|
+
// terkunci tanpa jalan keluar yang terlihat.
|
|
394
|
+
if (this.tooSmall()) {
|
|
395
|
+
if (key.type === "ctrl-d") this.quit()
|
|
396
|
+
return
|
|
397
|
+
}
|
|
398
|
+
// Saat turn berjalan SEMUA input dibekukan kecuali abort (Esc/Ctrl+C),
|
|
399
|
+
// scroll (PgUp/PgDn di atas), dan Ctrl+D baris-kosong (= abort + quit,
|
|
400
|
+
// jalan keluar saat abort macet — kontrak I14).
|
|
401
|
+
if (this.busy) {
|
|
402
|
+
if (key.type === "ctrl-d" && !this.state.line) {
|
|
403
|
+
try {
|
|
404
|
+
this.host.abort()
|
|
405
|
+
} catch {}
|
|
406
|
+
this.quit()
|
|
407
|
+
}
|
|
408
|
+
return
|
|
409
|
+
}
|
|
410
|
+
if (key.type === "ctrl-d") {
|
|
411
|
+
// Baris kosong = keluar (konvensi EOF); berisi = abaikan (I19).
|
|
412
|
+
if (!this.state.line) this.quit()
|
|
413
|
+
return
|
|
414
|
+
}
|
|
415
|
+
if (key.type === "tab") {
|
|
416
|
+
this.host.cycleMode(1)
|
|
417
|
+
this.paintCurrent()
|
|
418
|
+
return
|
|
419
|
+
}
|
|
420
|
+
if (key.type === "shift-tab") {
|
|
421
|
+
this.host.cycleMode(-1)
|
|
422
|
+
this.paintCurrent()
|
|
423
|
+
return
|
|
424
|
+
}
|
|
425
|
+
if (key.type === "ctrl-o") {
|
|
426
|
+
this.host.toggleCompact()
|
|
427
|
+
this.paintCurrent()
|
|
428
|
+
return
|
|
429
|
+
}
|
|
430
|
+
if (key.type === "ctrl-t") {
|
|
431
|
+
this.host.toggleReasoning()
|
|
432
|
+
this.paintCurrent()
|
|
433
|
+
return
|
|
434
|
+
}
|
|
435
|
+
if (key.type === "ctrl-r") {
|
|
436
|
+
this.historySearch()
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
// Up/Down di luar menu: jika teks multi-line, navigasi baris dalam teks dulu.
|
|
440
|
+
// Hanya picu navigasi histori bila Up di baris pertama atau Down di baris terakhir.
|
|
441
|
+
if ((key.type === "up" || key.type === "down") && !this.state.menuOpen) {
|
|
442
|
+
if (this.state.line.includes("\n")) {
|
|
443
|
+
const { lineIdx, colIdx } = cursorLineIndex(this.state.line, this.state.cursor)
|
|
444
|
+
const lines = this.state.line.split("\n")
|
|
445
|
+
if (key.type === "up" && lineIdx > 0) {
|
|
446
|
+
const targetLine = lineIdx - 1
|
|
447
|
+
const targetCol = Math.min(colIdx, toGraphemes(lines[targetLine] ?? "").length)
|
|
448
|
+
let newCursor = 0
|
|
449
|
+
for (let i = 0; i < targetLine; i++) newCursor += toGraphemes(lines[i] ?? "").length + 1
|
|
450
|
+
newCursor += targetCol
|
|
451
|
+
this.state = { ...this.state, cursor: newCursor }
|
|
452
|
+
this.paintCurrent()
|
|
453
|
+
return
|
|
454
|
+
}
|
|
455
|
+
if (key.type === "down" && lineIdx < lines.length - 1) {
|
|
456
|
+
const targetLine = lineIdx + 1
|
|
457
|
+
const targetCol = Math.min(colIdx, toGraphemes(lines[targetLine] ?? "").length)
|
|
458
|
+
let newCursor = 0
|
|
459
|
+
for (let i = 0; i < targetLine; i++) newCursor += toGraphemes(lines[i] ?? "").length + 1
|
|
460
|
+
newCursor += targetCol
|
|
461
|
+
this.state = { ...this.state, cursor: newCursor }
|
|
462
|
+
this.paintCurrent()
|
|
463
|
+
return
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
this.historyNav(key.type === "up" ? -1 : 1)
|
|
467
|
+
return
|
|
468
|
+
}
|
|
469
|
+
this.applyEngine(key)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private applyEngine(key: PromptKey): void {
|
|
473
|
+
const hints = (line: string) => (line.startsWith("/") ? this.host.listCommands(line) : [])
|
|
474
|
+
const { state, action } = applyKey(this.state, key, hints)
|
|
475
|
+
this.state = state
|
|
476
|
+
if (action === "submit") {
|
|
477
|
+
void this.doSubmit(state.line)
|
|
478
|
+
} else if (action === "cancel") {
|
|
479
|
+
// Engine cancel (ctrl-c/ctrl-d) sudah ditangani di atas; tak terjangkau.
|
|
480
|
+
} else if (action === "render" || action === "none") {
|
|
481
|
+
// Ketikan baru = kembali ke ekor (I18); stream turn TIDAK me-reset
|
|
482
|
+
// (user yang sedang membaca ke atas tak dirampas).
|
|
483
|
+
if (key.type === "char" || key.type === "backspace" || key.type === "delete") {
|
|
484
|
+
this.followTail()
|
|
485
|
+
}
|
|
486
|
+
this.paintCurrent()
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private async doSubmit(rawLine: string): Promise<void> {
|
|
491
|
+
const line = rawLine.trim()
|
|
492
|
+
this.state = createState()
|
|
493
|
+
this.histIdx = -1
|
|
494
|
+
this.followTail()
|
|
495
|
+
this.abortHintOn = false
|
|
496
|
+
if (!line) {
|
|
497
|
+
this.paintCurrent()
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
this.rememberHistory(line)
|
|
501
|
+
this.transcript.pushUser(rawLine)
|
|
502
|
+
this.busy = true
|
|
503
|
+
this.lastAbortAt = 0
|
|
504
|
+
this.paintCurrent()
|
|
505
|
+
try {
|
|
506
|
+
const res = await this.host.submit(line)
|
|
507
|
+
if (res?.quit) this.quit()
|
|
508
|
+
} catch (e) {
|
|
509
|
+
this.transcript.pushError(e instanceof Error ? e.message : String(e))
|
|
510
|
+
} finally {
|
|
511
|
+
this.busy = false
|
|
512
|
+
if (!this.quitRequested) this.paintCurrent()
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private quit(): void {
|
|
517
|
+
if (this.quitRequested) return
|
|
518
|
+
this.quitRequested = true
|
|
519
|
+
this.finish?.()
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Minta keluar (dipakai controller saat terminal tak bisa dihidupkan lagi
|
|
524
|
+
* setelah spawn gagal — daripada TUI mati tanpa layar).
|
|
525
|
+
*/
|
|
526
|
+
requestQuit(): void {
|
|
527
|
+
this.quit()
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Bekukan App untuk popup komposit: lepas listener stdin (byte masuk HANYA
|
|
532
|
+
* ke view popup — anti double-handling) + redupkan layar sebagai backdrop.
|
|
533
|
+
* View melukis kotaknya sendiri via paintRegion; tutup = resume().
|
|
534
|
+
*/
|
|
535
|
+
suspend(): void {
|
|
536
|
+
if (!this.currentScreen || this.quitRequested) return
|
|
537
|
+
if (this.suspended++ > 0) return
|
|
538
|
+
try {
|
|
539
|
+
if (this.onData) this.stdin?.removeListener("data", this.onData)
|
|
540
|
+
} catch {}
|
|
541
|
+
this.paintDimmed()
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Kembalikan fokus: rebut raw mode + pasang listener + repaint penuh
|
|
546
|
+
* (menimpa region popup). Idempoten terhadap resume berlebih. No-op bila
|
|
547
|
+
* terminal dilepas untuk spawn anak (releaseTerminal) — kebangkitan
|
|
548
|
+
* eksplisit lewat reacquireTerminal.
|
|
549
|
+
*/
|
|
550
|
+
resume(): void {
|
|
551
|
+
if (this.released || this.suspended <= 0) return
|
|
552
|
+
if (--this.suspended > 0) return
|
|
553
|
+
try {
|
|
554
|
+
this.stdin?.setRawMode(true)
|
|
555
|
+
} catch {}
|
|
556
|
+
try {
|
|
557
|
+
if (this.onData) this.stdin?.on("data", this.onData)
|
|
558
|
+
} catch {}
|
|
559
|
+
this.paintCurrent()
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Lepas terminal untuk spawn anak stdio-inherit (/sessions <id>): keluar
|
|
564
|
+
* alt-screen + cooked mode + lepas listener. Tanpa ini anak mewarisi buffer
|
|
565
|
+
* ?1049h + raw mode (double-ENTER, EXIT anak merobek buffer parent,
|
|
566
|
+
* stdin mentah macet). Gagal-di-kode-lama: layar korup + terminal rusak
|
|
567
|
+
* setelah anak keluar.
|
|
568
|
+
*/
|
|
569
|
+
releaseTerminal(): void {
|
|
570
|
+
try {
|
|
571
|
+
if (this.onData) this.stdin?.removeListener("data", this.onData)
|
|
572
|
+
} catch {}
|
|
573
|
+
try {
|
|
574
|
+
this.stdin?.setRawMode(false)
|
|
575
|
+
} catch {}
|
|
576
|
+
try {
|
|
577
|
+
this.currentScreen?.close()
|
|
578
|
+
} catch {}
|
|
579
|
+
this.currentScreen = null
|
|
580
|
+
this.released = true
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Hidupkan kembali terminal setelah release (jalur spawn GAGAL — anak tak
|
|
585
|
+
* jalan sehingga parent harus lanjut). No-op bila tidak dilepas. False =
|
|
586
|
+
* terminal tak mampu lagi → pemanggil harus quit. Listener stdin TIDAK
|
|
587
|
+
* dipasang di sini (tugas resume() di finally pemanggil) agar tak ganda.
|
|
588
|
+
*/
|
|
589
|
+
reacquireTerminal(): boolean {
|
|
590
|
+
if (!this.released) return true
|
|
591
|
+
if (this.quitRequested) return false
|
|
592
|
+
const screen = openAltScreen()
|
|
593
|
+
if (!screen.ok) return false
|
|
594
|
+
this.currentScreen = screen
|
|
595
|
+
this.released = false
|
|
596
|
+
try {
|
|
597
|
+
this.stdin?.setRawMode(true)
|
|
598
|
+
} catch {}
|
|
599
|
+
this.paintCurrent()
|
|
600
|
+
return true
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** True saat popup/modal memegang fokus (input App dibekukan). */
|
|
604
|
+
isSuspended(): boolean {
|
|
605
|
+
return this.suspended > 0
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Bungkus baris dengan mode redup (\x1b[2m) untuk backdrop popup.
|
|
610
|
+
* Reset (\x1b[0m atau \x1b[22m) dan bold (\x1b[1m) di dalam teks dinetralkan
|
|
611
|
+
* agar peredupan tidak bocor di tengah baris yang diwarnai.
|
|
612
|
+
*/
|
|
613
|
+
static applyBackdropDim(ln: string): string {
|
|
614
|
+
if (!ln) return ""
|
|
615
|
+
const esc = String.fromCharCode(27)
|
|
616
|
+
let s = ln.replaceAll(`${esc}[1m`, "")
|
|
617
|
+
s = s.replaceAll(`${esc}[22m`, `${esc}[2m`)
|
|
618
|
+
s = s.replaceAll(`${esc}[0m`, `${esc}[0m${esc}[2m`)
|
|
619
|
+
s = s.replaceAll(`${esc}[m`, `${esc}[0m${esc}[2m`)
|
|
620
|
+
return `${esc}[2m${s}${esc}[22m${esc}[0m`
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** Layar redup sebagai backdrop popup: frame normal dibungkus faint. */
|
|
624
|
+
private paintDimmed(): void {
|
|
625
|
+
const screen = this.currentScreen
|
|
626
|
+
if (!screen) return
|
|
627
|
+
const cols = screen.cols
|
|
628
|
+
const rows = screen.rows
|
|
629
|
+
const snap = this.host.getStatus()
|
|
630
|
+
const statusLine = renderFooter({ ...snap.footer, sparkFrame: 0 }, cols)[0] ?? ""
|
|
631
|
+
const menu = this.menuRows(rows, cols)
|
|
632
|
+
const inputAll = this.inputRows(cols)
|
|
633
|
+
const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
|
|
634
|
+
const viewH = Math.max(1, rows - 1 - inputH - menu.length)
|
|
635
|
+
const body = this.transcript.view(cols, viewH, this.scrollBack)
|
|
636
|
+
const frame: string[] = [...body, ...menu, ...inputAll.slice(-inputH), statusLine]
|
|
637
|
+
while (frame.length < rows) frame.unshift("")
|
|
638
|
+
const dimmed = frame.slice(-rows).map((ln) => TuiApp.applyBackdropDim(ln))
|
|
639
|
+
try {
|
|
640
|
+
screen.paint(dimmed)
|
|
641
|
+
} catch {}
|
|
642
|
+
this.frames++
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ── Histori prompt (memori sesi; tak persist ke berkas REPL) ──
|
|
646
|
+
|
|
647
|
+
private rememberHistory(line: string): void {
|
|
648
|
+
if (this.history[this.history.length - 1] !== line) this.history.push(line)
|
|
649
|
+
if (this.history.length > 200) this.history.splice(0, this.history.length - 200)
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
private historyNav(dir: -1 | 1): void {
|
|
653
|
+
if (!this.history.length) return
|
|
654
|
+
if (this.histIdx === -1) {
|
|
655
|
+
if (dir > 0) return
|
|
656
|
+
this.draft = this.state.line
|
|
657
|
+
this.histIdx = this.history.length - 1
|
|
658
|
+
} else {
|
|
659
|
+
const next = this.histIdx + dir
|
|
660
|
+
if (next < 0) return
|
|
661
|
+
if (next >= this.history.length) {
|
|
662
|
+
this.histIdx = -1
|
|
663
|
+
this.setLine(this.draft)
|
|
664
|
+
return
|
|
665
|
+
}
|
|
666
|
+
this.histIdx = next
|
|
667
|
+
}
|
|
668
|
+
this.setLine(this.history[this.histIdx] ?? "")
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
private historySearch(): void {
|
|
672
|
+
const prefix = this.state.line
|
|
673
|
+
for (let i = this.history.length - 1; i >= 0; i--) {
|
|
674
|
+
const h = this.history[i]!
|
|
675
|
+
if (h !== prefix && h.startsWith(prefix)) {
|
|
676
|
+
this.setLine(h)
|
|
677
|
+
return
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
private setLine(line: string): void {
|
|
683
|
+
// Bangun ulang state lewat engine (aturan menu/sel ikut terjaga). Baris
|
|
684
|
+
// berubah = kembali ke ekor (paritas ketikan — viewport tidak diam).
|
|
685
|
+
this.followTail()
|
|
686
|
+
let s = createState()
|
|
687
|
+
const hints = (l: string) => (l.startsWith("/") ? this.host.listCommands(l) : [])
|
|
688
|
+
for (const ch of line) {
|
|
689
|
+
const r = applyKey(s, { type: "char", ch }, hints)
|
|
690
|
+
s = r.state
|
|
691
|
+
if (r.action !== "render" && r.action !== "none") break
|
|
692
|
+
}
|
|
693
|
+
this.state = s
|
|
694
|
+
this.paintCurrent()
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// ── Scroll ──
|
|
698
|
+
|
|
699
|
+
private scrollBy(pages: number): void {
|
|
700
|
+
const rows = process.stdout.rows || 24
|
|
701
|
+
const page = Math.max(1, this.viewportHeight(rows, process.stdout.columns || 80) - 1)
|
|
702
|
+
// scrollBack dihitung dalam BARIS agar presisi di terminal pendek. Basis
|
|
703
|
+
// hitung "baris baru" dicatat saat mulai meninggalkan ekor. total()
|
|
704
|
+
// (monotonik) dipakai agar evict cap 5000 tak merusak hitungan.
|
|
705
|
+
// pages pecahan (±0.5) = setengah halaman (temuan audit TUI-002).
|
|
706
|
+
if (this.scrollBack === 0 && pages > 0) this.scrollBase = this.transcript.total()
|
|
707
|
+
this.scrollBack = Math.max(0, Math.round(this.scrollBack + pages * page))
|
|
708
|
+
if (this.scrollBack === 0) {
|
|
709
|
+
this.tailSize = this.transcript.total()
|
|
710
|
+
this.scrollBase = this.tailSize
|
|
711
|
+
}
|
|
712
|
+
this.paintCurrent()
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Lompat ke ujung transkrip (temuan audit TUI-002): Home = baris teratas
|
|
717
|
+
* (scrollBack maksimum), End = ekor. `lastWrapped` dinetralkan SEBELUM
|
|
718
|
+
* perhitungan kunci-posisi-baca berikutnya: jendela yang sengaja dipindah
|
|
719
|
+
* user bukan drift stream, tanpa ini paint pertama post-jump menarik
|
|
720
|
+
* viewport kembali ke ekor (lompatan tak terlihat).
|
|
721
|
+
*/
|
|
722
|
+
private jumpEdge(top: boolean): void {
|
|
723
|
+
const rows = process.stdout.rows || 24
|
|
724
|
+
const cols = process.stdout.columns || 80
|
|
725
|
+
const curWrapped = this.transcript.wrappedLength(cols)
|
|
726
|
+
this.lastWrapped = curWrapped
|
|
727
|
+
if (top) {
|
|
728
|
+
const viewH = Math.max(1, this.viewportHeight(rows, cols) - 1)
|
|
729
|
+
if (this.scrollBack === 0) this.scrollBase = this.transcript.total()
|
|
730
|
+
this.scrollBack = Math.max(0, curWrapped - viewH)
|
|
731
|
+
} else {
|
|
732
|
+
this.scrollBack = 0
|
|
733
|
+
this.tailSize = this.transcript.total()
|
|
734
|
+
this.scrollBase = this.tailSize
|
|
735
|
+
}
|
|
736
|
+
this.paintCurrent()
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Kembali ke ekor: dipakai tiap ketikan/submit baru (I18). */
|
|
740
|
+
private followTail(): void {
|
|
741
|
+
this.scrollBack = 0
|
|
742
|
+
this.tailSize = this.transcript.total()
|
|
743
|
+
this.scrollBase = this.tailSize
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** Kosongkan transkrip (/clear): viewport + basis scroll ikut di-reset agar
|
|
747
|
+
* tak tertinggal scrollBack basi (layar kosong + user harus PgDn manual). */
|
|
748
|
+
clearView(): void {
|
|
749
|
+
this.transcript.clear()
|
|
750
|
+
this.followTail()
|
|
751
|
+
this.lastWrapped = 0
|
|
752
|
+
this.paintCurrent()
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// ── Paint ──
|
|
756
|
+
|
|
757
|
+
private currentScreen: AltScreen | null = null
|
|
758
|
+
|
|
759
|
+
private paintCurrent(): void {
|
|
760
|
+
if (this.currentScreen) this.paint(this.currentScreen)
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Repaint eksplisit untuk pemilik sink eksternal (approval): blok yang baru
|
|
765
|
+
* dicatat harus terlihat SEBELUM user menjawab. No-op bila layar belum
|
|
766
|
+
* jalan atau sudah quit.
|
|
767
|
+
*/
|
|
768
|
+
repaint(): void {
|
|
769
|
+
if (!this.quitRequested) this.paintCurrent()
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
private viewportHeight(rows: number, cols: number): number {
|
|
773
|
+
const inputH = this.inputHeight(cols)
|
|
774
|
+
const menuH = this.menuHeight(rows, cols)
|
|
775
|
+
return Math.max(1, rows - 1 - inputH - menuH)
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
private inputRows(cols: number): string[] {
|
|
779
|
+
const w = Math.max(10, cols)
|
|
780
|
+
const out: string[] = []
|
|
781
|
+
// Baris kosong = placeholder redup (edukasi tanpa banjir): cara keluar
|
|
782
|
+
// selalu terlihat (Ctrl+D), tanpa menuh-menuhi transkrip.
|
|
783
|
+
if (!this.state.line) {
|
|
784
|
+
const hint = c.faint(truncateToWidth(t("app.placeholder"), w - PROMPT_FIRST.length))
|
|
785
|
+
out.push(`${PROMPT_FIRST}${hint}`)
|
|
786
|
+
return out
|
|
787
|
+
}
|
|
788
|
+
const logical = this.state.line.split("\n")
|
|
789
|
+
logical.forEach((ln, idx) => {
|
|
790
|
+
const prefix = idx === 0 ? PROMPT_FIRST : PROMPT_CONT
|
|
791
|
+
const full = `${prefix}${ln}`
|
|
792
|
+
const wrapped = chunkByWidth(full, w)
|
|
793
|
+
// Baris logis kosong tetap menempati 1 baris visual.
|
|
794
|
+
if (!wrapped.length) out.push(full)
|
|
795
|
+
else for (const r of wrapped) out.push(r)
|
|
796
|
+
})
|
|
797
|
+
return out
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
private inputHeight(cols: number): number {
|
|
801
|
+
return Math.min(MAX_INPUT_ROWS, Math.max(1, this.inputRows(cols).length))
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
private menuRows(rows: number, cols: number): string[] {
|
|
805
|
+
if (!this.state.menuOpen || !this.state.line.startsWith("/")) return []
|
|
806
|
+
const hints = this.host.listCommands(this.state.line)
|
|
807
|
+
if (!hints.length) return []
|
|
808
|
+
const room = Math.max(0, rows - 1 - this.inputHeight(cols) - 3)
|
|
809
|
+
const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
|
|
810
|
+
const w = Math.max(10, cols)
|
|
811
|
+
const out: string[] = [c.muted(t("app.menuHeader"))]
|
|
812
|
+
shown.forEach((h, i) => {
|
|
813
|
+
const picked = i === this.state.sel
|
|
814
|
+
const text = sanitizeAnsiLine(h)
|
|
815
|
+
out.push(picked ? c.accent(`› ${text}`) : ` ${text}`)
|
|
816
|
+
})
|
|
817
|
+
if (hints.length > shown.length)
|
|
818
|
+
out.push(c.muted(t("app.moreLines", { n: hints.length - shown.length })))
|
|
819
|
+
return out.map((l) => chunkByWidth(l, w)[0] ?? "")
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
private menuHeight(rows: number, cols: number): number {
|
|
823
|
+
return this.menuRows(rows, cols).length
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** True bila terminal menciut di bawah minimum TUI (MIN_ROWS/MIN_COLS). */
|
|
827
|
+
private tooSmall(): boolean {
|
|
828
|
+
const cols = process.stdout.columns || 0
|
|
829
|
+
const rows = process.stdout.rows || 0
|
|
830
|
+
return rows < MIN_ROWS || cols < MIN_COLS
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
private paint(screen: AltScreen): void {
|
|
834
|
+
this.currentScreen = screen
|
|
835
|
+
const cols = screen.cols
|
|
836
|
+
const rows = screen.rows
|
|
837
|
+
// Layar menciut tengah sesi: satu bingkai pesan jujur (tepat `rows`
|
|
838
|
+
// baris), bukan layout rusak. Kembali normal otomatis saat resize
|
|
839
|
+
// (onResize → paint). Gagal-di-kode-lama: wrap pecah + kursor liar.
|
|
840
|
+
if (this.tooSmall()) {
|
|
841
|
+
const w = Math.max(1, cols)
|
|
842
|
+
const frame = [c.warning(truncateToWidth(t("tui.tooSmall"), w))]
|
|
843
|
+
while (frame.length < Math.max(1, rows)) frame.push("")
|
|
844
|
+
try {
|
|
845
|
+
screen.paint(frame.slice(0, Math.max(1, rows)))
|
|
846
|
+
} catch {}
|
|
847
|
+
this.frames++
|
|
848
|
+
return
|
|
849
|
+
}
|
|
850
|
+
const snap = this.host.getStatus()
|
|
851
|
+
// MINICODE_MOTION=0 (temuan audit TUI-006): spark statis redup — status
|
|
852
|
+
// busy tak boleh bergantung pada animasi (aksesibilitas / rec / SSH lambat).
|
|
853
|
+
this.tick = snap.busy ? this.tick + 1 : 0
|
|
854
|
+
const statusLine =
|
|
855
|
+
renderFooter(
|
|
856
|
+
{ ...snap.footer, sparkFrame: snap.busy && !motionReduced() ? this.tick : 0 },
|
|
857
|
+
cols,
|
|
858
|
+
)[0] ?? ""
|
|
859
|
+
const menu = this.menuRows(rows, cols)
|
|
860
|
+
const inputAll = this.inputRows(cols)
|
|
861
|
+
const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
|
|
862
|
+
// Indikator "output baru di bawah": user membaca ke atas saat stream
|
|
863
|
+
// masuk — tanpa ini output baru lewat diam-diam. Makan 1 baris viewport.
|
|
864
|
+
// total() monotonik: evict cap tak membuat hitungan negatif/hilang.
|
|
865
|
+
const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
|
|
866
|
+
// Indikator + hint abort saling eksklusif (satu slot): scroll memakai slot
|
|
867
|
+
// untuk "baris baru"; abort memakainya untuk petunjuk keluar.
|
|
868
|
+
const indicator: string[] = []
|
|
869
|
+
if (newCount > 0) indicator.push(c.muted(t("app.newBelow", { n: newCount })))
|
|
870
|
+
else if (this.busy && this.abortHintOn) indicator.push(c.warning(t("app.abortHint")))
|
|
871
|
+
const viewH = Math.max(1, rows - 1 - inputH - menu.length - indicator.length)
|
|
872
|
+
// Kunci posisi baca: stream yang menambah baris saat user scroll ke atas
|
|
873
|
+
// ikut menggeser scrollBack agar jendela menunjuk baris absolut yang sama
|
|
874
|
+
// (dulu viewport merayap mengikuti ekor — kontrak I17).
|
|
875
|
+
const curWrapped = this.transcript.wrappedLength(cols)
|
|
876
|
+
if (this.scrollBack > 0 && this.lastWrapped > 0) {
|
|
877
|
+
this.scrollBack = Math.max(
|
|
878
|
+
0,
|
|
879
|
+
Math.min(this.scrollBack + (curWrapped - this.lastWrapped), Math.max(0, curWrapped - 1)),
|
|
880
|
+
)
|
|
881
|
+
}
|
|
882
|
+
this.lastWrapped = curWrapped
|
|
883
|
+
const body = this.transcript.view(cols, viewH, this.scrollBack)
|
|
884
|
+
// Jendela input mengikuti kursor: bila kursor di atas jendela ekor
|
|
885
|
+
// (mis. paste 10 baris lalu Home), gulir ke atas agar kursor terlihat.
|
|
886
|
+
// Tanpa ini baris atas tak terjangkau visual tapi kursor diparkir di
|
|
887
|
+
// baris yang salah (dulu selalu slice ekor).
|
|
888
|
+
const cursor = this.cursorIndex(cols)
|
|
889
|
+
const winStart = Math.max(0, Math.min(inputAll.length - inputH, cursor.visIdx))
|
|
890
|
+
const shownInput = inputAll.slice(winStart, winStart + inputH)
|
|
891
|
+
const frame: string[] = [...body, ...menu, ...indicator, ...shownInput, statusLine]
|
|
892
|
+
while (frame.length < rows) frame.unshift("")
|
|
893
|
+
const out = frame.slice(-rows)
|
|
894
|
+
try {
|
|
895
|
+
screen.paint(out)
|
|
896
|
+
} catch {}
|
|
897
|
+
// Parkir kursor di posisi ketik (kolom terminal, bukan karakter).
|
|
898
|
+
// Di dalam blok sync-update yang SAMA dengan frame (temuan audit TUI-007):
|
|
899
|
+
// kursor yang ditulis setelah SYNC_END berpotensi tearing di emulator
|
|
900
|
+
// tanpa ?2026 (frame tampil, kursor satu posisi lama).
|
|
901
|
+
const cursorRow = viewH + menu.length + indicator.length + (cursor.visIdx - winStart) + 1
|
|
902
|
+
try {
|
|
903
|
+
process.stdout.write(
|
|
904
|
+
`${SYNC_UPDATE_START}\x1b[?25l\x1b[${Math.max(1, cursorRow)};${Math.max(1, cursor.col)}H\x1b[?25h${SYNC_UPDATE_END}`,
|
|
905
|
+
)
|
|
906
|
+
} catch {}
|
|
907
|
+
this.frames++
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* Indeks baris visual kursor (koordinat PENUH inputAll) + kolom 1-based.
|
|
912
|
+
* Wrap-aware; CJK/emoji dihitung per kolom via displayWidth.
|
|
913
|
+
*/
|
|
914
|
+
private cursorIndex(cols: number): { visIdx: number; col: number } {
|
|
915
|
+
// Baris kursor dalam teks logis → petakan ke baris visual (wrap-aware).
|
|
916
|
+
const units = toGraphemes(this.state.line)
|
|
917
|
+
const before = units.slice(0, Math.max(0, Math.min(this.state.cursor, units.length))).join("")
|
|
918
|
+
const logicalIdx = before.split("\n").length - 1
|
|
919
|
+
const lastLine = before.split("\n").pop() ?? ""
|
|
920
|
+
const prefix = logicalIdx === 0 ? PROMPT_FIRST : PROMPT_CONT
|
|
921
|
+
const targetWidth = displayWidth(prefix) + displayWidth(lastLine)
|
|
922
|
+
const w = Math.max(10, cols)
|
|
923
|
+
// Baris visual ke berapa (dari atas blok input) posisi kursor berada.
|
|
924
|
+
let visIdx = 0
|
|
925
|
+
const logical = this.state.line.split("\n")
|
|
926
|
+
for (let li = 0; li < logical.length; li++) {
|
|
927
|
+
const full = `${li === 0 ? PROMPT_FIRST : PROMPT_CONT}${logical[li] ?? ""}`
|
|
928
|
+
const wrapped = chunkByWidth(full, w)
|
|
929
|
+
const n = Math.max(1, wrapped.length)
|
|
930
|
+
if (li < logicalIdx) {
|
|
931
|
+
visIdx += n
|
|
932
|
+
continue
|
|
933
|
+
}
|
|
934
|
+
// Baris kursor: kolom ke-n dalam wrap.
|
|
935
|
+
let acc = 0
|
|
936
|
+
for (let wi = 0; wi < n; wi++) {
|
|
937
|
+
const ww = displayWidth(wrapped[wi] ?? "")
|
|
938
|
+
if (targetWidth < acc + ww || wi === n - 1) {
|
|
939
|
+
visIdx += wi
|
|
940
|
+
// Kolom 1-based dalam baris visual — SAMA untuk baris tengah
|
|
941
|
+
// maupun terakhir (dulu baris tengah selalu diparkir di EOL).
|
|
942
|
+
return { visIdx, col: Math.max(1, targetWidth - acc + 1) }
|
|
943
|
+
}
|
|
944
|
+
acc += ww
|
|
945
|
+
}
|
|
946
|
+
visIdx += n - 1
|
|
947
|
+
break
|
|
948
|
+
}
|
|
949
|
+
return { visIdx, col: 1 }
|
|
950
|
+
}
|
|
951
|
+
}
|