@d3ara1n/pi-ask-user 2.1.0 → 2.1.2

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 (4) hide show
  1. package/README.md +44 -32
  2. package/package.json +3 -2
  3. package/preview.png +0 -0
  4. package/src/index.ts +1368 -1267
package/src/index.ts CHANGED
@@ -30,15 +30,15 @@
30
30
 
31
31
  import type { ExtensionAPI, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
32
32
  import {
33
- type Component,
34
- Editor,
35
- type EditorTheme,
36
- type Focusable,
37
- Key,
38
- matchesKey,
39
- truncateToWidth,
40
- visibleWidth,
41
- wrapTextWithAnsi,
33
+ type Component,
34
+ Editor,
35
+ type EditorTheme,
36
+ type Focusable,
37
+ Key,
38
+ matchesKey,
39
+ truncateToWidth,
40
+ visibleWidth,
41
+ wrapTextWithAnsi,
42
42
  } from "@earendil-works/pi-tui";
43
43
  import { Type } from "typebox";
44
44
 
@@ -60,23 +60,23 @@ const ICON_ANSWER = "›"; // lead glyph on option-pick answers in the result ca
60
60
  // ────────────────────────────────────────────────────────────────────────────
61
61
 
62
62
  interface QuestionOption {
63
- label: string;
64
- description?: string;
65
- /** Rich preview shown in the right column when this option is focused. */
66
- preview?: string;
63
+ label: string;
64
+ description?: string;
65
+ /** Rich preview shown in the right column when this option is focused. */
66
+ preview?: string;
67
67
  }
68
68
 
69
69
  interface RenderOption extends QuestionOption {
70
- isOther?: boolean;
70
+ isOther?: boolean;
71
71
  }
72
72
 
73
73
  interface Question {
74
- tab: string;
75
- header: string;
76
- prompt?: string;
77
- options: QuestionOption[];
78
- multiSelect?: boolean;
79
- allowSkip?: boolean;
74
+ tab: string;
75
+ header: string;
76
+ prompt?: string;
77
+ options: QuestionOption[];
78
+ multiSelect?: boolean;
79
+ allowSkip?: boolean;
80
80
  }
81
81
 
82
82
  /** A committed answer. Discriminated by `kind` so every state carries exactly
@@ -93,35 +93,35 @@ interface Question {
93
93
  * - `skipped`: the user navigated past without answering (Tab/arrows).
94
94
  */
95
95
  type Answer =
96
- | { tab: string; kind: "single"; option: string }
97
- | { tab: string; kind: "custom"; text: string }
98
- | { tab: string; kind: "multi"; options: string[]; custom?: string }
99
- | { tab: string; kind: "skipped" };
96
+ | { tab: string; kind: "single"; option: string }
97
+ | { tab: string; kind: "custom"; text: string }
98
+ | { tab: string; kind: "multi"; options: string[]; custom?: string }
99
+ | { tab: string; kind: "skipped" };
100
100
 
101
101
  interface AskUserResult {
102
- questions: Question[];
103
- answers: Answer[];
104
- cancelled: boolean;
105
- /** Free-form note the user can attach on the review screen. Absent when empty. */
106
- message?: string;
102
+ questions: Question[];
103
+ answers: Answer[];
104
+ cancelled: boolean;
105
+ /** Free-form note the user can attach on the review screen. Absent when empty. */
106
+ message?: string;
107
107
  }
108
108
 
109
109
  /** Per-tab ephemeral UI state. Preserved across tab switches. */
110
110
  interface TabState {
111
- /** Cursor position (where ▸ is). */
112
- cursor: number;
113
- /** Vertical scroll offset for the options viewport. */
114
- scrollOffset: number;
115
- /** Whether "Type something." input mode is active for this tab. */
116
- inputMode: boolean;
117
- /** This tab's own editor instance (its draft lives inside; no cross-tab sync needed). */
118
- editor: Editor;
119
- /** Indices of committed options (multi-select). */
120
- multiChecked: Set<number>;
121
- /** Committed custom text for multi-select mode (kept alongside multiChecked, never overwriting it). Null if none. */
122
- customText: string | null;
123
- /** Committed single-select index (or -1 if none yet, -2 = answered via type-something). */
124
- selectedSingle: number;
111
+ /** Cursor position (where ▸ is). */
112
+ cursor: number;
113
+ /** Vertical scroll offset for the options viewport. */
114
+ scrollOffset: number;
115
+ /** Whether "Type something." input mode is active for this tab. */
116
+ inputMode: boolean;
117
+ /** This tab's own editor instance (its draft lives inside; no cross-tab sync needed). */
118
+ editor: Editor;
119
+ /** Indices of committed options (multi-select). */
120
+ multiChecked: Set<number>;
121
+ /** Committed custom text for multi-select mode (kept alongside multiChecked, never overwriting it). Null if none. */
122
+ customText: string | null;
123
+ /** Committed single-select index (or -1 if none yet, -2 = answered via type-something). */
124
+ selectedSingle: number;
125
125
  }
126
126
 
127
127
  // ────────────────────────────────────────────────────────────────────────────
@@ -129,48 +129,54 @@ interface TabState {
129
129
  // ────────────────────────────────────────────────────────────────────────────
130
130
 
131
131
  const QuestionOptionSchema = Type.Object({
132
- label: Type.String({ description: "Short display label for the option (shown on the selection row)" }),
133
- description: Type.Optional(
134
- Type.String({
135
- description: "Short explanation shown under the label (wraps). Add one when the label alone isn't self-explanatory.",
136
- }),
137
- ),
138
- preview: Type.Optional(
139
- Type.String({
140
- description:
141
- "Use this when `description` (a short one-liner) is not enough and the user genuinely benefits from seeing more detail in a side column — e.g. an ASCII layout demo, a code skeleton, a Pro/Cons breakdown, or the reasoning behind why this option is offered and what choosing it entails. Rendered verbatim in a side column (spaces/newlines preserved). Do NOT treat preview as extra text capacity. Every line competes for the user's attention against the option list; only add a preview when the content is worth reading, not just because there's room for more words. If a short `description` already conveys the option, leave preview empty. Most options need only `description`.",
142
- }),
143
- ),
132
+ label: Type.String({
133
+ description: "Short display label for the option (shown on the selection row)",
134
+ }),
135
+ description: Type.Optional(
136
+ Type.String({
137
+ description:
138
+ "Short explanation shown under the label (wraps). Add one when the label alone isn't self-explanatory.",
139
+ }),
140
+ ),
141
+ preview: Type.Optional(
142
+ Type.String({
143
+ description:
144
+ "Use this when `description` (a short one-liner) is not enough and the user genuinely benefits from seeing more detail in a side column — e.g. an ASCII layout demo, a code skeleton, a Pro/Cons breakdown, or the reasoning behind why this option is offered and what choosing it entails. Rendered verbatim in a side column (spaces/newlines preserved). Do NOT treat preview as extra text capacity. Every line competes for the user's attention against the option list; only add a preview when the content is worth reading, not just because there's room for more words. If a short `description` already conveys the option, leave preview empty. Most options need only `description`.",
145
+ }),
146
+ ),
144
147
  });
145
148
 
146
149
  const QuestionSchema = Type.Object({
147
- header: Type.String({
148
- description: "Short question title shown in the panel header, e.g. 'Which layout?'",
149
- }),
150
- tab: Type.String({
151
- description: "Short keyword that identifies this question. Shown on the tab bar when there are multiple questions, and returned in the result as the answer's prefix. Write it in the user's language (e.g. \"数据库\" or \"布局\" in a Chinese conversation, \"Database\" or \"Layout\" in English), not as a programmatic identifier like \"db_choice\". Must be unique across questions in one call." }),
152
- prompt: Type.Optional(
153
- Type.String({ description: "Optional longer body text shown under the header" }),
154
- ),
155
- options: Type.Array(QuestionOptionSchema, {
156
- description: "Available options. Pass 2-4; each needs a short `label` + a `description`, and a `preview` only when a description can't fully convey the option.",
157
- }),
158
- multiSelect: Type.Optional(
159
- Type.Boolean({
160
- description:
161
- "If true, the user may check multiple options (space toggles, enter commits). Default false.",
162
- }),
163
- ),
164
- allowSkip: Type.Optional(
165
- Type.Boolean({
166
- description:
167
- "If false, the user MUST answer before proceeding (Tab/Enter with no selection is blocked). Default true. Use false for required questions.",
168
- }),
169
- ),
150
+ header: Type.String({
151
+ description: "Short question title shown in the panel header, e.g. 'Which layout?'",
152
+ }),
153
+ tab: Type.String({
154
+ description:
155
+ 'Short keyword that identifies this question. Shown on the tab bar when there are multiple questions, and returned in the result as the answer\'s prefix. Write it in the user\'s language (e.g. "数据库" or "布局" in a Chinese conversation, "Database" or "Layout" in English), not as a programmatic identifier like "db_choice". Must be unique across questions in one call.',
156
+ }),
157
+ prompt: Type.Optional(
158
+ Type.String({ description: "Optional longer body text shown under the header" }),
159
+ ),
160
+ options: Type.Array(QuestionOptionSchema, {
161
+ description:
162
+ "Available options. Pass 2-4; each needs a short `label` + a `description`, and a `preview` only when a description can't fully convey the option.",
163
+ }),
164
+ multiSelect: Type.Optional(
165
+ Type.Boolean({
166
+ description:
167
+ "If true, the user may check multiple options (space toggles, enter commits). Default false.",
168
+ }),
169
+ ),
170
+ allowSkip: Type.Optional(
171
+ Type.Boolean({
172
+ description:
173
+ "If false, the user MUST answer before proceeding (Tab/Enter with no selection is blocked). Default true. Use false for required questions.",
174
+ }),
175
+ ),
170
176
  });
171
177
 
172
178
  const AskUserParams = Type.Object({
173
- questions: Type.Array(QuestionSchema, { description: "One or more questions to ask" }),
179
+ questions: Type.Array(QuestionSchema, { description: "One or more questions to ask" }),
174
180
  });
175
181
 
176
182
  // ────────────────────────────────────────────────────────────────────────────
@@ -190,63 +196,79 @@ const TOGGLE_HINT = "Ctrl+\\";
190
196
  // ────────────────────────────────────────────────────────────────────────────
191
197
 
192
198
  function wrapTab(index: number, total: number): number {
193
- if (total <= 0) return 0;
194
- return ((index % total) + total) % total;
199
+ if (total <= 0) return 0;
200
+ return ((index % total) + total) % total;
195
201
  }
196
202
 
197
203
  /** Build the full option list for a question, always appending the "Type something." custom-input row. */
198
204
  function buildOptions(q: Question): RenderOption[] {
199
- const opts: RenderOption[] = [...q.options];
200
- opts.push({ label: "Type something.", isOther: true });
201
- return opts;
205
+ const opts: RenderOption[] = [...q.options];
206
+ opts.push({ label: "Type something.", isOther: true });
207
+ return opts;
202
208
  }
203
209
 
204
210
  function isMulti(q: Question | undefined): boolean {
205
- return !!q?.multiSelect;
211
+ return !!q?.multiSelect;
206
212
  }
207
213
 
208
214
  /** Whether the user is allowed to skip this question (default true). */
209
215
  function canSkip(q: Question | undefined): boolean {
210
- return q?.allowSkip !== false;
216
+ return q?.allowSkip !== false;
211
217
  }
212
218
 
213
219
  /** Does this question use the two-column (options | preview) layout? */
214
220
  function isDualColumn(q: Question | undefined): boolean {
215
- if (!q) return false;
216
- return q.options.some((o) => o.preview);
221
+ if (!q) return false;
222
+ return q.options.some((o) => o.preview);
217
223
  }
218
224
 
219
- function newTabState(tui: TuiLike, theme: EditorTheme, tabIndex: number, onSubmit: (tabIndex: number, value: string) => void): TabState {
220
- const editor = new Editor(tui as never, theme);
221
- editor.onSubmit = (value) => onSubmit(tabIndex, value);
222
- return { cursor: 0, scrollOffset: 0, inputMode: false, editor, multiChecked: new Set(), customText: null, selectedSingle: -1 };
225
+ function newTabState(
226
+ tui: TuiLike,
227
+ theme: EditorTheme,
228
+ tabIndex: number,
229
+ onSubmit: (tabIndex: number, value: string) => void,
230
+ ): TabState {
231
+ const editor = new Editor(tui as never, theme);
232
+ editor.onSubmit = (value) => onSubmit(tabIndex, value);
233
+ return {
234
+ cursor: 0,
235
+ scrollOffset: 0,
236
+ inputMode: false,
237
+ editor,
238
+ multiChecked: new Set(),
239
+ customText: null,
240
+ selectedSingle: -1,
241
+ };
223
242
  }
224
243
 
225
- function errorResult(message: string, questions: Question[] = []): {
226
- content: { type: "text"; text: string }[];
227
- details: AskUserResult;
244
+ function errorResult(
245
+ message: string,
246
+ questions: Question[] = [],
247
+ ): {
248
+ content: { type: "text"; text: string }[];
249
+ details: AskUserResult;
228
250
  } {
229
- return {
230
- content: [{ type: "text", text: message }],
231
- details: { questions, answers: [], cancelled: true },
232
- };
251
+ return {
252
+ content: [{ type: "text", text: message }],
253
+ details: { questions, answers: [], cancelled: true },
254
+ };
233
255
  }
234
256
 
235
257
  /** Pad a string with trailing spaces to a visible width (left-justified). */
236
258
  function padRight(s: string, width: number): string {
237
- const v = visibleWidth(s);
238
- return v >= width ? s : s + " ".repeat(width - v);
259
+ const v = visibleWidth(s);
260
+ return v >= width ? s : s + " ".repeat(width - v);
239
261
  }
240
262
 
241
263
  /** Truncate to a visible width, appending “…” only when the text actually
242
264
  * overflows. (truncateToWidth's third arg is a fill, not a suffix, so we
243
265
  * reserve one column and append the ellipsis ourselves when needed.) */
244
266
  function truncForDisplay(text: string, maxW: number): string {
245
- if (maxW <= 0) return "";
246
- if (maxW === 1) return "…";
247
- const vw = visibleWidth(text);
248
- if (vw <= maxW) return text;
249
- return truncateToWidth(text, maxW - 1, "") + "…";
267
+ if (maxW <= 0) return "";
268
+ if (maxW === 1) return "…";
269
+ const vw = visibleWidth(text);
270
+ if (vw <= maxW) return text;
271
+ return truncateToWidth(text, maxW - 1, "") + "…";
250
272
  }
251
273
 
252
274
  /** Structured interpretation of an Answer for display/serialization.
@@ -254,31 +276,31 @@ function truncForDisplay(text: string, maxW: number): string {
254
276
  * formatAnswerText, result card's formatAnswer, execute's JSON payload)
255
277
  * derive from this, so they can never drift apart. */
256
278
  interface AnswerView {
257
- /** Human-readable text WITHOUT ANSI — e.g. "Sidebar" / "甲, 乙" /
258
- * "✎ 自定义文本" / "(none)" / "(skipped)". Consumers wrap it in color. */
259
- text: string;
260
- /** Theme color name for the whole text. */
261
- color: ThemeColor;
279
+ /** Human-readable text WITHOUT ANSI — e.g. "Sidebar" / "甲, 乙" /
280
+ * "✎ 自定义文本" / "(none)" / "(skipped)". Consumers wrap it in color. */
281
+ text: string;
282
+ /** Theme color name for the whole text. */
283
+ color: ThemeColor;
262
284
  }
263
285
 
264
286
  /** Interpret an Answer into display form. `customGlyph` (default "✎") prefixes
265
287
  * any custom text. Returns `(no answer)` / dim for an absent answer. */
266
288
  function describeAnswer(ans: Answer | undefined, customGlyph = ICON_OTHER): AnswerView {
267
- if (!ans) return { text: "(no answer)", color: "dim" };
268
- switch (ans.kind) {
269
- case "skipped":
270
- return { text: "(skipped)", color: "warning" };
271
- case "multi": {
272
- if (ans.options.length === 0 && !ans.custom) return { text: "(none)", color: "dim" };
273
- const parts = [...ans.options];
274
- if (ans.custom) parts.push(`${customGlyph} ${ans.custom}`);
275
- return { text: parts.join(", "), color: "text" };
276
- }
277
- case "custom":
278
- return { text: `${customGlyph} ${ans.text}`, color: "text" };
279
- case "single":
280
- return { text: ans.option, color: "text" };
281
- }
289
+ if (!ans) return { text: "(no answer)", color: "dim" };
290
+ switch (ans.kind) {
291
+ case "skipped":
292
+ return { text: "(skipped)", color: "warning" };
293
+ case "multi": {
294
+ if (ans.options.length === 0 && !ans.custom) return { text: "(none)", color: "dim" };
295
+ const parts = [...ans.options];
296
+ if (ans.custom) parts.push(`${customGlyph} ${ans.custom}`);
297
+ return { text: parts.join(", "), color: "text" };
298
+ }
299
+ case "custom":
300
+ return { text: `${customGlyph} ${ans.text}`, color: "text" };
301
+ case "single":
302
+ return { text: ans.option, color: "text" };
303
+ }
282
304
  }
283
305
 
284
306
  // ────────────────────────────────────────────────────────────────────────────
@@ -286,925 +308,986 @@ function describeAnswer(ans: Answer | undefined, customGlyph = ICON_OTHER): Answ
286
308
  // ────────────────────────────────────────────────────────────────────────────
287
309
 
288
310
  interface TuiLike {
289
- requestRender(): void;
311
+ requestRender(): void;
290
312
  }
291
313
 
292
314
  interface PanelCallbacks {
293
- onResult: (result: AskUserResult) => void;
315
+ onResult: (result: AskUserResult) => void;
294
316
  }
295
317
 
296
318
  class AskUserPanel implements Component, Focusable {
297
- focused = false;
298
-
299
- private questions: Question[];
300
- private theme: Theme;
301
- private tui: TuiLike;
302
- private cb: PanelCallbacks;
303
-
304
- // ── state ──
305
- private currentTab = 0;
306
- private answers = new Map<string, Answer>();
307
- private collapsed = false;
308
- private tabs: TabState[];
309
- /** Visible option rows (recomputed each render). */
310
- private optionViewportH = 8;
311
- /** Cursor row in the review summary (shown on the review tab). */
312
- private reviewCursor = 0;
313
- /** Vertical scroll offset for the review viewport. */
314
- private reviewScrollOffset = 0;
315
- /** Visible review rows (recomputed each render). */
316
- private reviewViewportH = 8;
317
- /** True while the user is editing the free-form "note to assistant" on the
318
- * review tab. While true, all input goes to messageEditor. */
319
- private messageEditing = false;
320
- /** Committed note text (trimmed). Empty string = no note. Lives only on the
321
- * review screen; the LLM cannot set it. */
322
- private messageText = "";
323
- /** Dedicated editor for the note. Single-line semantics: Enter saves (like
324
- * the per-question "Type something." editor). */
325
- private messageEditor: Editor;
326
-
327
- // ── render cache ──
328
- private cachedWidth?: number;
329
- private cachedLines?: string[];
330
-
331
- constructor(questions: Question[], tui: TuiLike, theme: Theme, cb: PanelCallbacks) {
332
- this.questions = questions;
333
- this.tui = tui;
334
- this.theme = theme;
335
- this.cb = cb;
336
-
337
- const editorTheme: EditorTheme = {
338
- borderColor: (s) => theme.fg("accent", s),
339
- selectList: {
340
- selectedPrefix: (t) => theme.fg("accent", t),
341
- selectedText: (t) => theme.fg("accent", t),
342
- description: (t) => theme.fg("muted", t),
343
- scrollInfo: (t) => theme.fg("dim", t),
344
- noMatch: (t) => theme.fg("warning", t),
345
- },
346
- };
347
- // Each tab owns its own Editor instance — its internal state IS that tab's
348
- // draft, so tab switching needs no text shuttling. This is the fix for the
349
- // draft-loss bug (previously a single shared editor was swapped in/out and
350
- // the swap was lossy across the input-mode / tab-switch boundary).
351
- this.tabs = questions.map((_, i) => newTabState(tui, editorTheme, i, (ti, v) => this.handleSubmit(ti, v)));
352
- // Dedicated editor for the review-screen note. Enter saves (single-line),
353
- // Esc returns to the review without saving — mirroring the per-question
354
- // "Type something." editor's semantics.
355
- this.messageEditor = new Editor(tui as never, editorTheme);
356
- this.messageEditor.onSubmit = (value) => this.handleMessageSubmit(value);
357
- }
358
-
359
- /** Shared submit logic bound to each tab's editor. */
360
- private handleSubmit(tabIndex: number, value: string): void {
361
- const q = this.questions[tabIndex];
362
- const st = this.tabs[tabIndex];
363
- if (!q || !st) return;
364
- const trimmed = value.trim();
365
- if (!trimmed) {
366
- // empty back to options. In multi-select mode, an empty submit also
367
- // clears any previously committed custom text (blank = "remove my custom
368
- // answer"), then re-commits the remaining checked options.
369
- st.inputMode = false;
370
- st.editor.setText("");
371
- if (isMulti(q)) {
372
- st.customText = null;
373
- if (!this.commitMultiAnswer(q, st)) this.answers.delete(q.tab);
374
- }
375
- if (tabIndex === this.currentTab) this.invalidate();
376
- return;
377
- }
378
- if (isMulti(q)) {
379
- // Multi-select: the custom text is an extra entry kept ALONGSIDE the
380
- // checked options — it must NOT overwrite them. (Previously this path
381
- // did answers.set with only the custom text, dropping every check.)
382
- // Committing custom text only records it we return to the OPTION LIST
383
- // (not advance) so the user can keep checking options and then press
384
- // Enter on an option to confirm the whole question. Advancing here used
385
- // to jump straight to review the moment the custom editor closed.
386
- st.customText = trimmed;
387
- this.commitMultiAnswer(q, st);
388
- st.inputMode = false;
389
- if (tabIndex === this.currentTab) this.invalidate();
390
- return;
391
- }
392
- this.answers.set(q.tab, {
393
- tab: q.tab,
394
- kind: "custom",
395
- text: trimmed,
396
- });
397
- st.selectedSingle = -1; // clear any prior option pick — answer is now custom
398
- st.inputMode = false;
399
- if (tabIndex === this.currentTab) {
400
- this.advanceAfterAnswer();
401
- }
402
- }
403
-
404
- /** Save the review-tab note: trim, store, return to the review tab.
405
- * currentTab already points at the review tab (note editing is only
406
- * entered from there), so we just clear the editing flag. Empty = no note. */
407
- private handleMessageSubmit(value: string): void {
408
- this.messageText = value.trim();
409
- this.messageEditing = false;
410
- this.invalidate();
411
- }
412
-
413
- /**
414
- * Multi-select commit: merge the checked options (st.multiChecked) together
415
- * with the committed custom text (st.customText) into one multi-select
416
- * answer. Returns false when there is nothing to commit (no checks and no
417
- * custom text), so the caller can delete the stale answer if desired.
418
- */
419
- private commitMultiAnswer(q: Question, st: TabState): boolean {
420
- const opts = buildOptions(q);
421
- const picked = Array.from(st.multiChecked)
422
- .sort((a, b) => a - b)
423
- .map((i) => opts[i])
424
- .filter((o): o is RenderOption => !!o && !o.isOther);
425
- const labels = picked.map((o) => o.label);
426
- const customText = st.customText;
427
- // Empty commit = no option picks AND no custom text. (A skippable
428
- // multi-select still records an explicit empty answer via the Enter
429
- // path see handleInput so this function returning false just means
430
- // "nothing to record here".)
431
- if (labels.length === 0 && !customText) return false;
432
- const ans: Answer = {
433
- tab: q.tab,
434
- kind: "multi",
435
- options: labels,
436
- };
437
- if (customText) ans.custom = customText;
438
- this.answers.set(q.tab, ans);
439
- return true;
440
- }
441
-
442
- // ── accessors ──
443
-
444
- /** Total number of tabs: one per question, plus the trailing review tab. */
445
- private get totalTabs(): number {
446
- return this.questions.length + 1;
447
- }
448
-
449
- /** The review tab sits at index === questions.length (the last tab).
450
- * While true, the panel renders the review summary instead of a question. */
451
- private get isReviewTab(): boolean {
452
- return this.currentTab === this.questions.length;
453
- }
454
-
455
- private currentQuestion(): Question | undefined {
456
- return this.questions[this.currentTab];
457
- }
458
-
459
- private currentTabState(): TabState {
460
- return this.tabs[this.currentTab]!;
461
- }
462
-
463
- private currentOptions(): RenderOption[] {
464
- const q = this.currentQuestion();
465
- return q ? buildOptions(q) : [];
466
- }
467
-
468
- private advanceAfterAnswer(): void {
469
- // Advance to the next tab. The review tab is the last tab, so answering
470
- // the final question lands the user on the review tab (where Enter
471
- // submits). Navigation is now uniform: review is just the next tab,
472
- // reached by the same Tab/→ keys as any question no special "enter
473
- // review" step. Safe because this is only called from question tabs
474
- // (currentTab < questions.length), so currentTab + 1 <= reviewTabIndex.
475
- this.switchTab(this.currentTab + 1);
476
- }
477
-
478
- /**
479
- * Called before navigating AWAY from a question tab (Tab/→/←/Shift+Tab).
480
- * Resolves the current question's state so it can be left cleanly:
481
- *
482
- * - Already committed (answers.has): leave freely.
483
- * - Multi-select with UNCOMMITTED checks (or a typed custom text): a check
484
- * IS an answer commit it first, then leave. Navigating away with
485
- * pending checks must submit them (not skip, not block), regardless of
486
- * allowSkip, because the user has already expressed a choice. (Single-
487
- * select commits on Space, so it never has pending uncommitted state.)
488
- * - Nothing selected at all:
489
- * allowSkip true → record a skipped answer, allow leaving.
490
- * allowSkip false block (a required question must be answered).
491
- *
492
- * Returns true when navigation may proceed.
493
- */
494
- private prepareQuestionForLeave(): boolean {
495
- const q = this.currentQuestion();
496
- if (!q) return true;
497
- if (this.answers.has(q.tab)) return true;
498
- const st = this.currentTabState();
499
- // Multi-select: uncommitted checks count as an answer — commit them,
500
- // then leave. commitMultiAnswer only returns false when there's nothing
501
- // to commit (no checks, no custom), which the guard already rules out.
502
- if (isMulti(q) && (st.multiChecked.size > 0 || !!st.customText)) {
503
- this.commitMultiAnswer(q, st);
504
- return true;
505
- }
506
- if (!canSkip(q)) return false; // required question, nothing chosen: block
507
- this.answers.set(q.tab, {
508
- tab: q.tab,
509
- kind: "skipped",
510
- });
511
- return true;
512
- }
513
-
514
- private submit(cancelled: boolean): void {
515
- this.cb.onResult({
516
- questions: this.questions,
517
- answers: Array.from(this.answers.values()),
518
- cancelled,
519
- // Only attach the note when non-empty. A cancelled submit still carries
520
- // the note if the user wrote one (it may explain why they cancelled).
521
- message: this.messageText || undefined,
522
- });
523
- }
524
-
525
- private setCollapsed(next: boolean): void {
526
- if (this.collapsed === next) return;
527
- this.collapsed = next;
528
- this.invalidate();
529
- }
530
-
531
- private clampScrollToCursor(): void {
532
- const opts = this.currentOptions();
533
- if (opts.length === 0) return;
534
- const viewH = this.optionViewportH;
535
- const st = this.currentTabState();
536
- if (st.cursor < st.scrollOffset) st.scrollOffset = st.cursor;
537
- else if (st.cursor >= st.scrollOffset + viewH) st.scrollOffset = st.cursor - viewH + 1;
538
- if (st.scrollOffset < 0) st.scrollOffset = 0;
539
- }
540
-
541
- // ── input ──
542
-
543
- handleInput(data: string): void {
544
- // 1. Note editor (messageEditing): owns all input while active. Esc
545
- // returns to the review tab (currentTab already points there — note
546
- // editing is only entered from the review tab).
547
- if (this.messageEditing) {
548
- if (matchesKey(data, Key.escape)) {
549
- this.messageEditing = false;
550
- this.invalidate();
551
- return;
552
- }
553
- this.messageEditor.handleInput(data);
554
- this.invalidate();
555
- return;
556
- }
557
-
558
- // 2. Collapse toggle (global, any tab).
559
- if (matchesKey(data, TOGGLE_KEY)) {
560
- this.setCollapsed(!this.collapsed);
561
- return;
562
- }
563
-
564
- // 3. Collapsed: only Esc (cancel) is meaningful.
565
- if (this.collapsed) {
566
- if (matchesKey(data, Key.escape)) this.submit(true);
567
- return;
568
- }
569
-
570
- // 4. Question tab + "Type something." input mode: the editor owns ALL
571
- // editing keys (Tab, arrows, etc.). Tab is NOT hijacked for tab
572
- // switching here, because that would break indentation / cursor
573
- // movement. Esc exits back to the option list. The review tab has no
574
- // input mode (it never edits options), so it skips this branch the
575
- // `!this.isReviewTab` short-circuit also avoids indexing tabs[] OOB.
576
- if (!this.isReviewTab && this.currentTabState().inputMode) {
577
- if (matchesKey(data, Key.escape)) {
578
- const st = this.currentTabState();
579
- st.inputMode = false;
580
- // Keep the editor content (per-tab editor preserves it as draft).
581
- this.invalidate();
582
- return;
583
- }
584
- this.currentTabState().editor.handleInput(data);
585
- this.invalidate();
586
- return;
587
- }
588
-
589
- // 5. Esc = cancel submission (any tab, when not editing).
590
- if (matchesKey(data, Key.escape)) {
591
- this.submit(true);
592
- return;
593
- }
594
-
595
- // 6. Shared tab navigation — Tab/→ forward, Shift+Tab/← backward.
596
- // Runs on BOTH question tabs and the review tab, which is what makes
597
- // the review reachable by the same keys as any question. The skip
598
- // check only applies when LEAVING a question tab (never the review).
599
- if (this.handleTabNavigation(data)) return;
600
-
601
- // 7. Review tab: ↑↓ move · Space edit · Enter submit. (Esc + tab
602
- // navigation were already handled above.)
603
- if (this.isReviewTab) {
604
- return this.handleReviewInput(data);
605
- }
606
-
607
- // 8. Question tab: ↑↓ move cursor · Space toggle/commit · Enter confirm.
608
- const st = this.currentTabState();
609
- const q = this.currentQuestion();
610
- if (!q) return;
611
- const opts = this.currentOptions();
612
- const multi = isMulti(q);
613
-
614
- // Up / Down — moves ONLY the cursor (), does not change selection
615
- if (matchesKey(data, Key.up)) {
616
- if (st.cursor > 0) {
617
- st.cursor--;
618
- this.clampScrollToCursor();
619
- this.invalidate();
620
- }
621
- return;
622
- }
623
- if (matchesKey(data, Key.down)) {
624
- if (st.cursor < opts.length - 1) {
625
- st.cursor++;
626
- this.clampScrollToCursor();
627
- this.invalidate();
628
- }
629
- return;
630
- }
631
- if (matchesKey(data, Key.pageUp)) {
632
- st.cursor = Math.max(0, st.cursor - Math.max(1, this.optionViewportH));
633
- this.clampScrollToCursor();
634
- this.invalidate();
635
- return;
636
- }
637
- if (matchesKey(data, Key.pageDown)) {
638
- st.cursor = Math.min(opts.length - 1, st.cursor + Math.max(1, this.optionViewportH));
639
- this.clampScrollToCursor();
640
- this.invalidate();
641
- return;
642
- }
643
-
644
- // Space — the "interact" key: select (single), toggle (multi), or EDIT
645
- // (the "Type something." row). It never advances — that's Enter's job.
646
- // This mirrors the review tab (where Space opens an entry for editing),
647
- // so "the key that modifies things" is the same on every screen.
648
- if (matchesKey(data, Key.space)) {
649
- const opt = opts[st.cursor];
650
- if (!opt) return;
651
- if (opt.isOther) {
652
- // Enter edit mode for a custom answer. Prefill with any committed
653
- // custom text so the user edits rather than retypes. Per-tab
654
- // editor keeps the text for Esc-discard semantics automatically.
655
- // - Single-select: custom text lives in the `custom` answer.
656
- // - Multi-select: it lives in st.customText (kept alongside checks).
657
- st.inputMode = true;
658
- const existing = this.answers.get(q.tab);
659
- const prefill = multi ? st.customText : existing?.kind === "custom" ? existing.text : null;
660
- if (prefill) st.editor.setText(prefill);
661
- this.invalidate();
662
- return;
663
- }
664
- if (multi) {
665
- if (st.multiChecked.has(st.cursor)) st.multiChecked.delete(st.cursor);
666
- else st.multiChecked.add(st.cursor);
667
- this.invalidate();
668
- return;
669
- }
670
- // single-select: mark the selection WITHOUT advancing (stay on question)
671
- st.selectedSingle = st.cursor;
672
- this.answers.set(q.tab, {
673
- tab: q.tab,
674
- kind: "single",
675
- option: opt.label,
676
- });
677
- this.invalidate();
678
- return;
679
- }
680
-
681
- // Enter — confirm + advance to the next tab. It does NOT enter edit mode
682
- // (Space owns that now), keeping the two keys orthogonal: Space modifies,
683
- // Enter commits. Single-select commits the cursor position and advances;
684
- // multi-select commits the currently checked options as-is and advances
685
- // (Space owns checking, so Enter no longer auto-checks the cursor option).
686
- if (matchesKey(data, Key.enter)) {
687
- const opt = opts[st.cursor];
688
- if (!opt) return;
689
- if (opt.isOther && !multi) {
690
- // Single-select isOther: Enter never edits (Space owns that). Only
691
- // advance if a custom answer was already committed; otherwise stay.
692
- if (this.answers.get(q.tab)?.kind === "custom") {
693
- this.advanceAfterAnswer();
694
- }
695
- return;
696
- }
697
- if (multi) {
698
- // Commit the current checks (+ any custom text) and advance. For a
699
- // skippable multi-select, committing an EMPTY selection is still a
700
- // commit — Enter means "submit (even if empty) and move on", not
701
- // "skip" (Tab/arrows do skipping). So we record an explicit empty
702
- // answer and advance; a required question (!canSkip) with an empty
703
- // selection stays put, since it must have at least one pick.
704
- if (this.commitMultiAnswer(q, st)) {
705
- this.advanceAfterAnswer();
706
- } else if (canSkip(q)) {
707
- this.answers.set(q.tab, {
708
- tab: q.tab,
709
- kind: "multi",
710
- options: [],
711
- });
712
- this.advanceAfterAnswer();
713
- }
714
- return;
715
- }
716
- // single-select: commit cursor position as the selection, then advance
717
- st.selectedSingle = st.cursor;
718
- this.answers.set(q.tab, {
719
- tab: q.tab,
720
- kind: "single",
721
- option: opt.label,
722
- });
723
- this.advanceAfterAnswer();
724
- return;
725
- }
726
- }
727
-
728
- /** Switch tab. Each tab owns its own Editor instance, so draft preservation
729
- * is automatic — no text shuttling required. */
730
- private switchTab(next: number): void {
731
- if (next === this.currentTab) return;
732
- this.currentTab = next;
733
- this.invalidate();
734
- }
735
-
736
- /** Shared tab navigation, invoked from handleInput for BOTH question tabs
737
- * and the review tab. Returns true when the key was consumed.
738
- *
739
- * - Tab / → : forward. Tab WRAPS through every tab (questions → review →
740
- * first question); STOPS at the review tab (boundary).
741
- * - Shift+Tab / ← : backward. Shift+Tab wraps; ← stops at the first
742
- * question.
743
- *
744
- * Leaving a question tab may need to commit pending multi-select checks
745
- * or record a skip (when it's unanswered and required) — that's handled
746
- * by prepareQuestionForLeave. Leaving the review tab never needs that
747
- * check (it isn't a question), so →/Tab work freely from review. */
748
- private handleTabNavigation(data: string): boolean {
749
- if (this.totalTabs <= 1) return false;
750
- // Forward
751
- if (matchesKey(data, Key.tab)) {
752
- if (!this.isReviewTab && !this.prepareQuestionForLeave()) return true; // required: blocked
753
- this.switchTab(wrapTab(this.currentTab + 1, this.totalTabs));
754
- return true;
755
- }
756
- if (matchesKey(data, Key.right)) {
757
- if (!this.isReviewTab && !this.prepareQuestionForLeave()) return true; // required: blocked
758
- if (this.currentTab + 1 >= this.totalTabs) return true; // stop at review
759
- this.switchTab(this.currentTab + 1);
760
- return true;
761
- }
762
- // Backward
763
- if (matchesKey(data, Key.shift("tab"))) {
764
- this.switchTab(wrapTab(this.currentTab - 1, this.totalTabs));
765
- return true;
766
- }
767
- if (matchesKey(data, Key.left)) {
768
- if (this.currentTab - 1 < 0) return true; // stop at first question
769
- this.switchTab(this.currentTab - 1);
770
- return true;
771
- }
772
- return false;
773
- }
774
-
775
- /** Handle input specific to the review tab. Esc and tab navigation
776
- * (Tab/←/→) are already handled upstream in handleInput, so here we only
777
- * deal with: ↑↓/PgUp/PgDn (move the review cursor), Space (open the entry
778
- * under the cursor for editing), and Enter (submit the whole review).
779
- *
780
- * The review list has N question entries plus one trailing "note to
781
- * assistant" entry (index N), so the cursor ranges over [0, N]. */
782
- private handleReviewInput(data: string): void {
783
- const n = this.questions.length;
784
- const total = n + 1; // include the note entry
785
- // ↑/↓/PgUp/PgDn move the review cursor over [0, total-1]
786
- if (matchesKey(data, Key.up)) {
787
- if (this.reviewCursor > 0) { this.reviewCursor--; this.invalidate(); }
788
- return;
789
- }
790
- if (matchesKey(data, Key.down)) {
791
- if (this.reviewCursor < total - 1) { this.reviewCursor++; this.invalidate(); }
792
- return;
793
- }
794
- if (matchesKey(data, Key.pageUp)) {
795
- this.reviewCursor = Math.max(0, this.reviewCursor - Math.max(1, this.reviewViewportH));
796
- this.invalidate();
797
- return;
798
- }
799
- if (matchesKey(data, Key.pageDown)) {
800
- this.reviewCursor = Math.min(total - 1, this.reviewCursor + Math.max(1, this.reviewViewportH));
801
- this.invalidate();
802
- return;
803
- }
804
- // Space "select" the entry under the cursor: jump into editing it.
805
- // (Mirrors the option screens, where Space = select/toggle.)
806
- if (matchesKey(data, Key.space)) {
807
- if (this.reviewCursor === n) {
808
- // Note entry: open the note editor. Prefill with the committed note
809
- // (if any) so the user can tweak rather than retype.
810
- this.messageEditing = true;
811
- if (this.messageText) this.messageEditor.setText(this.messageText);
812
- this.invalidate();
813
- return;
814
- }
815
- // Question entry: switch to that question's tab for editing.
816
- // switchTab early-returns when next === currentTab, which is fine that
817
- // only happens on a single-question call where we're already on the
818
- // question; nothing to redraw.
819
- this.switchTab(this.reviewCursor);
820
- return;
821
- }
822
- // Enter — submit the whole review, no matter where the cursor sits.
823
- if (matchesKey(data, Key.enter)) {
824
- this.submit(false);
825
- return;
826
- }
827
- }
828
-
829
- // ── render ──
830
-
831
- render(width: number): string[] {
832
- if (this.collapsed) {
833
- this.cachedWidth = width;
834
- this.cachedLines = this.renderCollapsed(width);
835
- return this.cachedLines;
836
- }
837
- if (this.cachedLines && this.cachedWidth === width) {
838
- return this.cachedLines;
839
- }
840
- this.cachedWidth = width;
841
- this.cachedLines = this.renderExpanded(width);
842
- return this.cachedLines;
843
- }
844
-
845
- private renderCollapsed(width: number): string[] {
846
- const th = this.theme;
847
- const qParts = this.questions.map((q, i) => {
848
- const done = this.answers.has(q.tab);
849
- const active = i === this.currentTab && !this.isReviewTab;
850
- const mark = active ? "▸" : done ? "✓" : "○";
851
- const color = active ? "accent" : done ? "success" : "dim";
852
- return th.fg(color, `${q.tab}${mark}`);
853
- });
854
- const reviewPart = this.isReviewTab
855
- ? th.fg("accent", "Review▸")
856
- : th.fg("dim", "Review○");
857
- const tabsPart = [...qParts, reviewPart].join(th.fg("dim", " "));
858
- const inner = `${tabsPart} ${th.fg("dim", ` ${TOGGLE_HINT} expand `)}${th.fg("dim", " Esc cancel ")}`;
859
- const line =
860
- th.fg("border", "│") + inner + " ".repeat(Math.max(0, width - 2 - visibleWidth(inner))) + th.fg("border", "│");
861
- return [truncateToWidth(line, width)];
862
- }
863
-
864
- /** Build the tab-bar content line (without border wrapping). Shared by the
865
- * question screen and the review screen so the bar is always visible —
866
- * the review tab is a real tab, so it must highlight when active just like
867
- * any question. Callers wrap the returned string in their own row() so the
868
- * border color matches the surrounding screen. */
869
- private renderTabBarContent(th: Theme): string {
870
- const tabCells = this.questions.map((q, i) => {
871
- const active = i === this.currentTab;
872
- const ans = this.answers.get(q.tab);
873
- let mark = " ";
874
- let baseColor: import("@earendil-works/pi-coding-agent").ThemeColor = active ? "accent" : "muted";
875
- if (ans?.kind === "skipped") { mark = "—"; baseColor = "warning"; }
876
- else if (ans) { mark = "✓"; baseColor = "success"; }
877
- else if (active) mark = "▸";
878
- const color = active ? "accent" : baseColor;
879
- return th.fg(color, `${mark} ${q.tab}`);
880
- });
881
- const reviewActive = this.isReviewTab;
882
- const reviewMark = reviewActive ? "▸" : " ";
883
- const reviewColor: import("@earendil-works/pi-coding-agent").ThemeColor = reviewActive ? "accent" : "muted";
884
- const reviewCell = th.fg(reviewColor, `${reviewMark} [ Review ]`);
885
- const sep = th.fg("dim", " │");
886
- return ` ${tabCells.join(th.fg("dim", " "))}${sep}${reviewCell}`;
887
- }
888
-
889
- private renderExpanded(width: number): string[] {
890
- const th = this.theme;
891
- const innerW = Math.max(20, width - 2);
892
- const lines: string[] = [];
893
- const row = (content: string) => th.fg("border", "│") + padRight(content, innerW) + th.fg("border", "│");
894
-
895
- if (this.messageEditing) {
896
- return this.renderMessageEditor(width, innerW, th);
897
- }
898
- if (this.isReviewTab) {
899
- return this.renderReview(width, innerW, th);
900
- }
901
-
902
- lines.push(th.fg("border", `╭${"─".repeat(innerW)}╮`));
903
-
904
- // ── Tab bar ──
905
- // Always shown: there is always at least one question tab plus the
906
- // trailing review tab. renderTabBarContent is shared with the review
907
- // screen so the active tab stays visible across every screen.
908
- lines.push(row(this.renderTabBarContent(th)));
909
- lines.push(row(""));
910
-
911
- // ── Question header ──
912
- const q = this.currentQuestion();
913
- const multi = isMulti(q);
914
- const dual = isDualColumn(q);
915
- const progress = this.questions.length > 1 ? ` [${this.currentTab + 1}/${this.questions.length}]` : "";
916
- const tag = multi ? th.fg("dim", " (multi)") : "";
917
- const headerText = truncateToWidth(
918
- ` ${th.fg("accent", th.bold(q?.header ?? ""))}${tag}${th.fg("dim", progress)}`,
919
- innerW,
920
- "",
921
- );
922
- lines.push(th.fg("border", "│") + padRight(headerText, innerW) + th.fg("border", "│"));
923
-
924
- // ── Prompt body ──
925
- if (q?.prompt) {
926
- for (const w of wrapTextWithAnsi(th.fg("muted", q.prompt), innerW - 2)) lines.push(row(` ${w}`));
927
- }
928
- // 空行分隔 header/prompt options。原来只在有 prompt 时才加,导致无
929
- // prompt 的问题其标题与选项紧贴("粘在一起")。现在无条件加。
930
- lines.push(row(""));
931
-
932
- // ── Body: options / preview / input editor ──
933
- const st = this.currentTabState();
934
- if (st.inputMode) {
935
- for (const el of st.editor.render(innerW - 2)) lines.push(row(` ${el}`));
936
- lines.push(row(th.fg("dim", " Esc back to options · Enter submit")));
937
- } else if (dual && q) {
938
- lines.push(...this.renderDualColumn(q, st, innerW, row, th));
939
- } else {
940
- lines.push(...this.renderSingleColumn(st, innerW, row, th));
941
- }
942
-
943
- // ── Footer ──
944
- lines.push(th.fg("border", `├${"─".repeat(innerW)}┤`));
945
- const doneCount = Array.from(this.answers.keys()).length;
946
- const left =
947
- this.questions.length > 1 ? th.fg("dim", ` ${doneCount}/${this.questions.length} answered · `) : th.fg("dim", " ");
948
- const hint = multi
949
- ? `${TOGGLE_HINT} collapse · ↑↓ move · Space toggle · Enter confirm · Esc cancel`
950
- : `${TOGGLE_HINT} collapse · ↑↓ move · Space select · Enter confirm · Esc cancel`;
951
- lines.push(row(`${left}${th.fg("dim", hint)}`));
952
- lines.push(th.fg("border", `╰${"─".repeat(innerW)}╯`));
953
- return lines;
954
- }
955
-
956
- /** Render the option row glyph. The cursor (▸) is independent of selection. */
957
- private optionGlyph(opt: RenderOption, index: number, st: TabState, multi: boolean, th: Theme, isCursor: boolean, customAnswered: boolean): string {
958
- if (opt.isOther) {
959
- // "Type something." is filled when a custom answer was committed.
960
- return customAnswered
961
- ? th.fg("success", ICON_RADIO_FILLED)
962
- : th.fg("dim", ICON_OTHER);
963
- }
964
- if (multi) {
965
- const checked = st.multiChecked.has(index);
966
- return checked ? th.fg("success", ICON_CHECK_FILLED) : th.fg("dim", ICON_CHECK_EMPTY);
967
- }
968
- // single: filled only when committed (selectedSingle), not on cursor hover
969
- const filled = st.selectedSingle === index;
970
- return filled ? th.fg("success", ICON_RADIO_FILLED) : th.fg("dim", ICON_RADIO_EMPTY);
971
- }
972
-
973
- /** Format an answer for the review summary. Delegates to describeAnswer
974
- * (single source of truth), then wraps in the theme color + truncates. */
975
- private formatAnswerText(ans: Answer | undefined, maxW: number, th: Theme): string {
976
- const view = describeAnswer(ans);
977
- const text = truncForDisplay(view.text, maxW);
978
- return th.fg(view.color, text);
979
- }
980
-
981
- /** Clamp the review scroll offset so the cursor stays visible. The review
982
- * list has N questions + 1 note entry, so the cursor may equal N. */
983
- private clampReviewScroll(): void {
984
- const total = this.questions.length + 1;
985
- if (total === 0) return;
986
- const viewH = this.reviewViewportH;
987
- if (this.reviewCursor < this.reviewScrollOffset) this.reviewScrollOffset = this.reviewCursor;
988
- else if (this.reviewCursor >= this.reviewScrollOffset + viewH)
989
- this.reviewScrollOffset = this.reviewCursor - viewH + 1;
990
- if (this.reviewScrollOffset < 0) this.reviewScrollOffset = 0;
991
- }
992
-
993
- /** Review summary: one question per entry (header + answer), plus a trailing
994
- * "note to assistant" entry. Viewport scrolling reuses the option-screen
995
- * layout primitives. */
996
- private renderReview(width: number, innerW: number, th: Theme): string[] {
997
- const lines: string[] = [];
998
- // Review uses a distinct border color (success/green) so it's visually
999
- // unmistakable as the review/confirm screen — not another question. The
1000
- // question screen keeps the default "border" color.
1001
- const bc: import("@earendil-works/pi-coding-agent").ThemeColor = "success";
1002
- const row = (content: string) => th.fg(bc, "") + padRight(content, innerW) + th.fg(bc, "│");
1003
- lines.push(th.fg(bc, `╭${"─".repeat(innerW)}╮`));
1004
- lines.push(row(this.renderTabBarContent(th)));
1005
- lines.push(row(""));
1006
- lines.push(row(` ${th.fg("accent", th.bold("Review your answers"))}`));
1007
- lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1008
- const n = this.questions.length;
1009
- const total = n + 1; // +1 for the note entry
1010
- // Body indent (6 cols): questions and the note carry a 2-visible-col marker
1011
- // (`1.` / `2.` … or `✎ ` for the note) right after the cursor, plus a
1012
- // separator space, so every title starts at the same column. The body is
1013
- // indented one past that so header vs content stay visually distinct —
1014
- // previously the body sat at 5 cols and the note's icon pushed its title
1015
- // out of alignment with the question titles.
1016
- const bodyIndent = " "; // 6 spaces
1017
- const maxW = innerW - 2 - bodyIndent.length;
1018
- this.reviewViewportH = Math.max(3, Math.min(total, 10));
1019
- this.clampReviewScroll();
1020
- const start = this.reviewScrollOffset;
1021
- const end = Math.min(total, start + this.reviewViewportH);
1022
- for (let i = start; i < end; i++) {
1023
- const isCursor = i === this.reviewCursor;
1024
- const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1025
- const headerColor: import("@earendil-works/pi-coding-agent").ThemeColor = isCursor ? "accent" : "muted";
1026
- // marker: a fixed 2-visible-col slot + 1 separator space, so every title
1027
- // (questions + note) aligns regardless of icon width. `1.` is 2 cols;
1028
- // the note's is 1 col, padded to `✎ ` (hence one extra space between
1029
- // and its title — the deliberate tradeoff of this layout).
1030
- // ── Note entry (index n): always last, two rows like a question. ──
1031
- if (i === n) {
1032
- // 空行分隔:note 是异类条目(附加留言,非问答),用空行和上方
1033
- // 问答列表隔开。保持简单,不用点线/装饰。
1034
- lines.push(row(""));
1035
- const marker = th.fg(headerColor, `${ICON_OTHER} `);
1036
- lines.push(row(` ${prefix}${marker} ${th.fg(headerColor, "Note to assistant")}`));
1037
- const msg = this.messageText;
1038
- if (msg) {
1039
- const vw = visibleWidth(msg);
1040
- const body = vw <= maxW ? msg : `${truncateToWidth(msg, maxW - 1, "")}…`;
1041
- lines.push(row(`${bodyIndent}${th.fg("text", body)}`));
1042
- } else {
1043
- lines.push(row(`${bodyIndent}${th.fg("dim", "(optional Space to add a note)")}`));
1044
- }
1045
- continue;
1046
- }
1047
- const q = this.questions[i]!;
1048
- const ans = this.answers.get(q.tab);
1049
- // Header row: cursor + marker + title.
1050
- const marker = th.fg(headerColor, `${i + 1}.`);
1051
- lines.push(row(` ${prefix}${marker} ${th.fg(headerColor, q.header)}`));
1052
- // Answer row: reuse the description renderer's indent/wrap, fed the
1053
- // formatted answer text. Skipped/custom/multi-select all flow through
1054
- // formatAnswerText, so the coloring matches the option screen.
1055
- const ansText = this.formatAnswerText(ans, maxW, th);
1056
- lines.push(row(`${bodyIndent}${ansText}`));
1057
- }
1058
- if (total > this.reviewViewportH) {
1059
- lines.push(row(th.fg("dim", `${bodyIndent}↑↓/PgUp/PgDn scroll · ${start + 1}-${end}/${total}`)));
1060
- }
1061
- lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1062
- lines.push(row(th.fg("dim", " ↑↓ move · Space edit · Enter confirm · Esc cancel")));
1063
- lines.push(th.fg(bc, `╰${"─".repeat(innerW)}╯`));
1064
- return lines;
1065
- }
1066
-
1067
- /** Note editor screen: reached from the review's note entry via Space. Uses
1068
- * the same success-bordered look as the review screen to signal it's part
1069
- * of the review flow, not a fresh question. */
1070
- private renderMessageEditor(width: number, innerW: number, th: Theme): string[] {
1071
- const lines: string[] = [];
1072
- const bc: import("@earendil-works/pi-coding-agent").ThemeColor = "success";
1073
- const row = (content: string) => th.fg(bc, "│") + padRight(content, innerW) + th.fg(bc, "│");
1074
- lines.push(th.fg(bc, `╭${"".repeat(innerW)}╮`));
1075
- lines.push(row(` ${th.fg("accent", th.bold(`${ICON_OTHER} Note to assistant`))}`));
1076
- lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1077
- for (const el of this.messageEditor.render(innerW - 2)) lines.push(row(` ${el}`));
1078
- lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1079
- lines.push(row(th.fg("dim", " Esc back to review · Enter save note")));
1080
- lines.push(th.fg(bc, `╰${"─".repeat(innerW)}╯`));
1081
- return lines;
1082
- }
1083
-
1084
- /** Single-column layout: option label + wrapped description below. */
1085
- private renderSingleColumn(st: TabState, innerW: number, row: (s: string) => string, th: Theme): string[] {
1086
- const q = this.currentQuestion()!;
1087
- const multi = isMulti(q);
1088
- const opts = this.currentOptions();
1089
- const maxRows = Math.max(3, Math.min(opts.length, 10));
1090
- this.optionViewportH = maxRows;
1091
- this.clampScrollToCursor();
1092
- const start = st.scrollOffset;
1093
- const end = Math.min(opts.length, start + maxRows);
1094
- const out: string[] = [];
1095
- for (let i = start; i < end; i++) {
1096
- const opt = opts[i]!;
1097
- const isCursor = i === st.cursor;
1098
- const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1099
- const ans = this.answers.get(q.tab);
1100
- const committedCustom = multi ? st.customText : ans?.kind === "custom" ? ans.text : null;
1101
- const customAnswered = !!committedCustom;
1102
- const glyph = this.optionGlyph(opt, i, st, multi, th, isCursor, customAnswered);
1103
- // For "Type something.", show the committed text instead of the placeholder.
1104
- const displayLabel = opt.isOther && customAnswered ? committedCustom! : opt.label;
1105
- const labelColor = isCursor ? "accent" : opt.isOther ? (customAnswered ? "text" : "dim") : "text";
1106
- const labelText = th.fg(labelColor, displayLabel);
1107
- out.push(row(` ${prefix}${glyph} ${labelText}`));
1108
- if (opt.description) {
1109
- out.push(...this.renderDescription(opt.description, isCursor, innerW, row, th));
1110
- }
1111
- }
1112
- if (opts.length > maxRows) {
1113
- out.push(row(th.fg("dim", ` ↑↓/PgUp/PgDn scroll · ${start + 1}-${end}/${opts.length}`)));
1114
- }
1115
- return out;
1116
- }
1117
-
1118
- /**
1119
- * Two-column layout (options | preview), each half-width. Triggered when any
1120
- * option of the question carries a `preview` field. The right pane shows the
1121
- * preview of the option currently under the cursor.
1122
- */
1123
- private renderDualColumn(
1124
- q: Question,
1125
- st: TabState,
1126
- innerW: number,
1127
- row: (s: string) => string,
1128
- th: Theme,
1129
- ): string[] {
1130
- const multi = isMulti(q);
1131
- const opts = this.currentOptions();
1132
- const halfW = Math.floor((innerW - 2) / 2); // 1-space gutter between columns
1133
- const leftW = halfW;
1134
- const rightW = innerW - 2 - halfW;
1135
- const maxRows = Math.max(3, Math.min(opts.length, 10));
1136
- this.optionViewportH = maxRows;
1137
- this.clampScrollToCursor();
1138
- const start = st.scrollOffset;
1139
- const end = Math.min(opts.length, start + maxRows);
1140
-
1141
- // ── build left column lines (options) ──
1142
- const leftLines: string[] = [];
1143
- const dualAns = this.answers.get(q.tab);
1144
- const dualCommittedCustom = multi ? st.customText : dualAns?.kind === "custom" ? dualAns.text : null;
1145
- const customAnswered = !!dualCommittedCustom;
1146
- for (let i = start; i < end; i++) {
1147
- const opt = opts[i]!;
1148
- const isCursor = i === st.cursor;
1149
- const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1150
- const glyph = this.optionGlyph(opt, i, st, multi, th, isCursor, customAnswered);
1151
- const displayLabel = opt.isOther && customAnswered ? dualCommittedCustom! : opt.label;
1152
- const labelColor = isCursor ? "accent" : opt.isOther ? (customAnswered ? "text" : "dim") : "text";
1153
- const labelLine = `${prefix}${glyph} ${th.fg(labelColor, displayLabel)}`;
1154
- leftLines.push(truncateToWidth(labelLine, leftW - 1, ""));
1155
- }
1156
- if (opts.length > maxRows) {
1157
- leftLines.push(th.fg("dim", truncateToWidth(`${start + 1}-${end}/${opts.length}`, leftW - 1, "")));
1158
- }
1159
-
1160
- // ── build right column lines (preview of cursor option) ──
1161
- const rightLines: string[] = [];
1162
- const cursorOpt = opts[st.cursor];
1163
- if (cursorOpt?.preview) {
1164
- // Render preview verbatim (preserve ASCII layout), truncate to rightW.
1165
- for (const ln of cursorOpt.preview.split("\n")) {
1166
- rightLines.push(th.fg("muted", truncateToWidth(ln, rightW - 1, "")));
1167
- }
1168
- } else {
1169
- rightLines.push(th.fg("dim", truncateToWidth("(no preview)", rightW - 1, "")));
1170
- }
1171
-
1172
- // ── merge columns side by side, padding the shorter one ──
1173
- const rowCount = Math.max(leftLines.length, rightLines.length);
1174
- const out: string[] = [];
1175
- for (let r = 0; r < rowCount; r++) {
1176
- const l = padRight(leftLines[r] ?? "", leftW);
1177
- const rr = padRight(rightLines[r] ?? "", rightW);
1178
- out.push(row(` ${l} ${rr}`));
1179
- }
1180
- return out;
1181
- }
1182
-
1183
- /**
1184
- * Render an option description in single-column mode. Multi-line (newline-
1185
- * containing) descriptions render verbatim as a fixed-width block.
1186
- */
1187
- private renderDescription(
1188
- description: string,
1189
- selected: boolean,
1190
- innerW: number,
1191
- row: (s: string) => string,
1192
- th: Theme,
1193
- ): string[] {
1194
- const indent = " ";
1195
- const color = selected ? "muted" : "dim";
1196
- if (description.includes("\n")) {
1197
- const maxW = innerW - 2 - indent.length;
1198
- return description.split("\n").map((ln) => row(`${indent}${truncateToWidth(th.fg(color, ln), maxW, "")}`));
1199
- }
1200
- return wrapTextWithAnsi(`${indent}${th.fg(color, description)}`, innerW - 2).map((w) => row(w));
1201
- }
1202
-
1203
- invalidate(): void {
1204
- this.cachedWidth = undefined;
1205
- this.cachedLines = undefined;
1206
- this.tui.requestRender();
1207
- }
319
+ focused = false;
320
+
321
+ private questions: Question[];
322
+ private theme: Theme;
323
+ private tui: TuiLike;
324
+ private cb: PanelCallbacks;
325
+
326
+ // ── state ──
327
+ private currentTab = 0;
328
+ private answers = new Map<string, Answer>();
329
+ private collapsed = false;
330
+ private tabs: TabState[];
331
+ /** Visible option rows (recomputed each render). */
332
+ private optionViewportH = 8;
333
+ /** Cursor row in the review summary (shown on the review tab). */
334
+ private reviewCursor = 0;
335
+ /** Vertical scroll offset for the review viewport. */
336
+ private reviewScrollOffset = 0;
337
+ /** Visible review rows (recomputed each render). */
338
+ private reviewViewportH = 8;
339
+ /** True while the user is editing the free-form "note to assistant" on the
340
+ * review tab. While true, all input goes to messageEditor. */
341
+ private messageEditing = false;
342
+ /** Committed note text (trimmed). Empty string = no note. Lives only on the
343
+ * review screen; the LLM cannot set it. */
344
+ private messageText = "";
345
+ /** Dedicated editor for the note. Single-line semantics: Enter saves (like
346
+ * the per-question "Type something." editor). */
347
+ private messageEditor: Editor;
348
+
349
+ // ── render cache ──
350
+ private cachedWidth?: number;
351
+ private cachedLines?: string[];
352
+
353
+ constructor(questions: Question[], tui: TuiLike, theme: Theme, cb: PanelCallbacks) {
354
+ this.questions = questions;
355
+ this.tui = tui;
356
+ this.theme = theme;
357
+ this.cb = cb;
358
+
359
+ const editorTheme: EditorTheme = {
360
+ borderColor: (s) => theme.fg("accent", s),
361
+ selectList: {
362
+ selectedPrefix: (t) => theme.fg("accent", t),
363
+ selectedText: (t) => theme.fg("accent", t),
364
+ description: (t) => theme.fg("muted", t),
365
+ scrollInfo: (t) => theme.fg("dim", t),
366
+ noMatch: (t) => theme.fg("warning", t),
367
+ },
368
+ };
369
+ // Each tab owns its own Editor instance — its internal state IS that tab's
370
+ // draft, so tab switching needs no text shuttling. This is the fix for the
371
+ // draft-loss bug (previously a single shared editor was swapped in/out and
372
+ // the swap was lossy across the input-mode / tab-switch boundary).
373
+ this.tabs = questions.map((_, i) =>
374
+ newTabState(tui, editorTheme, i, (ti, v) => this.handleSubmit(ti, v)),
375
+ );
376
+ // Dedicated editor for the review-screen note. Enter saves (single-line),
377
+ // Esc returns to the review without saving — mirroring the per-question
378
+ // "Type something." editor's semantics.
379
+ this.messageEditor = new Editor(tui as never, editorTheme);
380
+ this.messageEditor.onSubmit = (value) => this.handleMessageSubmit(value);
381
+ }
382
+
383
+ /** Shared submit logic bound to each tab's editor. */
384
+ private handleSubmit(tabIndex: number, value: string): void {
385
+ const q = this.questions[tabIndex];
386
+ const st = this.tabs[tabIndex];
387
+ if (!q || !st) return;
388
+ const trimmed = value.trim();
389
+ if (!trimmed) {
390
+ // empty back to options. In multi-select mode, an empty submit also
391
+ // clears any previously committed custom text (blank = "remove my custom
392
+ // answer"), then re-commits the remaining checked options.
393
+ st.inputMode = false;
394
+ st.editor.setText("");
395
+ if (isMulti(q)) {
396
+ st.customText = null;
397
+ if (!this.commitMultiAnswer(q, st)) this.answers.delete(q.tab);
398
+ }
399
+ if (tabIndex === this.currentTab) this.invalidate();
400
+ return;
401
+ }
402
+ if (isMulti(q)) {
403
+ // Multi-select: the custom text is an extra entry kept ALONGSIDE the
404
+ // checked options it must NOT overwrite them. (Previously this path
405
+ // did answers.set with only the custom text, dropping every check.)
406
+ // Committing custom text only records it we return to the OPTION LIST
407
+ // (not advance) so the user can keep checking options and then press
408
+ // Enter on an option to confirm the whole question. Advancing here used
409
+ // to jump straight to review the moment the custom editor closed.
410
+ st.customText = trimmed;
411
+ this.commitMultiAnswer(q, st);
412
+ st.inputMode = false;
413
+ if (tabIndex === this.currentTab) this.invalidate();
414
+ return;
415
+ }
416
+ this.answers.set(q.tab, {
417
+ tab: q.tab,
418
+ kind: "custom",
419
+ text: trimmed,
420
+ });
421
+ st.selectedSingle = -1; // clear any prior option pick — answer is now custom
422
+ st.inputMode = false;
423
+ if (tabIndex === this.currentTab) {
424
+ this.advanceAfterAnswer();
425
+ }
426
+ }
427
+
428
+ /** Save the review-tab note: trim, store, return to the review tab.
429
+ * currentTab already points at the review tab (note editing is only
430
+ * entered from there), so we just clear the editing flag. Empty = no note. */
431
+ private handleMessageSubmit(value: string): void {
432
+ this.messageText = value.trim();
433
+ this.messageEditing = false;
434
+ this.invalidate();
435
+ }
436
+
437
+ /**
438
+ * Multi-select commit: merge the checked options (st.multiChecked) together
439
+ * with the committed custom text (st.customText) into one multi-select
440
+ * answer. Returns false when there is nothing to commit (no checks and no
441
+ * custom text), so the caller can delete the stale answer if desired.
442
+ */
443
+ private commitMultiAnswer(q: Question, st: TabState): boolean {
444
+ const opts = buildOptions(q);
445
+ const picked = Array.from(st.multiChecked)
446
+ .sort((a, b) => a - b)
447
+ .map((i) => opts[i])
448
+ .filter((o): o is RenderOption => !!o && !o.isOther);
449
+ const labels = picked.map((o) => o.label);
450
+ const customText = st.customText;
451
+ // Empty commit = no option picks AND no custom text. (A skippable
452
+ // multi-select still records an explicit empty answer via the Enter
453
+ // path see handleInput so this function returning false just means
454
+ // "nothing to record here".)
455
+ if (labels.length === 0 && !customText) return false;
456
+ const ans: Answer = {
457
+ tab: q.tab,
458
+ kind: "multi",
459
+ options: labels,
460
+ };
461
+ if (customText) ans.custom = customText;
462
+ this.answers.set(q.tab, ans);
463
+ return true;
464
+ }
465
+
466
+ // ── accessors ──
467
+
468
+ /** Total number of tabs: one per question, plus the trailing review tab. */
469
+ private get totalTabs(): number {
470
+ return this.questions.length + 1;
471
+ }
472
+
473
+ /** The review tab sits at index === questions.length (the last tab).
474
+ * While true, the panel renders the review summary instead of a question. */
475
+ private get isReviewTab(): boolean {
476
+ return this.currentTab === this.questions.length;
477
+ }
478
+
479
+ private currentQuestion(): Question | undefined {
480
+ return this.questions[this.currentTab];
481
+ }
482
+
483
+ private currentTabState(): TabState {
484
+ return this.tabs[this.currentTab]!;
485
+ }
486
+
487
+ private currentOptions(): RenderOption[] {
488
+ const q = this.currentQuestion();
489
+ return q ? buildOptions(q) : [];
490
+ }
491
+
492
+ private advanceAfterAnswer(): void {
493
+ // Advance to the next tab. The review tab is the last tab, so answering
494
+ // the final question lands the user on the review tab (where Enter
495
+ // submits). Navigation is now uniform: review is just the next tab,
496
+ // reached by the same Tab/→ keys as any question — no special "enter
497
+ // review" step. Safe because this is only called from question tabs
498
+ // (currentTab < questions.length), so currentTab + 1 <= reviewTabIndex.
499
+ this.switchTab(this.currentTab + 1);
500
+ }
501
+
502
+ /**
503
+ * Called before navigating AWAY from a question tab (Tab/→/←/Shift+Tab).
504
+ * Resolves the current question's state so it can be left cleanly:
505
+ *
506
+ * - Already committed (answers.has): leave freely.
507
+ * - Multi-select with UNCOMMITTED checks (or a typed custom text): a check
508
+ * IS an answer commit it first, then leave. Navigating away with
509
+ * pending checks must submit them (not skip, not block), regardless of
510
+ * allowSkip, because the user has already expressed a choice. (Single-
511
+ * select commits on Space, so it never has pending uncommitted state.)
512
+ * - Nothing selected at all:
513
+ * allowSkip true → record a skipped answer, allow leaving.
514
+ * allowSkip false block (a required question must be answered).
515
+ *
516
+ * Returns true when navigation may proceed.
517
+ */
518
+ private prepareQuestionForLeave(): boolean {
519
+ const q = this.currentQuestion();
520
+ if (!q) return true;
521
+ if (this.answers.has(q.tab)) return true;
522
+ const st = this.currentTabState();
523
+ // Multi-select: uncommitted checks count as an answer commit them,
524
+ // then leave. commitMultiAnswer only returns false when there's nothing
525
+ // to commit (no checks, no custom), which the guard already rules out.
526
+ if (isMulti(q) && (st.multiChecked.size > 0 || !!st.customText)) {
527
+ this.commitMultiAnswer(q, st);
528
+ return true;
529
+ }
530
+ if (!canSkip(q)) return false; // required question, nothing chosen: block
531
+ this.answers.set(q.tab, {
532
+ tab: q.tab,
533
+ kind: "skipped",
534
+ });
535
+ return true;
536
+ }
537
+
538
+ private submit(cancelled: boolean): void {
539
+ this.cb.onResult({
540
+ questions: this.questions,
541
+ answers: Array.from(this.answers.values()),
542
+ cancelled,
543
+ // Only attach the note when non-empty. A cancelled submit still carries
544
+ // the note if the user wrote one (it may explain why they cancelled).
545
+ message: this.messageText || undefined,
546
+ });
547
+ }
548
+
549
+ private setCollapsed(next: boolean): void {
550
+ if (this.collapsed === next) return;
551
+ this.collapsed = next;
552
+ this.invalidate();
553
+ }
554
+
555
+ private clampScrollToCursor(): void {
556
+ const opts = this.currentOptions();
557
+ if (opts.length === 0) return;
558
+ const viewH = this.optionViewportH;
559
+ const st = this.currentTabState();
560
+ if (st.cursor < st.scrollOffset) st.scrollOffset = st.cursor;
561
+ else if (st.cursor >= st.scrollOffset + viewH) st.scrollOffset = st.cursor - viewH + 1;
562
+ if (st.scrollOffset < 0) st.scrollOffset = 0;
563
+ }
564
+
565
+ // ── input ──
566
+
567
+ handleInput(data: string): void {
568
+ // 1. Note editor (messageEditing): owns all input while active. Esc
569
+ // returns to the review tab (currentTab already points there — note
570
+ // editing is only entered from the review tab).
571
+ if (this.messageEditing) {
572
+ if (matchesKey(data, Key.escape)) {
573
+ this.messageEditing = false;
574
+ this.invalidate();
575
+ return;
576
+ }
577
+ this.messageEditor.handleInput(data);
578
+ this.invalidate();
579
+ return;
580
+ }
581
+
582
+ // 2. Collapse toggle (global, any tab).
583
+ if (matchesKey(data, TOGGLE_KEY)) {
584
+ this.setCollapsed(!this.collapsed);
585
+ return;
586
+ }
587
+
588
+ // 3. Collapsed: only Esc (cancel) is meaningful.
589
+ if (this.collapsed) {
590
+ if (matchesKey(data, Key.escape)) this.submit(true);
591
+ return;
592
+ }
593
+
594
+ // 4. Question tab + "Type something." input mode: the editor owns ALL
595
+ // editing keys (Tab, arrows, etc.). Tab is NOT hijacked for tab
596
+ // switching here, because that would break indentation / cursor
597
+ // movement. Esc exits back to the option list. The review tab has no
598
+ // input mode (it never edits options), so it skips this branch — the
599
+ // `!this.isReviewTab` short-circuit also avoids indexing tabs[] OOB.
600
+ if (!this.isReviewTab && this.currentTabState().inputMode) {
601
+ if (matchesKey(data, Key.escape)) {
602
+ const st = this.currentTabState();
603
+ st.inputMode = false;
604
+ // Keep the editor content (per-tab editor preserves it as draft).
605
+ this.invalidate();
606
+ return;
607
+ }
608
+ this.currentTabState().editor.handleInput(data);
609
+ this.invalidate();
610
+ return;
611
+ }
612
+
613
+ // 5. Esc = cancel submission (any tab, when not editing).
614
+ if (matchesKey(data, Key.escape)) {
615
+ this.submit(true);
616
+ return;
617
+ }
618
+
619
+ // 6. Shared tab navigation Tab/→ forward, Shift+Tab/← backward.
620
+ // Runs on BOTH question tabs and the review tab, which is what makes
621
+ // the review reachable by the same keys as any question. The skip
622
+ // check only applies when LEAVING a question tab (never the review).
623
+ if (this.handleTabNavigation(data)) return;
624
+
625
+ // 7. Review tab: ↑↓ move · Space edit · Enter submit. (Esc + tab
626
+ // navigation were already handled above.)
627
+ if (this.isReviewTab) {
628
+ this.handleReviewInput(data);
629
+ return;
630
+ }
631
+
632
+ // 8. Question tab: ↑↓ move cursor · Space toggle/commit · Enter confirm.
633
+ const st = this.currentTabState();
634
+ const q = this.currentQuestion();
635
+ if (!q) return;
636
+ const opts = this.currentOptions();
637
+ const multi = isMulti(q);
638
+
639
+ // Up / Down — moves ONLY the cursor (▸), does not change selection
640
+ if (matchesKey(data, Key.up)) {
641
+ if (st.cursor > 0) {
642
+ st.cursor--;
643
+ this.clampScrollToCursor();
644
+ this.invalidate();
645
+ }
646
+ return;
647
+ }
648
+ if (matchesKey(data, Key.down)) {
649
+ if (st.cursor < opts.length - 1) {
650
+ st.cursor++;
651
+ this.clampScrollToCursor();
652
+ this.invalidate();
653
+ }
654
+ return;
655
+ }
656
+ if (matchesKey(data, Key.pageUp)) {
657
+ st.cursor = Math.max(0, st.cursor - Math.max(1, this.optionViewportH));
658
+ this.clampScrollToCursor();
659
+ this.invalidate();
660
+ return;
661
+ }
662
+ if (matchesKey(data, Key.pageDown)) {
663
+ st.cursor = Math.min(opts.length - 1, st.cursor + Math.max(1, this.optionViewportH));
664
+ this.clampScrollToCursor();
665
+ this.invalidate();
666
+ return;
667
+ }
668
+
669
+ // Space the "interact" key: select (single), toggle (multi), or EDIT
670
+ // (the "Type something." row). It never advances — that's Enter's job.
671
+ // This mirrors the review tab (where Space opens an entry for editing),
672
+ // so "the key that modifies things" is the same on every screen.
673
+ if (matchesKey(data, Key.space)) {
674
+ const opt = opts[st.cursor];
675
+ if (!opt) return;
676
+ if (opt.isOther) {
677
+ // Enter edit mode for a custom answer. Prefill with any committed
678
+ // custom text so the user edits rather than retypes. Per-tab
679
+ // editor keeps the text for Esc-discard semantics automatically.
680
+ // - Single-select: custom text lives in the `custom` answer.
681
+ // - Multi-select: it lives in st.customText (kept alongside checks).
682
+ st.inputMode = true;
683
+ const existing = this.answers.get(q.tab);
684
+ const prefill = multi ? st.customText : existing?.kind === "custom" ? existing.text : null;
685
+ if (prefill) st.editor.setText(prefill);
686
+ this.invalidate();
687
+ return;
688
+ }
689
+ if (multi) {
690
+ if (st.multiChecked.has(st.cursor)) st.multiChecked.delete(st.cursor);
691
+ else st.multiChecked.add(st.cursor);
692
+ this.invalidate();
693
+ return;
694
+ }
695
+ // single-select: mark the selection WITHOUT advancing (stay on question)
696
+ st.selectedSingle = st.cursor;
697
+ this.answers.set(q.tab, {
698
+ tab: q.tab,
699
+ kind: "single",
700
+ option: opt.label,
701
+ });
702
+ this.invalidate();
703
+ return;
704
+ }
705
+
706
+ // Enter confirm + advance to the next tab. It does NOT enter edit mode
707
+ // (Space owns that now), keeping the two keys orthogonal: Space modifies,
708
+ // Enter commits. Single-select commits the cursor position and advances;
709
+ // multi-select commits the currently checked options as-is and advances
710
+ // (Space owns checking, so Enter no longer auto-checks the cursor option).
711
+ if (matchesKey(data, Key.enter)) {
712
+ const opt = opts[st.cursor];
713
+ if (!opt) return;
714
+ if (opt.isOther && !multi) {
715
+ // Single-select isOther: Enter never edits (Space owns that). Only
716
+ // advance if a custom answer was already committed; otherwise stay.
717
+ if (this.answers.get(q.tab)?.kind === "custom") {
718
+ this.advanceAfterAnswer();
719
+ }
720
+ return;
721
+ }
722
+ if (multi) {
723
+ // Commit the current checks (+ any custom text) and advance. For a
724
+ // skippable multi-select, committing an EMPTY selection is still a
725
+ // commit Enter means "submit (even if empty) and move on", not
726
+ // "skip" (Tab/arrows do skipping). So we record an explicit empty
727
+ // answer and advance; a required question (!canSkip) with an empty
728
+ // selection stays put, since it must have at least one pick.
729
+ if (this.commitMultiAnswer(q, st)) {
730
+ this.advanceAfterAnswer();
731
+ } else if (canSkip(q)) {
732
+ this.answers.set(q.tab, {
733
+ tab: q.tab,
734
+ kind: "multi",
735
+ options: [],
736
+ });
737
+ this.advanceAfterAnswer();
738
+ }
739
+ return;
740
+ }
741
+ // single-select: commit cursor position as the selection, then advance
742
+ st.selectedSingle = st.cursor;
743
+ this.answers.set(q.tab, {
744
+ tab: q.tab,
745
+ kind: "single",
746
+ option: opt.label,
747
+ });
748
+ this.advanceAfterAnswer();
749
+ return;
750
+ }
751
+ }
752
+
753
+ /** Switch tab. Each tab owns its own Editor instance, so draft preservation
754
+ * is automatic — no text shuttling required. */
755
+ private switchTab(next: number): void {
756
+ if (next === this.currentTab) return;
757
+ this.currentTab = next;
758
+ this.invalidate();
759
+ }
760
+
761
+ /** Shared tab navigation, invoked from handleInput for BOTH question tabs
762
+ * and the review tab. Returns true when the key was consumed.
763
+ *
764
+ * - Tab / → : forward. Tab WRAPS through every tab (questions → review →
765
+ * first question); → STOPS at the review tab (boundary).
766
+ * - Shift+Tab / : backward. Shift+Tab wraps; stops at the first
767
+ * question.
768
+ *
769
+ * Leaving a question tab may need to commit pending multi-select checks
770
+ * or record a skip (when it's unanswered and required) that's handled
771
+ * by prepareQuestionForLeave. Leaving the review tab never needs that
772
+ * check (it isn't a question), so →/Tab work freely from review. */
773
+ private handleTabNavigation(data: string): boolean {
774
+ if (this.totalTabs <= 1) return false;
775
+ // Forward
776
+ if (matchesKey(data, Key.tab)) {
777
+ if (!this.isReviewTab && !this.prepareQuestionForLeave()) return true; // required: blocked
778
+ this.switchTab(wrapTab(this.currentTab + 1, this.totalTabs));
779
+ return true;
780
+ }
781
+ if (matchesKey(data, Key.right)) {
782
+ if (!this.isReviewTab && !this.prepareQuestionForLeave()) return true; // required: blocked
783
+ if (this.currentTab + 1 >= this.totalTabs) return true; // stop at review
784
+ this.switchTab(this.currentTab + 1);
785
+ return true;
786
+ }
787
+ // Backward
788
+ if (matchesKey(data, Key.shift("tab"))) {
789
+ this.switchTab(wrapTab(this.currentTab - 1, this.totalTabs));
790
+ return true;
791
+ }
792
+ if (matchesKey(data, Key.left)) {
793
+ if (this.currentTab - 1 < 0) return true; // stop at first question
794
+ this.switchTab(this.currentTab - 1);
795
+ return true;
796
+ }
797
+ return false;
798
+ }
799
+
800
+ /** Handle input specific to the review tab. Esc and tab navigation
801
+ * (Tab/←/→) are already handled upstream in handleInput, so here we only
802
+ * deal with: ↑↓/PgUp/PgDn (move the review cursor), Space (open the entry
803
+ * under the cursor for editing), and Enter (submit the whole review).
804
+ *
805
+ * The review list has N question entries plus one trailing "note to
806
+ * assistant" entry (index N), so the cursor ranges over [0, N]. */
807
+ private handleReviewInput(data: string): void {
808
+ const n = this.questions.length;
809
+ const total = n + 1; // include the note entry
810
+ // ↑/↓/PgUp/PgDn — move the review cursor over [0, total-1]
811
+ if (matchesKey(data, Key.up)) {
812
+ if (this.reviewCursor > 0) {
813
+ this.reviewCursor--;
814
+ this.invalidate();
815
+ }
816
+ return;
817
+ }
818
+ if (matchesKey(data, Key.down)) {
819
+ if (this.reviewCursor < total - 1) {
820
+ this.reviewCursor++;
821
+ this.invalidate();
822
+ }
823
+ return;
824
+ }
825
+ if (matchesKey(data, Key.pageUp)) {
826
+ this.reviewCursor = Math.max(0, this.reviewCursor - Math.max(1, this.reviewViewportH));
827
+ this.invalidate();
828
+ return;
829
+ }
830
+ if (matchesKey(data, Key.pageDown)) {
831
+ this.reviewCursor = Math.min(
832
+ total - 1,
833
+ this.reviewCursor + Math.max(1, this.reviewViewportH),
834
+ );
835
+ this.invalidate();
836
+ return;
837
+ }
838
+ // Space "select" the entry under the cursor: jump into editing it.
839
+ // (Mirrors the option screens, where Space = select/toggle.)
840
+ if (matchesKey(data, Key.space)) {
841
+ if (this.reviewCursor === n) {
842
+ // Note entry: open the note editor. Prefill with the committed note
843
+ // (if any) so the user can tweak rather than retype.
844
+ this.messageEditing = true;
845
+ if (this.messageText) this.messageEditor.setText(this.messageText);
846
+ this.invalidate();
847
+ return;
848
+ }
849
+ // Question entry: switch to that question's tab for editing.
850
+ // switchTab early-returns when next === currentTab, which is fine — that
851
+ // only happens on a single-question call where we're already on the
852
+ // question; nothing to redraw.
853
+ this.switchTab(this.reviewCursor);
854
+ return;
855
+ }
856
+ // Enter — submit the whole review, no matter where the cursor sits.
857
+ if (matchesKey(data, Key.enter)) {
858
+ this.submit(false);
859
+ return;
860
+ }
861
+ }
862
+
863
+ // ── render ──
864
+
865
+ render(width: number): string[] {
866
+ if (this.collapsed) {
867
+ this.cachedWidth = width;
868
+ this.cachedLines = this.renderCollapsed(width);
869
+ return this.cachedLines;
870
+ }
871
+ if (this.cachedLines && this.cachedWidth === width) {
872
+ return this.cachedLines;
873
+ }
874
+ this.cachedWidth = width;
875
+ this.cachedLines = this.renderExpanded(width);
876
+ return this.cachedLines;
877
+ }
878
+
879
+ private renderCollapsed(width: number): string[] {
880
+ const th = this.theme;
881
+ const qParts = this.questions.map((q, i) => {
882
+ const done = this.answers.has(q.tab);
883
+ const active = i === this.currentTab && !this.isReviewTab;
884
+ const mark = active ? "▸" : done ? "✓" : "○";
885
+ const color = active ? "accent" : done ? "success" : "dim";
886
+ return th.fg(color, `${q.tab}${mark}`);
887
+ });
888
+ const reviewPart = this.isReviewTab ? th.fg("accent", "Review▸") : th.fg("dim", "Review○");
889
+ const tabsPart = [...qParts, reviewPart].join(th.fg("dim", " "));
890
+ const inner = `${tabsPart} ${th.fg("dim", ` ${TOGGLE_HINT} expand `)}${th.fg("dim", " Esc cancel ")}`;
891
+ const line =
892
+ th.fg("border", "│") +
893
+ inner +
894
+ " ".repeat(Math.max(0, width - 2 - visibleWidth(inner))) +
895
+ th.fg("border", "│");
896
+ return [truncateToWidth(line, width)];
897
+ }
898
+
899
+ /** Build the tab-bar content line (without border wrapping). Shared by the
900
+ * question screen and the review screen so the bar is always visible —
901
+ * the review tab is a real tab, so it must highlight when active just like
902
+ * any question. Callers wrap the returned string in their own row() so the
903
+ * border color matches the surrounding screen. */
904
+ private renderTabBarContent(th: Theme): string {
905
+ const tabCells = this.questions.map((q, i) => {
906
+ const active = i === this.currentTab;
907
+ const ans = this.answers.get(q.tab);
908
+ let mark = " ";
909
+ let baseColor: import("@earendil-works/pi-coding-agent").ThemeColor = active
910
+ ? "accent"
911
+ : "muted";
912
+ if (ans?.kind === "skipped") {
913
+ mark = "—";
914
+ baseColor = "warning";
915
+ } else if (ans) {
916
+ mark = "✓";
917
+ baseColor = "success";
918
+ } else if (active) mark = "▸";
919
+ const color = active ? "accent" : baseColor;
920
+ return th.fg(color, `${mark} ${q.tab}`);
921
+ });
922
+ const reviewActive = this.isReviewTab;
923
+ const reviewMark = reviewActive ? "▸" : " ";
924
+ const reviewColor: import("@earendil-works/pi-coding-agent").ThemeColor = reviewActive
925
+ ? "accent"
926
+ : "muted";
927
+ const reviewCell = th.fg(reviewColor, `${reviewMark} [ Review ]`);
928
+ const sep = th.fg("dim", " │");
929
+ return ` ${tabCells.join(th.fg("dim", " "))}${sep}${reviewCell}`;
930
+ }
931
+
932
+ private renderExpanded(width: number): string[] {
933
+ const th = this.theme;
934
+ const innerW = Math.max(20, width - 2);
935
+ const lines: string[] = [];
936
+ const row = (content: string) =>
937
+ th.fg("border", "│") + padRight(content, innerW) + th.fg("border", "");
938
+
939
+ if (this.messageEditing) {
940
+ return this.renderMessageEditor(width, innerW, th);
941
+ }
942
+ if (this.isReviewTab) {
943
+ return this.renderReview(width, innerW, th);
944
+ }
945
+
946
+ lines.push(th.fg("border", `╭${"─".repeat(innerW)}╮`));
947
+
948
+ // ── Tab bar ──
949
+ // Always shown: there is always at least one question tab plus the
950
+ // trailing review tab. renderTabBarContent is shared with the review
951
+ // screen so the active tab stays visible across every screen.
952
+ lines.push(row(this.renderTabBarContent(th)));
953
+ lines.push(row(""));
954
+
955
+ // ── Question header ──
956
+ const q = this.currentQuestion();
957
+ const multi = isMulti(q);
958
+ const dual = isDualColumn(q);
959
+ const progress =
960
+ this.questions.length > 1 ? ` [${this.currentTab + 1}/${this.questions.length}]` : "";
961
+ const tag = multi ? th.fg("dim", " (multi)") : "";
962
+ const headerText = truncateToWidth(
963
+ ` ${th.fg("accent", th.bold(q?.header ?? ""))}${tag}${th.fg("dim", progress)}`,
964
+ innerW,
965
+ "",
966
+ );
967
+ lines.push(th.fg("border", "│") + padRight(headerText, innerW) + th.fg("border", "│"));
968
+
969
+ // ── Prompt body ──
970
+ if (q?.prompt) {
971
+ for (const w of wrapTextWithAnsi(th.fg("muted", q.prompt), innerW - 2))
972
+ lines.push(row(` ${w}`));
973
+ }
974
+ // 空行分隔 header/prompt 与 options。原来只在有 prompt 时才加,导致无
975
+ // prompt 的问题其标题与选项紧贴("粘在一起")。现在无条件加。
976
+ lines.push(row(""));
977
+
978
+ // ── Body: options / preview / input editor ──
979
+ const st = this.currentTabState();
980
+ if (st.inputMode) {
981
+ for (const el of st.editor.render(innerW - 2)) lines.push(row(` ${el}`));
982
+ lines.push(row(th.fg("dim", " Esc back to options · Enter submit")));
983
+ } else if (dual && q) {
984
+ lines.push(...this.renderDualColumn(q, st, innerW, row, th));
985
+ } else {
986
+ lines.push(...this.renderSingleColumn(st, innerW, row, th));
987
+ }
988
+
989
+ // ── Footer ──
990
+ lines.push(th.fg("border", `├${"─".repeat(innerW)}┤`));
991
+ const doneCount = Array.from(this.answers.keys()).length;
992
+ const left =
993
+ this.questions.length > 1
994
+ ? th.fg("dim", ` ${doneCount}/${this.questions.length} answered · `)
995
+ : th.fg("dim", " ");
996
+ const hint = multi
997
+ ? `${TOGGLE_HINT} collapse · ↑↓ move · Space toggle · Enter confirm · Esc cancel`
998
+ : `${TOGGLE_HINT} collapse · ↑↓ move · Space select · Enter confirm · Esc cancel`;
999
+ lines.push(row(`${left}${th.fg("dim", hint)}`));
1000
+ lines.push(th.fg("border", `╰${"─".repeat(innerW)}╯`));
1001
+ return lines;
1002
+ }
1003
+
1004
+ /** Render the option row glyph. The cursor (▸) is independent of selection. */
1005
+ private optionGlyph(
1006
+ opt: RenderOption,
1007
+ index: number,
1008
+ st: TabState,
1009
+ multi: boolean,
1010
+ th: Theme,
1011
+ _isCursor: boolean,
1012
+ customAnswered: boolean,
1013
+ ): string {
1014
+ if (opt.isOther) {
1015
+ // "Type something." is filled when a custom answer was committed.
1016
+ return customAnswered ? th.fg("success", ICON_RADIO_FILLED) : th.fg("dim", ICON_OTHER);
1017
+ }
1018
+ if (multi) {
1019
+ const checked = st.multiChecked.has(index);
1020
+ return checked ? th.fg("success", ICON_CHECK_FILLED) : th.fg("dim", ICON_CHECK_EMPTY);
1021
+ }
1022
+ // single: filled only when committed (selectedSingle), not on cursor hover
1023
+ const filled = st.selectedSingle === index;
1024
+ return filled ? th.fg("success", ICON_RADIO_FILLED) : th.fg("dim", ICON_RADIO_EMPTY);
1025
+ }
1026
+
1027
+ /** Format an answer for the review summary. Delegates to describeAnswer
1028
+ * (single source of truth), then wraps in the theme color + truncates. */
1029
+ private formatAnswerText(ans: Answer | undefined, maxW: number, th: Theme): string {
1030
+ const view = describeAnswer(ans);
1031
+ const text = truncForDisplay(view.text, maxW);
1032
+ return th.fg(view.color, text);
1033
+ }
1034
+
1035
+ /** Clamp the review scroll offset so the cursor stays visible. The review
1036
+ * list has N questions + 1 note entry, so the cursor may equal N. */
1037
+ private clampReviewScroll(): void {
1038
+ const total = this.questions.length + 1;
1039
+ if (total === 0) return;
1040
+ const viewH = this.reviewViewportH;
1041
+ if (this.reviewCursor < this.reviewScrollOffset) this.reviewScrollOffset = this.reviewCursor;
1042
+ else if (this.reviewCursor >= this.reviewScrollOffset + viewH)
1043
+ this.reviewScrollOffset = this.reviewCursor - viewH + 1;
1044
+ if (this.reviewScrollOffset < 0) this.reviewScrollOffset = 0;
1045
+ }
1046
+
1047
+ /** Review summary: one question per entry (header + answer), plus a trailing
1048
+ * "note to assistant" entry. Viewport scrolling reuses the option-screen
1049
+ * layout primitives. */
1050
+ private renderReview(_width: number, innerW: number, th: Theme): string[] {
1051
+ const lines: string[] = [];
1052
+ // Review uses a distinct border color (success/green) so it's visually
1053
+ // unmistakable as the review/confirm screen — not another question. The
1054
+ // question screen keeps the default "border" color.
1055
+ const bc: import("@earendil-works/pi-coding-agent").ThemeColor = "success";
1056
+ const row = (content: string) => th.fg(bc, "│") + padRight(content, innerW) + th.fg(bc, "");
1057
+ lines.push(th.fg(bc, `╭${"─".repeat(innerW)}╮`));
1058
+ lines.push(row(this.renderTabBarContent(th)));
1059
+ lines.push(row(""));
1060
+ lines.push(row(` ${th.fg("accent", th.bold("Review your answers"))}`));
1061
+ lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1062
+ const n = this.questions.length;
1063
+ const total = n + 1; // +1 for the note entry
1064
+ // Body indent (6 cols): questions and the note carry a 2-visible-col marker
1065
+ // (`1.` / `2.` or `✎ ` for the note) right after the cursor, plus a
1066
+ // separator space, so every title starts at the same column. The body is
1067
+ // indented one past that so header vs content stay visually distinct —
1068
+ // previously the body sat at 5 cols and the note's icon pushed its title
1069
+ // out of alignment with the question titles.
1070
+ const bodyIndent = " "; // 6 spaces
1071
+ const maxW = innerW - 2 - bodyIndent.length;
1072
+ this.reviewViewportH = Math.max(3, Math.min(total, 10));
1073
+ this.clampReviewScroll();
1074
+ const start = this.reviewScrollOffset;
1075
+ const end = Math.min(total, start + this.reviewViewportH);
1076
+ for (let i = start; i < end; i++) {
1077
+ const isCursor = i === this.reviewCursor;
1078
+ const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1079
+ const headerColor: import("@earendil-works/pi-coding-agent").ThemeColor = isCursor
1080
+ ? "accent"
1081
+ : "muted";
1082
+ // marker: a fixed 2-visible-col slot + 1 separator space, so every title
1083
+ // (questions + note) aligns regardless of icon width. `1.` is 2 cols;
1084
+ // the note's is 1 col, padded to `✎ ` (hence one extra space between
1085
+ // ✎ and its title — the deliberate tradeoff of this layout).
1086
+ // ── Note entry (index n): always last, two rows like a question. ──
1087
+ if (i === n) {
1088
+ // 空行分隔:note 是异类条目(附加留言,非问答),用空行和上方
1089
+ // 问答列表隔开。保持简单,不用点线/装饰。
1090
+ lines.push(row(""));
1091
+ const marker = th.fg(headerColor, `${ICON_OTHER} `);
1092
+ lines.push(row(` ${prefix}${marker} ${th.fg(headerColor, "Note to assistant")}`));
1093
+ const msg = this.messageText;
1094
+ if (msg) {
1095
+ const vw = visibleWidth(msg);
1096
+ const body = vw <= maxW ? msg : `${truncateToWidth(msg, maxW - 1, "")}…`;
1097
+ lines.push(row(`${bodyIndent}${th.fg("text", body)}`));
1098
+ } else {
1099
+ lines.push(row(`${bodyIndent}${th.fg("dim", "(optional Space to add a note)")}`));
1100
+ }
1101
+ continue;
1102
+ }
1103
+ const q = this.questions[i]!;
1104
+ const ans = this.answers.get(q.tab);
1105
+ // Header row: cursor + marker + title.
1106
+ const marker = th.fg(headerColor, `${i + 1}.`);
1107
+ lines.push(row(` ${prefix}${marker} ${th.fg(headerColor, q.header)}`));
1108
+ // Answer row: reuse the description renderer's indent/wrap, fed the
1109
+ // formatted answer text. Skipped/custom/multi-select all flow through
1110
+ // formatAnswerText, so the coloring matches the option screen.
1111
+ const ansText = this.formatAnswerText(ans, maxW, th);
1112
+ lines.push(row(`${bodyIndent}${ansText}`));
1113
+ }
1114
+ if (total > this.reviewViewportH) {
1115
+ lines.push(
1116
+ row(th.fg("dim", `${bodyIndent}↑↓/PgUp/PgDn scroll · ${start + 1}-${end}/${total}`)),
1117
+ );
1118
+ }
1119
+ lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1120
+ lines.push(row(th.fg("dim", " ↑↓ move · Space edit · Enter confirm · Esc cancel")));
1121
+ lines.push(th.fg(bc, `╰${"─".repeat(innerW)}╯`));
1122
+ return lines;
1123
+ }
1124
+
1125
+ /** Note editor screen: reached from the review's note entry via Space. Uses
1126
+ * the same success-bordered look as the review screen to signal it's part
1127
+ * of the review flow, not a fresh question. */
1128
+ private renderMessageEditor(_width: number, innerW: number, th: Theme): string[] {
1129
+ const lines: string[] = [];
1130
+ const bc: import("@earendil-works/pi-coding-agent").ThemeColor = "success";
1131
+ const row = (content: string) => th.fg(bc, "│") + padRight(content, innerW) + th.fg(bc, "│");
1132
+ lines.push(th.fg(bc, `╭${"─".repeat(innerW)}╮`));
1133
+ lines.push(row(` ${th.fg("accent", th.bold(`${ICON_OTHER} Note to assistant`))}`));
1134
+ lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1135
+ for (const el of this.messageEditor.render(innerW - 2)) lines.push(row(` ${el}`));
1136
+ lines.push(th.fg(bc, `├${"─".repeat(innerW)}┤`));
1137
+ lines.push(row(th.fg("dim", " Esc back to review · Enter save note")));
1138
+ lines.push(th.fg(bc, `╰${"─".repeat(innerW)}╯`));
1139
+ return lines;
1140
+ }
1141
+
1142
+ /** Single-column layout: option label + wrapped description below. */
1143
+ private renderSingleColumn(
1144
+ st: TabState,
1145
+ innerW: number,
1146
+ row: (s: string) => string,
1147
+ th: Theme,
1148
+ ): string[] {
1149
+ const q = this.currentQuestion()!;
1150
+ const multi = isMulti(q);
1151
+ const opts = this.currentOptions();
1152
+ const maxRows = Math.max(3, Math.min(opts.length, 10));
1153
+ this.optionViewportH = maxRows;
1154
+ this.clampScrollToCursor();
1155
+ const start = st.scrollOffset;
1156
+ const end = Math.min(opts.length, start + maxRows);
1157
+ const out: string[] = [];
1158
+ for (let i = start; i < end; i++) {
1159
+ const opt = opts[i]!;
1160
+ const isCursor = i === st.cursor;
1161
+ const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1162
+ const ans = this.answers.get(q.tab);
1163
+ const committedCustom = multi ? st.customText : ans?.kind === "custom" ? ans.text : null;
1164
+ const customAnswered = !!committedCustom;
1165
+ const glyph = this.optionGlyph(opt, i, st, multi, th, isCursor, customAnswered);
1166
+ // For "Type something.", show the committed text instead of the placeholder.
1167
+ const displayLabel = opt.isOther && customAnswered ? committedCustom! : opt.label;
1168
+ const labelColor = isCursor
1169
+ ? "accent"
1170
+ : opt.isOther
1171
+ ? customAnswered
1172
+ ? "text"
1173
+ : "dim"
1174
+ : "text";
1175
+ const labelText = th.fg(labelColor, displayLabel);
1176
+ out.push(row(` ${prefix}${glyph} ${labelText}`));
1177
+ if (opt.description) {
1178
+ out.push(...this.renderDescription(opt.description, isCursor, innerW, row, th));
1179
+ }
1180
+ }
1181
+ if (opts.length > maxRows) {
1182
+ out.push(row(th.fg("dim", ` ↑↓/PgUp/PgDn scroll · ${start + 1}-${end}/${opts.length}`)));
1183
+ }
1184
+ return out;
1185
+ }
1186
+
1187
+ /**
1188
+ * Two-column layout (options | preview), each half-width. Triggered when any
1189
+ * option of the question carries a `preview` field. The right pane shows the
1190
+ * preview of the option currently under the cursor.
1191
+ */
1192
+ private renderDualColumn(
1193
+ q: Question,
1194
+ st: TabState,
1195
+ innerW: number,
1196
+ row: (s: string) => string,
1197
+ th: Theme,
1198
+ ): string[] {
1199
+ const multi = isMulti(q);
1200
+ const opts = this.currentOptions();
1201
+ const halfW = Math.floor((innerW - 2) / 2); // 1-space gutter between columns
1202
+ const leftW = halfW;
1203
+ const rightW = innerW - 2 - halfW;
1204
+ const maxRows = Math.max(3, Math.min(opts.length, 10));
1205
+ this.optionViewportH = maxRows;
1206
+ this.clampScrollToCursor();
1207
+ const start = st.scrollOffset;
1208
+ const end = Math.min(opts.length, start + maxRows);
1209
+
1210
+ // ── build left column lines (options) ──
1211
+ const leftLines: string[] = [];
1212
+ const dualAns = this.answers.get(q.tab);
1213
+ const dualCommittedCustom = multi
1214
+ ? st.customText
1215
+ : dualAns?.kind === "custom"
1216
+ ? dualAns.text
1217
+ : null;
1218
+ const customAnswered = !!dualCommittedCustom;
1219
+ for (let i = start; i < end; i++) {
1220
+ const opt = opts[i]!;
1221
+ const isCursor = i === st.cursor;
1222
+ const prefix = isCursor ? `${th.fg("accent", ICON_CURSOR)} ` : " ";
1223
+ const glyph = this.optionGlyph(opt, i, st, multi, th, isCursor, customAnswered);
1224
+ const displayLabel = opt.isOther && customAnswered ? dualCommittedCustom! : opt.label;
1225
+ const labelColor = isCursor
1226
+ ? "accent"
1227
+ : opt.isOther
1228
+ ? customAnswered
1229
+ ? "text"
1230
+ : "dim"
1231
+ : "text";
1232
+ const labelLine = `${prefix}${glyph} ${th.fg(labelColor, displayLabel)}`;
1233
+ leftLines.push(truncateToWidth(labelLine, leftW - 1, ""));
1234
+ }
1235
+ if (opts.length > maxRows) {
1236
+ leftLines.push(
1237
+ th.fg("dim", truncateToWidth(`${start + 1}-${end}/${opts.length}`, leftW - 1, "")),
1238
+ );
1239
+ }
1240
+
1241
+ // ── build right column lines (preview of cursor option) ──
1242
+ const rightLines: string[] = [];
1243
+ const cursorOpt = opts[st.cursor];
1244
+ if (cursorOpt?.preview) {
1245
+ // Render preview verbatim (preserve ASCII layout), truncate to rightW.
1246
+ for (const ln of cursorOpt.preview.split("\n")) {
1247
+ rightLines.push(th.fg("muted", truncateToWidth(ln, rightW - 1, "")));
1248
+ }
1249
+ } else {
1250
+ rightLines.push(th.fg("dim", truncateToWidth("(no preview)", rightW - 1, "")));
1251
+ }
1252
+
1253
+ // ── merge columns side by side, padding the shorter one ──
1254
+ const rowCount = Math.max(leftLines.length, rightLines.length);
1255
+ const out: string[] = [];
1256
+ for (let r = 0; r < rowCount; r++) {
1257
+ const l = padRight(leftLines[r] ?? "", leftW);
1258
+ const rr = padRight(rightLines[r] ?? "", rightW);
1259
+ out.push(row(` ${l} ${rr}`));
1260
+ }
1261
+ return out;
1262
+ }
1263
+
1264
+ /**
1265
+ * Render an option description in single-column mode. Multi-line (newline-
1266
+ * containing) descriptions render verbatim as a fixed-width block.
1267
+ */
1268
+ private renderDescription(
1269
+ description: string,
1270
+ selected: boolean,
1271
+ innerW: number,
1272
+ row: (s: string) => string,
1273
+ th: Theme,
1274
+ ): string[] {
1275
+ const indent = " ";
1276
+ const color = selected ? "muted" : "dim";
1277
+ if (description.includes("\n")) {
1278
+ const maxW = innerW - 2 - indent.length;
1279
+ return description
1280
+ .split("\n")
1281
+ .map((ln) => row(`${indent}${truncateToWidth(th.fg(color, ln), maxW, "")}`));
1282
+ }
1283
+ return wrapTextWithAnsi(`${indent}${th.fg(color, description)}`, innerW - 2).map((w) => row(w));
1284
+ }
1285
+
1286
+ invalidate(): void {
1287
+ this.cachedWidth = undefined;
1288
+ this.cachedLines = undefined;
1289
+ this.tui.requestRender();
1290
+ }
1208
1291
  }
1209
1292
 
1210
1293
  // ────────────────────────────────────────────────────────────────────────────
@@ -1217,134 +1300,139 @@ class AskUserPanel implements Component, Focusable {
1217
1300
  // ────────────────────────────────────────────────────────────────────────────
1218
1301
 
1219
1302
  class AskUserResultView implements Component {
1220
- private questions: ReadonlyArray<Pick<Question, "header" | "tab">>;
1221
- private result: AskUserResult;
1222
- private theme: Theme;
1223
- private expanded = false;
1224
- private cachedWidth?: number;
1225
- private cachedLines?: string[];
1226
-
1227
- constructor(questions: ReadonlyArray<Pick<Question, "header" | "tab">>, result: AskUserResult, theme: Theme) {
1228
- this.questions = questions;
1229
- this.result = result;
1230
- this.theme = theme;
1231
- }
1232
-
1233
- setExpanded(expanded: boolean): void {
1234
- if (this.expanded !== expanded) {
1235
- this.expanded = expanded;
1236
- this.cachedWidth = undefined;
1237
- }
1238
- }
1239
-
1240
- invalidate(): void {
1241
- this.cachedWidth = undefined;
1242
- this.cachedLines = undefined;
1243
- }
1244
-
1245
- render(width: number): string[] {
1246
- if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
1247
- this.cachedWidth = width;
1248
- this.cachedLines = this.expanded ? this.renderCard(width) : this.renderCollapsed(width);
1249
- return this.cachedLines;
1250
- }
1251
-
1252
- /** Overall status icon, color, and a short status phrase (plain text,
1253
- * no ANSI — callers wrap it in color). */
1254
- private getStatus(): { icon: string; color: ThemeColor; phrase: string } {
1255
- const total = this.questions.length;
1256
- if (this.result.cancelled) {
1257
- return {
1258
- icon: "⊘",
1259
- color: "warning",
1260
- phrase: `Cancelled · ${this.result.answers.length}/${total} answered`,
1261
- };
1262
- }
1263
- const anySkipped = this.result.answers.some((a) => a.kind === "skipped");
1264
- return anySkipped
1265
- ? { icon: "○", color: "accent", phrase: "Answers (some skipped)" }
1266
- : { icon: "✓", color: "success", phrase: "Answers submitted" };
1267
- }
1268
-
1269
- /** Format one answer for the card display. Delegates to describeAnswer. */
1270
- private formatAnswer(ans: Answer | undefined): { text: string; color: ThemeColor } {
1271
- return describeAnswer(ans);
1272
- }
1273
-
1274
- private renderCollapsed(width: number): string[] {
1275
- const th = this.theme;
1276
- const { icon, color, phrase } = this.getStatus();
1277
- const head = `${th.fg(color, icon)} ${th.fg(color, phrase)}`;
1278
- const sep = th.fg("dim", ": ");
1279
- const pairs = this.questions.map((q) => {
1280
- const ans = this.result.answers.find((a) => a.tab === q.tab);
1281
- return `${q.header}=${this.formatAnswer(ans).text}`;
1282
- });
1283
- const body = pairs.join(th.fg("dim", " · "));
1284
- return [th.fg("dim", truncForDisplay(`${head}${sep}${body}`, width))];
1285
- }
1286
-
1287
- private renderCard(width: number): string[] {
1288
- const th = this.theme;
1289
- const { icon, color, phrase } = this.getStatus();
1290
- const lines: string[] = [];
1291
- // Status line icon + phrase in the status color. No border, no redundant
1292
- // "Ask User" title (the tool-execution cell already renders the tool name
1293
- // as its header above this component).
1294
- lines.push(`${th.fg(color, icon)} ${th.fg(color, th.bold(phrase))}`);
1295
- lines.push(""); // blank line separates status from the Q&A list
1296
-
1297
- // Each question: header on its own row, then one or more answer rows.
1298
- // Rows are prefixed by a glyph indicating the answer TYPE, not a uniform
1299
- // marker: option picks get an arrow (›), custom text gets a pencil (✎).
1300
- // A multi-select with BOTH options and custom renders as TWO rows. Long
1301
- // content wraps (wrapTextWithAnsi) so nothing is ever truncated/lost.
1302
- const indent = " "; // 4-space lead for answer rows
1303
- const arrow = th.fg("dim", ICON_ANSWER);
1304
- const pencil = th.fg("dim", ICON_OTHER);
1305
- const answerRow = (glyph: string, text: string, textColor: ThemeColor) => {
1306
- const lead = `${indent}${glyph} `;
1307
- const w = Math.max(8, width - visibleWidth(lead));
1308
- const wrapped = wrapTextWithAnsi(th.fg(textColor, text), w);
1309
- const contIndent = " ".repeat(visibleWidth(lead));
1310
- const out = [`${lead}${wrapped[0]}`];
1311
- for (let i = 1; i < wrapped.length; i++) out.push(`${contIndent}${wrapped[i]}`);
1312
- return out;
1313
- };
1314
- for (const q of this.questions) {
1315
- const ans = this.result.answers.find((a) => a.tab === q.tab);
1316
- lines.push(th.fg("muted", q.header));
1317
- if (!ans) {
1318
- lines.push(`${indent}${th.fg("dim", "(no answer)")}`);
1319
- } else if (ans.kind === "skipped") {
1320
- lines.push(`${indent}${th.fg("warning", "(skipped)")}`);
1321
- } else if (ans.kind === "single") {
1322
- lines.push(...answerRow(arrow, ans.option, "text"));
1323
- } else if (ans.kind === "custom") {
1324
- lines.push(...answerRow(pencil, ans.text, "text"));
1325
- } else if (ans.kind === "multi") {
1326
- if (ans.options.length === 0 && !ans.custom) {
1327
- lines.push(`${indent}${th.fg("dim", "(none)")}`);
1328
- } else {
1329
- // Options row (arrow) + optional custom row (pencil) — two rows.
1330
- if (ans.options.length > 0) lines.push(...answerRow(arrow, ans.options.join(", "), "text"));
1331
- if (ans.custom) lines.push(...answerRow(pencil, ans.custom, "text"));
1332
- }
1333
- }
1334
- }
1335
-
1336
- // Note — separated by a blank line, no border, no indent. A speech-bubble
1337
- // glyph marks it as a free-form message, distinct from the Q&A answers.
1338
- if (this.result.message) {
1339
- lines.push("");
1340
- const prefix = th.fg("accent", ICON_NOTE);
1341
- const noteW = Math.max(8, width - visibleWidth(prefix) - 1);
1342
- const wrapped = wrapTextWithAnsi(this.result.message, noteW);
1343
- lines.push(`${prefix} ${wrapped[0]}`);
1344
- for (let i = 1; i < wrapped.length; i++) lines.push(wrapped[i]);
1345
- }
1346
- return lines;
1347
- }
1303
+ private questions: ReadonlyArray<Pick<Question, "header" | "tab">>;
1304
+ private result: AskUserResult;
1305
+ private theme: Theme;
1306
+ private expanded = false;
1307
+ private cachedWidth?: number;
1308
+ private cachedLines?: string[];
1309
+
1310
+ constructor(
1311
+ questions: ReadonlyArray<Pick<Question, "header" | "tab">>,
1312
+ result: AskUserResult,
1313
+ theme: Theme,
1314
+ ) {
1315
+ this.questions = questions;
1316
+ this.result = result;
1317
+ this.theme = theme;
1318
+ }
1319
+
1320
+ setExpanded(expanded: boolean): void {
1321
+ if (this.expanded !== expanded) {
1322
+ this.expanded = expanded;
1323
+ this.cachedWidth = undefined;
1324
+ }
1325
+ }
1326
+
1327
+ invalidate(): void {
1328
+ this.cachedWidth = undefined;
1329
+ this.cachedLines = undefined;
1330
+ }
1331
+
1332
+ render(width: number): string[] {
1333
+ if (this.cachedLines && this.cachedWidth === width) return this.cachedLines;
1334
+ this.cachedWidth = width;
1335
+ this.cachedLines = this.expanded ? this.renderCard(width) : this.renderCollapsed(width);
1336
+ return this.cachedLines;
1337
+ }
1338
+
1339
+ /** Overall status → icon, color, and a short status phrase (plain text,
1340
+ * no ANSI — callers wrap it in color). */
1341
+ private getStatus(): { icon: string; color: ThemeColor; phrase: string } {
1342
+ const total = this.questions.length;
1343
+ if (this.result.cancelled) {
1344
+ return {
1345
+ icon: "⊘",
1346
+ color: "warning",
1347
+ phrase: `Cancelled · ${this.result.answers.length}/${total} answered`,
1348
+ };
1349
+ }
1350
+ const anySkipped = this.result.answers.some((a) => a.kind === "skipped");
1351
+ return anySkipped
1352
+ ? { icon: "○", color: "accent", phrase: "Answers (some skipped)" }
1353
+ : { icon: "✓", color: "success", phrase: "Answers submitted" };
1354
+ }
1355
+
1356
+ /** Format one answer for the card display. Delegates to describeAnswer. */
1357
+ private formatAnswer(ans: Answer | undefined): { text: string; color: ThemeColor } {
1358
+ return describeAnswer(ans);
1359
+ }
1360
+
1361
+ private renderCollapsed(width: number): string[] {
1362
+ const th = this.theme;
1363
+ const { icon, color, phrase } = this.getStatus();
1364
+ const head = `${th.fg(color, icon)} ${th.fg(color, phrase)}`;
1365
+ const sep = th.fg("dim", ": ");
1366
+ const pairs = this.questions.map((q) => {
1367
+ const ans = this.result.answers.find((a) => a.tab === q.tab);
1368
+ return `${q.header}=${this.formatAnswer(ans).text}`;
1369
+ });
1370
+ const body = pairs.join(th.fg("dim", " · "));
1371
+ return [th.fg("dim", truncForDisplay(`${head}${sep}${body}`, width))];
1372
+ }
1373
+
1374
+ private renderCard(width: number): string[] {
1375
+ const th = this.theme;
1376
+ const { icon, color, phrase } = this.getStatus();
1377
+ const lines: string[] = [];
1378
+ // Status line icon + phrase in the status color. No border, no redundant
1379
+ // "Ask User" title (the tool-execution cell already renders the tool name
1380
+ // as its header above this component).
1381
+ lines.push(`${th.fg(color, icon)} ${th.fg(color, th.bold(phrase))}`);
1382
+ lines.push(""); // blank line separates status from the Q&A list
1383
+
1384
+ // Each question: header on its own row, then one or more answer rows.
1385
+ // Rows are prefixed by a glyph indicating the answer TYPE, not a uniform
1386
+ // marker: option picks get an arrow (›), custom text gets a pencil (✎).
1387
+ // A multi-select with BOTH options and custom renders as TWO rows. Long
1388
+ // content wraps (wrapTextWithAnsi) so nothing is ever truncated/lost.
1389
+ const indent = " "; // 4-space lead for answer rows
1390
+ const arrow = th.fg("dim", ICON_ANSWER);
1391
+ const pencil = th.fg("dim", ICON_OTHER);
1392
+ const answerRow = (glyph: string, text: string, textColor: ThemeColor) => {
1393
+ const lead = `${indent}${glyph} `;
1394
+ const w = Math.max(8, width - visibleWidth(lead));
1395
+ const wrapped = wrapTextWithAnsi(th.fg(textColor, text), w);
1396
+ const contIndent = " ".repeat(visibleWidth(lead));
1397
+ const out = [`${lead}${wrapped[0]}`];
1398
+ for (let i = 1; i < wrapped.length; i++) out.push(`${contIndent}${wrapped[i]}`);
1399
+ return out;
1400
+ };
1401
+ for (const q of this.questions) {
1402
+ const ans = this.result.answers.find((a) => a.tab === q.tab);
1403
+ lines.push(th.fg("muted", q.header));
1404
+ if (!ans) {
1405
+ lines.push(`${indent}${th.fg("dim", "(no answer)")}`);
1406
+ } else if (ans.kind === "skipped") {
1407
+ lines.push(`${indent}${th.fg("warning", "(skipped)")}`);
1408
+ } else if (ans.kind === "single") {
1409
+ lines.push(...answerRow(arrow, ans.option, "text"));
1410
+ } else if (ans.kind === "custom") {
1411
+ lines.push(...answerRow(pencil, ans.text, "text"));
1412
+ } else if (ans.kind === "multi") {
1413
+ if (ans.options.length === 0 && !ans.custom) {
1414
+ lines.push(`${indent}${th.fg("dim", "(none)")}`);
1415
+ } else {
1416
+ // Options row (arrow) + optional custom row (pencil) — two rows.
1417
+ if (ans.options.length > 0)
1418
+ lines.push(...answerRow(arrow, ans.options.join(", "), "text"));
1419
+ if (ans.custom) lines.push(...answerRow(pencil, ans.custom, "text"));
1420
+ }
1421
+ }
1422
+ }
1423
+
1424
+ // Note separated by a blank line, no border, no indent. A speech-bubble
1425
+ // glyph marks it as a free-form message, distinct from the Q&A answers.
1426
+ if (this.result.message) {
1427
+ lines.push("");
1428
+ const prefix = th.fg("accent", ICON_NOTE);
1429
+ const noteW = Math.max(8, width - visibleWidth(prefix) - 1);
1430
+ const wrapped = wrapTextWithAnsi(this.result.message, noteW);
1431
+ lines.push(`${prefix} ${wrapped[0]}`);
1432
+ for (let i = 1; i < wrapped.length; i++) lines.push(wrapped[i]);
1433
+ }
1434
+ return lines;
1435
+ }
1348
1436
  }
1349
1437
 
1350
1438
  // ────────────────────────────────────────────────────────────────────────────
@@ -1352,104 +1440,117 @@ class AskUserResultView implements Component {
1352
1440
  // ────────────────────────────────────────────────────────────────────────────
1353
1441
 
1354
1442
  export default function askUserExtension(pi: ExtensionAPI) {
1355
- pi.registerTool<typeof AskUserParams, AskUserResult>({
1356
- name: "ask_user",
1357
- label: "Ask User",
1358
- description:
1359
- "Ask the user one or more questions with options. Supports single-select (◎→◉) and multi-select (□→▣, space toggles). Every question always includes a 'Type something.' row so the user can type a custom answer whenever none of the provided options fit — this is built in and cannot be disabled, so never assume the user is restricted to your listed options. The custom-input draft is preserved across tab switches, and a focused side panel shows extended detail (ASCII layouts, code, reasoning) when an option carries a `preview` field. Each option needs a short `label` + a `description` (shown beneath it); add a `preview` field only when a description can't fully convey the option. The panel is collapsible (Ctrl+\\). Use for clarifying requirements, getting preferences, or confirming decisions. Avoid using this to pick one item from a long list you just enumerated (e.g. \"which of these 8 fixes should I start with?\"): options are capped at a handful for a reason, and if the choice isn't a real either/or, present the list in a normal message and let the user reply freely, or just proceed with the highest-priority item — reserve ask_user for genuine decisions with a few distinct, mutually-exclusive paths. All displayed user-facing text should use the conversation's language. The result is returned as JSON: `{ \"cancelled\": bool, \"answers\": [{ \"tab\": <the question's tab>, ... }], \"message\"?: string }`. Each answer echoes the question's `tab` so you can correlate by key. Per answer only the relevant fields appear: single-select option pick → `answer`; single-select custom text → `custom`; multi-select option picks → `answers: [...]`; multi-select with custom → `answers` + `custom`; multi-select empty commit (skippable, submitted with nothing) → `answers: []`; Tab-skipped → `skipped: true`. `custom` is a sibling of `answer`/`answers`, never mixed in — it signals the user typed something outside the offered options. The optional top-level `message` is a free-form note the user can attach on the review screen (about overall direction, pacing, or anything beyond the specific questions); it is user-provided and out-of-band: you cannot set it via the parameters, and it may be absent; when present, treat it as high-priority context that can override or reframe the answers above it.",
1360
- parameters: AskUserParams,
1361
-
1362
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1363
- if (!ctx.hasUI) {
1364
- return errorResult("Error: UI not available (running in non-interactive mode)");
1365
- }
1366
- if (params.questions.length === 0) {
1367
- return errorResult("Error: No questions provided");
1368
- }
1369
-
1370
- const questions: Question[] = params.questions.map((q) => ({
1371
- ...q,
1372
- options: q.options.map((o) => ({ ...o })),
1373
- }));
1374
-
1375
- const result = await ctx.ui.custom<AskUserResult>((tui, theme, _kb, done) => {
1376
- return new AskUserPanel(questions, tui, theme, {
1377
- onResult: (r) => done(r),
1378
- });
1379
- }, {
1380
- // overlay:false renders the panel into pi's bottom editorContainer slot
1381
- // (the same path ctx.ui.select()/input() take) instead of compositing a
1382
- // screen overlay over everything. The chat transcript stays visible above
1383
- // the panel and is scrollable via the terminal's native scrollback. See
1384
- // "Layout" note at the top of this file for why overlay:true breaks
1385
- // transcript scrolling.
1386
- overlay: false,
1387
- });
1388
-
1389
- // ── Build the JSON payload returned to the LLM ──
1390
- //
1391
- // Structure is intentionally SYMMETRIC with the questions schema the LLM
1392
- // authored (AskUserParams): each question carries a `tab` as its identity
1393
- // key, and each answer echoes that same `tab`, so the LLM can correlate
1394
- // answers back to its own questions by key with zero parsing effort. This
1395
- // replaces the old `tab: answer` text format, which broke when a custom
1396
- // answer contained a colon or newline (it could overwrite or collide with
1397
- // adjacent lines).
1398
- //
1399
- // Field shape (only relevant fields are emitted no noise):
1400
- // single-select, option picked : { tab, answer }
1401
- // single-select, custom typed : { tab, custom } // custom NOT in answer
1402
- // multi-select, options picked : { tab, answers: [...] }
1403
- // multi-select, options+custom : { tab, answers: [...], custom }
1404
- // multi-select, custom only : { tab, custom }
1405
- // multi-select, empty commit : { tab, answers: [] } // NOT skipped
1406
- // any question, Tab-skipped : { tab, skipped: true }
1407
- //
1408
- // `custom` gets its own key (rather than being mixed into answer/answers)
1409
- // so the LLM can tell the user stepped outside the offered options — a
1410
- // useful signal, not an anti-spoofing measure. The empty-message note is
1411
- // omitted entirely ("user left no note" is noise the LLM doesn't need).
1412
- const jsonAnswers = result.answers.map((a): Record<string, unknown> => {
1413
- const out: Record<string, unknown> = { tab: a.tab };
1414
- switch (a.kind) {
1415
- case "skipped":
1416
- out.skipped = true;
1417
- break;
1418
- case "single":
1419
- out.answer = a.option;
1420
- break;
1421
- case "custom":
1422
- out.custom = a.text;
1423
- break;
1424
- case "multi":
1425
- out.answers = a.options;
1426
- if (a.custom) out.custom = a.custom;
1427
- break;
1428
- }
1429
- return out;
1430
- });
1431
- const payload: Record<string, unknown> = {
1432
- cancelled: result.cancelled,
1433
- answers: jsonAnswers,
1434
- };
1435
- if (result.message) payload.message = result.message;
1436
-
1437
- return {
1438
- content: [{ type: "text", text: JSON.stringify(payload) }],
1439
- details: result,
1440
- };
1441
- },
1442
- renderResult(result, options, theme, context) {
1443
- // context.args.questions is the schema-static type; AskUserResultView
1444
- // only needs header+tab, so the structural subtype is compatible.
1445
- const questions = context.args?.questions ?? [];
1446
- const details = result.details ?? { questions: [], answers: [], cancelled: true };
1447
- const comp =
1448
- context.lastComponent instanceof AskUserResultView
1449
- ? context.lastComponent
1450
- : new AskUserResultView(questions, details, theme);
1451
- comp.setExpanded(options.expanded);
1452
- return comp;
1453
- },
1454
- });
1443
+ pi.registerTool<typeof AskUserParams, AskUserResult>({
1444
+ name: "ask_user",
1445
+ label: "Ask User",
1446
+ description:
1447
+ 'Ask the user one or more questions with options. Supports single-select (◎→◉) and multi-select (□→▣, space toggles). Every question always includes a \'Type something.\' row so the user can type a custom answer whenever none of the provided options fit — this is built in and cannot be disabled, so never assume the user is restricted to your listed options. The custom-input draft is preserved across tab switches, and a focused side panel shows extended detail (ASCII layouts, code, reasoning) when an option carries a `preview` field. Each option needs a short `label` + a `description` (shown beneath it); add a `preview` field only when a description can\'t fully convey the option. The panel is collapsible (Ctrl+\\). Use for clarifying requirements, getting preferences, or confirming decisions. Avoid using this to pick one item from a long list you just enumerated (e.g. "which of these 8 fixes should I start with?"): options are capped at a handful for a reason, and if the choice isn\'t a real either/or, present the list in a normal message and let the user reply freely, or just proceed with the highest-priority item — reserve ask_user for genuine decisions with a few distinct, mutually-exclusive paths. All displayed user-facing text should use the conversation\'s language. The result is returned as JSON: `{ "cancelled": bool, "answers": [{ "tab": <the question\'s tab>, ... }], "message"?: string }`. Each answer echoes the question\'s `tab` so you can correlate by key. Per answer only the relevant fields appear: single-select option pick → `answer`; single-select custom text → `custom`; multi-select option picks → `answers: [...]`; multi-select with custom → `answers` + `custom`; multi-select empty commit (skippable, submitted with nothing) → `answers: []`; Tab-skipped → `skipped: true`. `custom` is a sibling of `answer`/`answers`, never mixed in — it signals the user typed something outside the offered options. The optional top-level `message` is a free-form note the user can attach on the review screen (about overall direction, pacing, or anything beyond the specific questions); it is user-provided and out-of-band: you cannot set it via the parameters, and it may be absent; when present, treat it as high-priority context that can override or reframe the answers above it.',
1448
+ parameters: AskUserParams,
1449
+
1450
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1451
+ if (!ctx.hasUI) {
1452
+ return errorResult("Error: UI not available (running in non-interactive mode)");
1453
+ }
1454
+ if (params.questions.length === 0) {
1455
+ return errorResult("Error: No questions provided");
1456
+ }
1457
+
1458
+ const questions: Question[] = params.questions.map((q) => ({
1459
+ ...q,
1460
+ options: q.options.map((o) => ({ ...o })),
1461
+ }));
1462
+
1463
+ const result = await ctx.ui.custom<AskUserResult>(
1464
+ (tui, theme, _kb, done) => {
1465
+ return new AskUserPanel(questions, tui, theme, {
1466
+ onResult: (r) => done(r),
1467
+ });
1468
+ },
1469
+ {
1470
+ // overlay:false renders the panel into pi's bottom editorContainer slot
1471
+ // (the same path ctx.ui.select()/input() take) instead of compositing a
1472
+ // screen overlay over everything. The chat transcript stays visible above
1473
+ // the panel and is scrollable via the terminal's native scrollback. See
1474
+ // "Layout" note at the top of this file for why overlay:true breaks
1475
+ // transcript scrolling.
1476
+ overlay: false,
1477
+ },
1478
+ );
1479
+
1480
+ // ── Build the JSON payload returned to the LLM ──
1481
+ //
1482
+ // Structure is intentionally SYMMETRIC with the questions schema the LLM
1483
+ // authored (AskUserParams): each question carries a `tab` as its identity
1484
+ // key, and each answer echoes that same `tab`, so the LLM can correlate
1485
+ // answers back to its own questions by key with zero parsing effort. This
1486
+ // replaces the old `tab: answer` text format, which broke when a custom
1487
+ // answer contained a colon or newline (it could overwrite or collide with
1488
+ // adjacent lines).
1489
+ //
1490
+ // Field shape (only relevant fields are emitted — no noise):
1491
+ // single-select, option picked : { tab, answer }
1492
+ // single-select, custom typed : { tab, custom } // custom NOT in answer
1493
+ // multi-select, options picked : { tab, answers: [...] }
1494
+ // multi-select, options+custom : { tab, answers: [...], custom }
1495
+ // multi-select, custom only : { tab, custom }
1496
+ // multi-select, empty commit : { tab, answers: [] } // NOT skipped
1497
+ // any question, Tab-skipped : { tab, skipped: true }
1498
+ //
1499
+ // `custom` gets its own key (rather than being mixed into answer/answers)
1500
+ // so the LLM can tell the user stepped outside the offered options — a
1501
+ // useful signal, not an anti-spoofing measure. The empty-message note is
1502
+ // omitted entirely ("user left no note" is noise the LLM doesn't need).
1503
+ const jsonAnswers = result.answers.map((a): Record<string, unknown> => {
1504
+ const out: Record<string, unknown> = { tab: a.tab };
1505
+ switch (a.kind) {
1506
+ case "skipped":
1507
+ out.skipped = true;
1508
+ break;
1509
+ case "single":
1510
+ out.answer = a.option;
1511
+ break;
1512
+ case "custom":
1513
+ out.custom = a.text;
1514
+ break;
1515
+ case "multi":
1516
+ out.answers = a.options;
1517
+ if (a.custom) out.custom = a.custom;
1518
+ break;
1519
+ }
1520
+ return out;
1521
+ });
1522
+ const payload: Record<string, unknown> = {
1523
+ cancelled: result.cancelled,
1524
+ answers: jsonAnswers,
1525
+ };
1526
+ if (result.message) payload.message = result.message;
1527
+
1528
+ return {
1529
+ content: [{ type: "text", text: JSON.stringify(payload) }],
1530
+ details: result,
1531
+ };
1532
+ },
1533
+ renderResult(result, options, theme, context) {
1534
+ // context.args.questions is the schema-static type; AskUserResultView
1535
+ // only needs header+tab, so the structural subtype is compatible.
1536
+ const questions = context.args?.questions ?? [];
1537
+ // Field-level fallback: result.details may be a truthy partial object
1538
+ // (e.g. { cancelled: false }) whose .answers is undefined, which would
1539
+ // crash getStatus/renderCollapsed/renderCard with "Cannot read
1540
+ // properties of undefined (reading 'some')". Normalize every field.
1541
+ const raw = result.details ?? {};
1542
+ const details: AskUserResult = {
1543
+ questions: raw.questions ?? [],
1544
+ answers: raw.answers ?? [],
1545
+ cancelled: raw.cancelled ?? true,
1546
+ message: raw.message,
1547
+ };
1548
+ const comp =
1549
+ context.lastComponent instanceof AskUserResultView
1550
+ ? context.lastComponent
1551
+ : new AskUserResultView(questions, details, theme);
1552
+ comp.setExpanded(options.expanded);
1553
+ return comp;
1554
+ },
1555
+ });
1455
1556
  }