@lune_99/pi-ask-question 0.0.0-stage → 0.2.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.
@@ -0,0 +1,864 @@
1
+ import type { ExtensionContext, ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
2
+
3
+ import {
4
+ Editor,
5
+ Key,
6
+ matchesKey,
7
+ type Component,
8
+ type EditorTheme,
9
+ type Focusable,
10
+ type KeybindingsManager,
11
+ type SizeValue,
12
+ type TUI,
13
+ type TuiMouseEvent,
14
+ type TuiMouseEventResult,
15
+ } from "@earendil-works/pi-tui";
16
+
17
+ import { requestHeaders } from "../../core/question-format.ts";
18
+ import type {
19
+ AskQuestionDraft,
20
+ AskQuestionRequest,
21
+ QuestionManager,
22
+ } from "../../core/questionManager.ts";
23
+ import { readClipboardPaste, type ClipboardPaste } from "./clipboard-paste.ts";
24
+ import { QuestionPanelController } from "./question-panel-controller.ts";
25
+ import {
26
+ QuestionPanelRenderer,
27
+ type PanelRect,
28
+ type PanelSpan,
29
+ type QuestionPanelLayout,
30
+ } from "./question-panel-renderer.ts";
31
+
32
+ const OVERLAY_WIDTH = "80%";
33
+ const OVERLAY_MIN_WIDTH = 70;
34
+ /**
35
+ * The overlay is clamped to the terminal minus its margins, so a taller share than this buys
36
+ * nothing; 90% is what a short terminal needs for the preview block to fit at all.
37
+ */
38
+ const OVERLAY_HEIGHT_RATIO = 0.9;
39
+ const OVERLAY_MAX_HEIGHT: SizeValue = `${OVERLAY_HEIGHT_RATIO * 100}%`;
40
+ const OVERLAY_MARGIN = 2;
41
+
42
+ /** Frame rows: top border, header, two separators, footer, bottom border. */
43
+ const FRAME_HEIGHT = 6;
44
+
45
+ /** pi-tui delivers a terminal paste as one input that starts with this marker. */
46
+ const BRACKETED_PASTE_START = "\x1b[200~";
47
+
48
+ export interface OpenQuestionPanelOptions {
49
+ /**
50
+ * Persist the pending questions after a deferred (Esc) close.
51
+ *
52
+ * Only the extension knows `pi`, and without this hook the answers written before
53
+ * the close would not survive a restart.
54
+ */
55
+ onDeferred?: () => void;
56
+ }
57
+
58
+ /**
59
+ * Why a panel closed: a settled or withdrawn one hands over to the next pending request, while a
60
+ * deferred one (Esc) leaves its request pending and only closes the overlay.
61
+ */
62
+ export type PanelCloseReason = "settled" | "deferred" | "withdrawn";
63
+
64
+ /**
65
+ * Ownership of the single overlay for the requests of one question manager.
66
+ *
67
+ * A panel is a long-lived async operation and a session boundary resets the ownership, so a
68
+ * flag is not enough: a panel that resolves after the reset would clear the ownership of the
69
+ * panel that replaced it. The generation is bumped on every reset, and the owner symbol
70
+ * identifies one invocation, so a stale continuation can neither release nor continue the
71
+ * new panel.
72
+ */
73
+ export class QuestionPanels {
74
+ private readonly manager: QuestionManager;
75
+ private generation = 0;
76
+ private owner: symbol | undefined;
77
+
78
+ constructor(manager: QuestionManager) {
79
+ this.manager = manager;
80
+ }
81
+
82
+ /**
83
+ * A session boundary disposes overlays without resolving their custom() promise in some
84
+ * cases, so the ownership must not survive the boundary and block `/question`.
85
+ */
86
+ reset(): void {
87
+ this.generation++;
88
+ this.owner = undefined;
89
+ }
90
+
91
+ /**
92
+ * Show pending requests in `nextPendingRequest` order until there is nothing left to answer.
93
+ *
94
+ * Called immediately after a request is created, and again from `/question`. A request that
95
+ * arrives while a panel is open does not have to wait for `/question`: it is already pending,
96
+ * so the loop picks it up as soon as the current panel settles or is withdrawn - and because
97
+ * it was never shown, it comes before a request the user only deferred. Deferring (Esc) ends
98
+ * the loop on purpose - the user asked for quiet, not for the next question - and the request
99
+ * stays pending for `/question`.
100
+ *
101
+ * The panel never settles the request when Esc closes it, so the promise completing only
102
+ * means the overlay is gone, not that the questions were answered.
103
+ */
104
+ async open(ctx: ExtensionContext, options: OpenQuestionPanelOptions = {}): Promise<void> {
105
+ if (ctx.mode !== "tui" || this.owner !== undefined) {
106
+ return;
107
+ }
108
+
109
+ const generation = this.generation;
110
+ const owner = Symbol("question-panel");
111
+
112
+ this.owner = owner;
113
+
114
+ try {
115
+ let reason: PanelCloseReason | undefined;
116
+
117
+ do {
118
+ const request = this.manager.nextPendingRequest();
119
+
120
+ if (!request) {
121
+ break;
122
+ }
123
+
124
+ // Claim it before showing it, so a request the user defers does not outrank one
125
+ // that has never been shown.
126
+ this.manager.markShown(request.id);
127
+
128
+ reason = await showQuestionPanel(ctx, this.manager, request, options);
129
+
130
+ // The session ended or changed branch while the overlay was up; this panel must
131
+ // not continue into the queue that replaced it.
132
+ if (this.generation !== generation || this.owner !== owner) {
133
+ return;
134
+ }
135
+ } while (
136
+ (reason === "settled" || reason === "withdrawn") &&
137
+ this.manager.getPendingRequests().length > 0
138
+ );
139
+ } finally {
140
+ if (this.generation === generation && this.owner === owner) {
141
+ this.owner = undefined;
142
+ }
143
+ }
144
+ }
145
+ }
146
+
147
+ /** One overlay for one request; `undefined` when it could not be opened at all. */
148
+ async function showQuestionPanel(
149
+ ctx: ExtensionContext,
150
+ manager: QuestionManager,
151
+ request: AskQuestionRequest,
152
+ options: OpenQuestionPanelOptions,
153
+ ): Promise<PanelCloseReason | undefined> {
154
+ let unsubscribe: (() => void) | undefined;
155
+
156
+ try {
157
+ return await ctx.ui.custom<PanelCloseReason>(
158
+ (tui, theme, keybindings, done) => {
159
+ const panel = new QuestionPanel({
160
+ manager,
161
+ request,
162
+ tui,
163
+ theme,
164
+ keybindings,
165
+ close: (reason) => done(reason),
166
+ onDeferred: options.onDeferred,
167
+ notify: (message, type) => ctx.ui.notify(message, type),
168
+ });
169
+
170
+ // The withdrawal comes from a tool call, not from this panel's input.
171
+ unsubscribe = manager.subscribe((event) => {
172
+ if (event.type === "request-withdrawn" && event.id === request.id) {
173
+ panel.closeWithdrawn();
174
+ ctx.ui.notify(
175
+ `The agent withdrew: ${requestHeaders(request)} (${event.reason})`,
176
+ "info",
177
+ );
178
+ }
179
+ });
180
+
181
+ return panel;
182
+ },
183
+ {
184
+ overlay: true,
185
+ overlayOptions: {
186
+ anchor: "center",
187
+ width: OVERLAY_WIDTH,
188
+ minWidth: OVERLAY_MIN_WIDTH,
189
+ maxHeight: OVERLAY_MAX_HEIGHT,
190
+ margin: OVERLAY_MARGIN,
191
+ },
192
+ },
193
+ );
194
+ } catch (error) {
195
+ // Opening failed: stop instead of retrying into the same error.
196
+ ctx.ui.notify(
197
+ `Question panel failed to open: ${error instanceof Error ? error.message : String(error)}`,
198
+ "error",
199
+ );
200
+
201
+ return undefined;
202
+ } finally {
203
+ unsubscribe?.();
204
+ }
205
+ }
206
+
207
+ export interface QuestionPanelOptions {
208
+ manager: QuestionManager;
209
+ request: AskQuestionRequest;
210
+ tui: TUI;
211
+ theme: Theme;
212
+ keybindings: KeybindingsManager;
213
+ close: (reason: PanelCloseReason) => void;
214
+ onDeferred?: () => void;
215
+ /** Reports a failed clipboard paste; only the extension holds `ctx.ui`. */
216
+ notify?: ExtensionUIContext["notify"];
217
+ }
218
+
219
+ /**
220
+ * Overlay adapter of one question request: it routes terminal input to the controller, owns
221
+ * the editor, and turns a controller transition into a render request, an editor mode change
222
+ * or a settle. Drawing is the renderer's job.
223
+ */
224
+ export class QuestionPanel implements Component, Focusable {
225
+ /** Set by the TUI when this overlay owns input. */
226
+ focused = false;
227
+
228
+ private readonly manager: QuestionManager;
229
+ private readonly request: AskQuestionRequest;
230
+ private readonly keybindings: KeybindingsManager;
231
+ private readonly requestRender: () => void;
232
+ private readonly terminalRows: () => number;
233
+ private readonly close: (reason: PanelCloseReason) => void;
234
+ private readonly onDeferred: (() => void) | undefined;
235
+ private readonly notify: ExtensionUIContext["notify"] | undefined;
236
+
237
+ private readonly controller: QuestionPanelController;
238
+ private readonly renderer: QuestionPanelRenderer;
239
+
240
+ private readonly editor: Editor;
241
+ private inputMode = false;
242
+ /** Set once the panel has closed itself, so a clipboard read that returns late is dropped. */
243
+ private closed = false;
244
+
245
+ /** Geometry of the last frame, for mouse hit-testing. */
246
+ private layout: QuestionPanelLayout | undefined;
247
+ /** Wheel position of the body; `undefined` lets the window follow the focused row. */
248
+ private bodyScroll: number | undefined;
249
+ private previewScroll = 0;
250
+
251
+ constructor(options: QuestionPanelOptions) {
252
+ this.manager = options.manager;
253
+ this.request = options.request;
254
+ this.keybindings = options.keybindings;
255
+ this.close = (reason) => {
256
+ this.closed = true;
257
+ options.close(reason);
258
+ };
259
+ this.onDeferred = options.onDeferred;
260
+ this.notify = options.notify;
261
+
262
+ this.requestRender = () => options.tui.requestRender();
263
+ this.terminalRows = () => options.tui.terminal.rows;
264
+ this.controller = new QuestionPanelController(options.request);
265
+ this.renderer = new QuestionPanelRenderer({
266
+ view: this.controller,
267
+ theme: options.theme,
268
+ });
269
+
270
+ const editorTheme: EditorTheme = {
271
+ borderColor: (text) => options.theme.fg("accent", text),
272
+ selectList: {
273
+ selectedPrefix: (text) => options.theme.fg("accent", text),
274
+ selectedText: (text) => options.theme.fg("accent", text),
275
+ description: (text) => options.theme.fg("muted", text),
276
+ scrollInfo: (text) => options.theme.fg("dim", text),
277
+ noMatch: (text) => options.theme.fg("warning", text),
278
+ },
279
+ };
280
+
281
+ this.editor = new Editor(options.tui, editorTheme, { paddingX: 1 });
282
+ this.editor.onSubmit = (text) => this.commitCustomAnswer(text);
283
+ // The draft is kept in sync while typing, so a persistence pass from any direction
284
+ // (Esc, shutdown, restart) sees the text even if the editor never lost focus.
285
+ this.editor.onChange = () => this.captureEditorDraft();
286
+
287
+ this.syncAutoInputMode();
288
+ }
289
+
290
+ handleInput(data: string): void {
291
+ // A key moves the focus, so the window goes back to following it.
292
+ this.bodyScroll = undefined;
293
+ this.withPreviewReset(() => this.handleKey(data));
294
+ }
295
+
296
+ private handleKey(data: string): void {
297
+ if (this.inputMode) {
298
+ // Esc belongs to the editor first: it drops back to the options while keeping
299
+ // what was written, and only a second Esc defers the whole panel.
300
+ if (this.isCancelKey(data)) {
301
+ this.exitInputMode();
302
+ return;
303
+ }
304
+
305
+ // pi's editor handles this key itself; this editor is a plain one that drops it.
306
+ if (this.isClipboardPasteKey(data)) {
307
+ void this.pasteFromClipboard();
308
+ return;
309
+ }
310
+
311
+ const step = this.editorTabStep(data);
312
+
313
+ if (step !== 0) {
314
+ this.leaveEditorForTab();
315
+ this.moveTab(step);
316
+ return;
317
+ }
318
+
319
+ this.editor.handleInput(data);
320
+ this.requestRender();
321
+ return;
322
+ }
323
+
324
+ if (this.isCancelKey(data)) {
325
+ this.defer();
326
+ return;
327
+ }
328
+
329
+ // Skip is Shift+S, and it is checked before the custom-row shortcut: a free-form
330
+ // question opens its editor by itself, so Esc has to leave a key that still skips,
331
+ // while a plain `s` stays the letter it is everywhere else - the start of an answer.
332
+ // A Kitty-protocol terminal reports a modified key as a CSI sequence instead of the
333
+ // uppercase byte, so matching `"S"` alone would leave skip unreachable there.
334
+ if (data === "S" || matchesKey(data, Key.shift("s"))) {
335
+ this.skipRequest();
336
+ return;
337
+ }
338
+
339
+ // The custom row is where answers are written, so printable keys and pastes start the
340
+ // editor there instead of being eaten by the single-key shortcuts below (digits, space,
341
+ // j/k), which keep working on the option rows and on the submit tab.
342
+ if (this.controller.isCustomRowFocused()) {
343
+ if (this.isClipboardPasteKey(data)) {
344
+ this.enterInputMode();
345
+ void this.pasteFromClipboard();
346
+ return;
347
+ }
348
+
349
+ if (isTypedCharacter(data) || data.startsWith(BRACKETED_PASTE_START)) {
350
+ this.enterInputMode(data);
351
+ return;
352
+ }
353
+ }
354
+
355
+ if (this.controller.isMultiQuestion) {
356
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
357
+ this.moveTab(1);
358
+ return;
359
+ }
360
+
361
+ if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) {
362
+ this.moveTab(-1);
363
+ return;
364
+ }
365
+ }
366
+
367
+ if (this.controller.isSubmitTab) {
368
+ if (this.isConfirmKey(data)) {
369
+ this.submit();
370
+ }
371
+ return;
372
+ }
373
+
374
+ if (this.isUpKey(data) || data === "k") {
375
+ this.moveRow(-1);
376
+ return;
377
+ }
378
+
379
+ if (this.isDownKey(data) || data === "j") {
380
+ this.moveRow(1);
381
+ return;
382
+ }
383
+
384
+ if (this.isConfirmKey(data)) {
385
+ this.confirmRow();
386
+ return;
387
+ }
388
+
389
+ if (matchesKey(data, Key.space)) {
390
+ this.toggleFocusedRow();
391
+ return;
392
+ }
393
+
394
+ const digit = /^[1-9]$/.exec(data);
395
+
396
+ if (digit) {
397
+ this.pickOption(Number(digit[0]) - 1);
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Fullscreen mode routes the mouse here; regular mode leaves it to the terminal, so every
403
+ * action below also has a key. Only the tab strip and the open editor are targets: a press
404
+ * on an option row stays unhandled, so the panel's text can still be selected and copied.
405
+ */
406
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
407
+ const layout = this.layout;
408
+
409
+ if (!layout) {
410
+ return undefined;
411
+ }
412
+
413
+ if (event.type === "wheel") {
414
+ // Claimed even when nothing moves: an unhandled wheel scrolls the transcript behind.
415
+ return { handled: true, render: this.scrollBy(layout, event) };
416
+ }
417
+
418
+ if (event.button !== "left") {
419
+ return undefined;
420
+ }
421
+
422
+ if (
423
+ this.inputMode &&
424
+ layout.editor &&
425
+ insideRect(layout.editor, event) &&
426
+ insideRect(layout.body, event)
427
+ ) {
428
+ return this.editor.handleMouse({
429
+ ...event,
430
+ x: event.x - layout.editor.x,
431
+ y: event.y - layout.editor.y,
432
+ width: layout.editor.width,
433
+ height: layout.editor.height,
434
+ });
435
+ }
436
+
437
+ if (event.type === "press") {
438
+ return this.withPreviewReset(() => this.pressTabAt(layout, event));
439
+ }
440
+
441
+ return undefined;
442
+ }
443
+
444
+ /**
445
+ * A preview belongs to one option, so moving the focus away and back starts it at its top;
446
+ * another question starts with the window on its focused row.
447
+ */
448
+ private withPreviewReset<T>(action: () => T): T {
449
+ const question = this.draft.currentIndex;
450
+ const option = this.draft.optionIndex;
451
+ const result = action();
452
+
453
+ if (this.draft.currentIndex !== question) {
454
+ this.bodyScroll = undefined;
455
+ }
456
+
457
+ if (this.draft.currentIndex !== question || this.draft.optionIndex !== option) {
458
+ this.previewScroll = 0;
459
+ }
460
+
461
+ return result;
462
+ }
463
+
464
+ render(width: number): string[] {
465
+ // The hardware cursor belongs to the editor only while it owns the keys.
466
+ this.editor.focused = this.focused && this.inputMode;
467
+
468
+ const frame = this.renderer.render(width, {
469
+ inputMode: this.inputMode,
470
+ maxBodyHeight: this.maxBodyHeight(),
471
+ editor: this.inputMode ? this.editor : undefined,
472
+ bodyScroll: this.bodyScroll,
473
+ previewScroll: this.previewScroll,
474
+ });
475
+
476
+ this.layout = frame.layout;
477
+
478
+ return frame.lines;
479
+ }
480
+
481
+ invalidate(): void {
482
+ this.renderer.invalidate();
483
+ }
484
+
485
+ /** The request was withdrawn under the panel; its draft goes with it. */
486
+ closeWithdrawn(): void {
487
+ if (!this.closed) {
488
+ this.close("withdrawn");
489
+ }
490
+ }
491
+
492
+ private get draft(): AskQuestionDraft {
493
+ return this.request.draft;
494
+ }
495
+
496
+ /**
497
+ * The preview under the pointer scrolls first; at its limits the wheel stays with it.
498
+ *
499
+ * Renders are batched, so several wheel events can arrive against one frame: each step
500
+ * builds on the scroll already requested, not on the offset that frame drew.
501
+ */
502
+ private scrollBy(layout: QuestionPanelLayout, event: TuiMouseEvent): boolean {
503
+ const delta = event.wheelDelta ?? 0;
504
+ const preview = layout.preview;
505
+
506
+ if (preview && preview.maxOffset > 0 && insideRect(preview, event)) {
507
+ const current = clamp(this.previewScroll, 0, preview.maxOffset);
508
+ const next = clamp(current + delta, 0, preview.maxOffset);
509
+
510
+ this.previewScroll = next;
511
+ return next !== current;
512
+ }
513
+
514
+ const body = layout.body;
515
+ const current = clamp(this.bodyScroll ?? body.offset, 0, body.maxOffset);
516
+ const next = clamp(current + delta, 0, body.maxOffset);
517
+
518
+ this.bodyScroll = next;
519
+ return next !== current;
520
+ }
521
+
522
+ /** The tab strip is the only row the mouse can act on; option rows stay keyboard-only. */
523
+ private pressTabAt(
524
+ layout: QuestionPanelLayout,
525
+ event: TuiMouseEvent,
526
+ ): TuiMouseEventResult | undefined {
527
+ const tab = layout.tabs.find((span) => insideSpan(span, event));
528
+
529
+ if (!tab) {
530
+ return undefined;
531
+ }
532
+
533
+ const target = tab.target;
534
+
535
+ if (target.kind === "step" || target.index !== this.draft.currentIndex) {
536
+ // Before the switch: the draft is stored under the question being left.
537
+ this.leaveEditorForTab();
538
+
539
+ if (target.kind === "step") {
540
+ this.moveTab(target.step);
541
+ } else {
542
+ this.controller.selectTab(target.index);
543
+ this.inputMode = false;
544
+ this.syncAutoInputMode();
545
+ }
546
+ }
547
+
548
+ this.requestRender();
549
+ return { handled: true, focus: true };
550
+ }
551
+
552
+ /**
553
+ * Tab step while the editor owns the keys. A free-form question opens its editor by itself,
554
+ * so without this the tabs could not be left by key. Tab has no other use in this editor,
555
+ * while the arrows move its cursor and only switch while there is no text to move through.
556
+ */
557
+ private editorTabStep(data: string): number {
558
+ if (!this.controller.isMultiQuestion) {
559
+ return 0;
560
+ }
561
+
562
+ if (matchesKey(data, Key.tab)) {
563
+ return 1;
564
+ }
565
+
566
+ if (matchesKey(data, Key.shift("tab"))) {
567
+ return -1;
568
+ }
569
+
570
+ if (this.editor.getText().length > 0) {
571
+ return 0;
572
+ }
573
+
574
+ if (matchesKey(data, Key.right)) {
575
+ return 1;
576
+ }
577
+
578
+ return matchesKey(data, Key.left) ? -1 : 0;
579
+ }
580
+
581
+ /** Moving away from the editor must keep what was typed, as `Esc` does. */
582
+ private leaveEditorForTab(): void {
583
+ if (this.inputMode) {
584
+ this.captureEditorDraft();
585
+ }
586
+ }
587
+
588
+ private moveRow(step: number): void {
589
+ this.controller.moveRow(step);
590
+ this.requestRender();
591
+ }
592
+
593
+ private moveTab(step: number): void {
594
+ this.controller.moveTab(step);
595
+ this.inputMode = false;
596
+ this.syncAutoInputMode();
597
+ this.requestRender();
598
+ }
599
+
600
+ private confirmRow(): void {
601
+ const question = this.controller.currentQuestion();
602
+ const row = this.controller.focusedRow();
603
+
604
+ if (!question || !row) {
605
+ return;
606
+ }
607
+
608
+ if (row.kind === "custom") {
609
+ this.enterInputMode();
610
+ return;
611
+ }
612
+
613
+ if (row.kind === "next") {
614
+ this.advanceAfterAnswer();
615
+ return;
616
+ }
617
+
618
+ if (question.multiSelect === true) {
619
+ this.toggleOption(row.index);
620
+ return;
621
+ }
622
+
623
+ this.answerWithOption(row.index);
624
+ }
625
+
626
+ private toggleFocusedRow(): void {
627
+ this.controller.toggleFocusedRow();
628
+ this.requestRender();
629
+ }
630
+
631
+ private toggleOption(index: number): void {
632
+ this.controller.toggleOption(index);
633
+ this.requestRender();
634
+ }
635
+
636
+ private pickOption(index: number): void {
637
+ const action = this.controller.pickOption(index);
638
+
639
+ if (action === "answer") {
640
+ this.advanceAfterAnswer();
641
+ return;
642
+ }
643
+
644
+ if (action === "toggle") {
645
+ this.requestRender();
646
+ }
647
+ }
648
+
649
+ private answerWithOption(index: number): void {
650
+ this.controller.answerWithOption(index);
651
+ this.advanceAfterAnswer();
652
+ }
653
+
654
+ private advanceAfterAnswer(): void {
655
+ if (this.controller.advanceAfterAnswer() === "submit") {
656
+ this.submit();
657
+ return;
658
+ }
659
+
660
+ this.inputMode = false;
661
+ this.syncAutoInputMode();
662
+ this.requestRender();
663
+ }
664
+
665
+ private enterInputMode(seed?: string): void {
666
+ const questionIndex = this.draft.currentIndex;
667
+ const draftText =
668
+ this.draft.customDrafts[questionIndex] ??
669
+ this.draft.answers[questionIndex]?.customText ??
670
+ "";
671
+
672
+ this.inputMode = true;
673
+ this.editor.setText(draftText);
674
+ this.editor.focused = this.focused;
675
+
676
+ if (seed !== undefined) {
677
+ // Let the editor place the key that opened it, so cursor and wrapping stay its job.
678
+ this.editor.handleInput(seed);
679
+ }
680
+
681
+ this.requestRender();
682
+ }
683
+
684
+ private exitInputMode(): void {
685
+ this.captureEditorDraft();
686
+ this.inputMode = false;
687
+ this.requestRender();
688
+ }
689
+
690
+ private captureEditorDraft(): void {
691
+ // A large paste lives behind a `[paste #1 +12 lines]` marker in the editor; only
692
+ // getExpandedText() returns the content that has to survive Esc and a restart.
693
+ const text = this.editor.getExpandedText();
694
+
695
+ this.draft.customDrafts[this.draft.currentIndex] = text.length > 0 ? text : undefined;
696
+ }
697
+
698
+ /**
699
+ * The read is async, so by the time it returns the editor may be closed or show another
700
+ * question; the paste is then dropped instead of landing in an answer it was not meant for.
701
+ */
702
+ private async pasteFromClipboard(): Promise<void> {
703
+ const question = this.draft.currentIndex;
704
+ let paste: ClipboardPaste | undefined;
705
+
706
+ try {
707
+ paste = await readClipboardPaste();
708
+ } catch (error) {
709
+ this.notify?.(
710
+ `Failed to paste from clipboard: ${error instanceof Error ? error.message : String(error)}`,
711
+ "error",
712
+ );
713
+ return;
714
+ }
715
+
716
+ if (!paste || this.closed || !this.inputMode || this.draft.currentIndex !== question) {
717
+ return;
718
+ }
719
+
720
+ let text = paste.text;
721
+
722
+ if (paste.isPath) {
723
+ // A path glued to a word would read as one token to the model.
724
+ const cursor = this.editor.getCursor();
725
+ const line = this.editor.getLines()[cursor.line] ?? "";
726
+ const before = line[cursor.col - 1];
727
+ const after = line[cursor.col];
728
+
729
+ if (before !== undefined && !/\s/.test(before)) {
730
+ text = ` ${text}`;
731
+ }
732
+
733
+ if (after !== undefined && !/\s/.test(after)) {
734
+ text = `${text} `;
735
+ }
736
+ }
737
+
738
+ this.editor.insertTextAtCursor(text);
739
+ this.requestRender();
740
+ }
741
+
742
+ private commitCustomAnswer(text: string): void {
743
+ const trimmed = text.trim();
744
+
745
+ // An empty answer would be indistinguishable from unanswered; keep the editor
746
+ // open so the user can type something or leave with Esc.
747
+ if (trimmed.length === 0) {
748
+ return;
749
+ }
750
+
751
+ this.controller.setCustomAnswer(trimmed);
752
+ this.inputMode = false;
753
+ this.advanceAfterAnswer();
754
+ }
755
+
756
+ /** Free-form questions have nothing to pick, so their editor opens immediately. */
757
+ private syncAutoInputMode(): void {
758
+ const question = this.controller.currentQuestion();
759
+ const unanswered = this.draft.answers[this.draft.currentIndex] === undefined;
760
+
761
+ this.inputMode =
762
+ question !== undefined && (question.options?.length ?? 0) === 0 && unanswered;
763
+
764
+ if (this.inputMode) {
765
+ this.editor.setText(this.draft.customDrafts[this.draft.currentIndex] ?? "");
766
+ }
767
+ }
768
+
769
+ private submit(): void {
770
+ if (!this.controller.prepareSubmit()) {
771
+ this.inputMode = false;
772
+ this.syncAutoInputMode();
773
+ this.requestRender();
774
+ return;
775
+ }
776
+
777
+ if (this.manager.submit(this.request.id, this.controller.collectAnswers())) {
778
+ this.close("settled");
779
+ }
780
+ }
781
+
782
+ private skipRequest(): void {
783
+ if (this.manager.skip(this.request.id)) {
784
+ this.close("settled");
785
+ }
786
+ }
787
+
788
+ private defer(): void {
789
+ if (this.inputMode) {
790
+ this.captureEditorDraft();
791
+ }
792
+
793
+ try {
794
+ // The draft is already on the request, so only the snapshot has to be written.
795
+ this.onDeferred?.();
796
+ } catch {
797
+ // A hook failure must not leave the overlay stuck, and it must not reach the
798
+ // terminal input loop either - the hook reports its own errors.
799
+ } finally {
800
+ this.close("deferred");
801
+ }
802
+ }
803
+
804
+ private isConfirmKey(data: string): boolean {
805
+ return (
806
+ matchesKey(data, Key.enter) ||
807
+ this.keybindings.matches(data, "tui.select.confirm") ||
808
+ this.keybindings.matches(data, "tui.input.submit")
809
+ );
810
+ }
811
+
812
+ private isCancelKey(data: string): boolean {
813
+ return matchesKey(data, Key.escape) || this.keybindings.matches(data, "tui.select.cancel");
814
+ }
815
+
816
+ private isClipboardPasteKey(data: string): boolean {
817
+ return this.keybindings.matches(data, "app.clipboard.pasteImage");
818
+ }
819
+
820
+ private isUpKey(data: string): boolean {
821
+ return matchesKey(data, Key.up) || this.keybindings.matches(data, "tui.select.up");
822
+ }
823
+
824
+ private isDownKey(data: string): boolean {
825
+ return matchesKey(data, Key.down) || this.keybindings.matches(data, "tui.select.down");
826
+ }
827
+
828
+ /**
829
+ * Upper bound for the body, not a target: the panel is only as tall as its content, and
830
+ * the bound is whatever room the terminal gives the overlay - a percentage of its height,
831
+ * itself limited by the overlay margins. There is no fixed row cap: a request with several
832
+ * questions is meant to be read in one piece, and clipping it to a constant would hide
833
+ * content the user has to answer. Scrolling only steps in when the content genuinely does
834
+ * not fit the screen.
835
+ */
836
+ private maxBodyHeight(): number {
837
+ const rows = this.terminalRows();
838
+ const usable = Math.min(Math.floor(rows * OVERLAY_HEIGHT_RATIO), rows - OVERLAY_MARGIN * 2);
839
+
840
+ return Math.max(1, usable - FRAME_HEIGHT);
841
+ }
842
+ }
843
+
844
+ function insideRect(rect: PanelRect, event: TuiMouseEvent): boolean {
845
+ return (
846
+ event.x >= rect.x &&
847
+ event.x < rect.x + rect.width &&
848
+ event.y >= rect.y &&
849
+ event.y < rect.y + rect.height
850
+ );
851
+ }
852
+
853
+ function insideSpan(span: PanelSpan, event: TuiMouseEvent): boolean {
854
+ return event.y === span.y && event.x >= span.start && event.x < span.end;
855
+ }
856
+
857
+ function clamp(value: number, min: number, max: number): number {
858
+ return Math.min(max, Math.max(min, value));
859
+ }
860
+
861
+ /** A single printable character, as opposed to an escape sequence or a control key. */
862
+ function isTypedCharacter(data: string): boolean {
863
+ return data.length > 0 && !data.startsWith("\x1b") && !/[\u0000-\u001f\u007f]/.test(data);
864
+ }