@juicesharp/rpiv-ask-user-question 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,276 @@
1
+ import type { QuestionnaireAction } from "./dispatch.js";
2
+ import { computeFocusedOptionHasPreview, type QuestionnaireState } from "./questionnaire-state.js";
3
+ import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "./types.js";
4
+ import type { WrappingSelectItem } from "./wrapping-select.js";
5
+
6
+ /**
7
+ * Per-dispatch context that doesn't live on canonical state. Captured by the runtime each
8
+ * tick (`pendingNotesValue` is `notesInput.getValue().trim()`; `itemsByTab` is constant for
9
+ * the session lifetime). The reducer never touches a live component — every IO call is
10
+ * emitted as an `Effect` in the result.
11
+ */
12
+ export interface ApplyContext {
13
+ questions: readonly QuestionData[];
14
+ itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
15
+ /** Trimmed notes input value at dispatch time. The reducer uses this for `notes_exit`
16
+ * to decide whether to merge notes into the current answer or delete pending notes. */
17
+ pendingNotesValue: string;
18
+ }
19
+
20
+ /**
21
+ * Declarative side-effects emitted by `applyAction`. The runtime executes them after
22
+ * committing the new state, then asks the view-adapter to re-project. Closed set —
23
+ * adding an effect requires updating both the union AND the runtime's `runEffect` switch
24
+ * (compiler-enforced exhaustive). No string-keyed escape hatch.
25
+ */
26
+ export type Effect =
27
+ | { kind: "set_input_buffer"; value: string }
28
+ | { kind: "clear_input_buffer" }
29
+ | { kind: "set_notes_value"; value: string }
30
+ | { kind: "set_notes_focused"; focused: boolean }
31
+ | { kind: "set_active_preview_pane"; paneIndex: number }
32
+ | { kind: "done"; result: QuestionnaireResult };
33
+
34
+ export interface ApplyResult {
35
+ state: QuestionnaireState;
36
+ effects: readonly Effect[];
37
+ }
38
+
39
+ const EMPTY_NOTES: ReadonlyMap<number, string> = new Map();
40
+
41
+ function notesOf(state: QuestionnaireState): ReadonlyMap<number, string> {
42
+ return state.notesByTab ?? EMPTY_NOTES;
43
+ }
44
+
45
+ function orderedAnswers(state: QuestionnaireState, questions: readonly QuestionData[]): QuestionAnswer[] {
46
+ const out: QuestionAnswer[] = [];
47
+ for (let i = 0; i < questions.length; i++) {
48
+ const a = state.answers.get(i);
49
+ if (a) out.push(a);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function withFocusedOptionHasPreview(
55
+ state: QuestionnaireState,
56
+ questions: readonly QuestionData[],
57
+ ): QuestionnaireState {
58
+ const focusedOptionHasPreview = computeFocusedOptionHasPreview(questions, state.currentTab, state.optionIndex);
59
+ if (state.focusedOptionHasPreview === focusedOptionHasPreview) return state;
60
+ return { ...state, focusedOptionHasPreview };
61
+ }
62
+
63
+ function syncMultiSelectFromAnswers(
64
+ answers: ReadonlyMap<number, QuestionAnswer>,
65
+ questions: readonly QuestionData[],
66
+ tab: number,
67
+ ): ReadonlySet<number> {
68
+ const q = questions[tab];
69
+ if (!q?.multiSelect) return new Set();
70
+ const saved = answers.get(tab);
71
+ const labels = saved?.selected ?? [];
72
+ const indices = new Set<number>();
73
+ for (let i = 0; i < q.options.length; i++) {
74
+ if (labels.includes(q.options[i]!.label)) indices.add(i);
75
+ }
76
+ return indices;
77
+ }
78
+
79
+ function persistMultiSelectAnswer(state: QuestionnaireState, ctx: ApplyContext): ReadonlyMap<number, QuestionAnswer> {
80
+ const q = ctx.questions[state.currentTab];
81
+ if (!q?.multiSelect) return state.answers;
82
+ const selected: string[] = [];
83
+ for (let i = 0; i < q.options.length; i++) {
84
+ if (state.multiSelectChecked.has(i)) selected.push(q.options[i]!.label);
85
+ }
86
+ const out = new Map(state.answers);
87
+ if (selected.length === 0) {
88
+ out.delete(state.currentTab);
89
+ return out;
90
+ }
91
+ const pendingNotes = notesOf(state).get(state.currentTab);
92
+ out.set(state.currentTab, {
93
+ questionIndex: state.currentTab,
94
+ question: q.question,
95
+ kind: "multi",
96
+ answer: null,
97
+ selected,
98
+ ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
99
+ });
100
+ return out;
101
+ }
102
+
103
+ function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyContext): ApplyResult {
104
+ const transitioned: QuestionnaireState = {
105
+ ...state,
106
+ currentTab: nextTab,
107
+ optionIndex: 0,
108
+ inputMode: false,
109
+ notesVisible: false,
110
+ chatFocused: false,
111
+ submitChoiceIndex: 0,
112
+ multiSelectChecked: syncMultiSelectFromAnswers(state.answers, ctx.questions, nextTab),
113
+ };
114
+ const finalState = withFocusedOptionHasPreview(transitioned, ctx.questions);
115
+ const paneIndex = Math.min(nextTab, Math.max(0, ctx.questions.length - 1));
116
+ const notesValue = notesOf(state).get(nextTab) ?? state.answers.get(nextTab)?.notes ?? "";
117
+ return {
118
+ state: finalState,
119
+ effects: [
120
+ { kind: "set_active_preview_pane", paneIndex },
121
+ { kind: "set_notes_focused", focused: false },
122
+ { kind: "set_notes_value", value: notesValue },
123
+ ],
124
+ };
125
+ }
126
+
127
+ function doneFor(state: QuestionnaireState, ctx: ApplyContext, cancelled: boolean): ApplyResult {
128
+ const result: QuestionnaireResult = { answers: orderedAnswers(state, ctx.questions), cancelled };
129
+ return { state, effects: [{ kind: "done", result }] };
130
+ }
131
+
132
+ /**
133
+ * Pure reducer: given (state, action, ctx) returns new state + a list of declarative IO
134
+ * effects. Mirrors `rpiv-todo`'s `applyTaskMutation`.
135
+ *
136
+ * Actions NOT routed through this reducer (handled by the runtime directly):
137
+ * - `ignore` — per-keystroke input-buffer mutation; no canonical-state change. The runtime
138
+ * calls `pane.appendInput` / `pane.backspaceInput` directly via `handleIgnoreInline`.
139
+ * - `notes_visible` two-pass forward — the runtime probes the dispatcher for `notes_exit`;
140
+ * every other key forwards to the pi-tui `Input` without reducer involvement.
141
+ */
142
+ export function applyAction(state: QuestionnaireState, action: QuestionnaireAction, ctx: ApplyContext): ApplyResult {
143
+ switch (action.kind) {
144
+ case "nav": {
145
+ const items = ctx.itemsByTab[state.currentTab] ?? [];
146
+ const item = items[action.nextIndex];
147
+ const inputMode = item?.kind === "other";
148
+ const next = withFocusedOptionHasPreview(
149
+ { ...state, optionIndex: action.nextIndex, inputMode },
150
+ ctx.questions,
151
+ );
152
+ if (!inputMode) {
153
+ return { state: next, effects: [{ kind: "clear_input_buffer" }] };
154
+ }
155
+ const prior = state.answers.get(state.currentTab);
156
+ if (prior?.kind === "custom" && typeof prior.answer === "string") {
157
+ return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
158
+ }
159
+ return { state: next, effects: [] };
160
+ }
161
+ case "tab_switch": {
162
+ return switchTabResult(state, action.nextTab, ctx);
163
+ }
164
+ case "confirm": {
165
+ let answer = action.answer;
166
+ if (answer.kind === "option" && answer.answer) {
167
+ const q = ctx.questions[answer.questionIndex];
168
+ const matched = q?.options.find((o) => o.label === answer.answer);
169
+ if (matched?.preview && matched.preview.length > 0) {
170
+ answer = { ...answer, preview: matched.preview };
171
+ }
172
+ }
173
+ const pendingNotes = notesOf(state).get(answer.questionIndex);
174
+ if (pendingNotes && pendingNotes.length > 0) {
175
+ answer = { ...answer, notes: pendingNotes };
176
+ }
177
+ const answers = new Map(state.answers);
178
+ answers.set(answer.questionIndex, answer);
179
+ const next: QuestionnaireState = { ...state, answers };
180
+ if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
181
+ return doneFor(next, ctx, false);
182
+ }
183
+ case "toggle": {
184
+ const checked = new Set(state.multiSelectChecked);
185
+ if (checked.has(action.index)) checked.delete(action.index);
186
+ else checked.add(action.index);
187
+ const intermediate: QuestionnaireState = { ...state, multiSelectChecked: checked };
188
+ const answers = persistMultiSelectAnswer(intermediate, ctx);
189
+ return { state: { ...intermediate, answers }, effects: [] };
190
+ }
191
+ case "multi_confirm": {
192
+ const q = ctx.questions[state.currentTab];
193
+ if (!q) return { state, effects: [] };
194
+ const pendingNotes = notesOf(state).get(state.currentTab);
195
+ const answers = new Map(state.answers);
196
+ answers.set(state.currentTab, {
197
+ questionIndex: state.currentTab,
198
+ question: q.question,
199
+ kind: "multi",
200
+ answer: null,
201
+ selected: action.selected,
202
+ ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
203
+ });
204
+ const synced: QuestionnaireState = {
205
+ ...state,
206
+ answers,
207
+ multiSelectChecked: syncMultiSelectFromAnswers(answers, ctx.questions, state.currentTab),
208
+ };
209
+ if (action.autoAdvanceTab !== undefined) return switchTabResult(synced, action.autoAdvanceTab, ctx);
210
+ return doneFor(synced, ctx, false);
211
+ }
212
+ case "cancel": {
213
+ return doneFor(state, ctx, true);
214
+ }
215
+ case "notes_enter": {
216
+ const value = state.answers.get(state.currentTab)?.notes ?? "";
217
+ return {
218
+ state: { ...state, notesVisible: true },
219
+ effects: [
220
+ { kind: "set_notes_value", value },
221
+ { kind: "set_notes_focused", focused: true },
222
+ ],
223
+ };
224
+ }
225
+ case "notes_exit": {
226
+ const trimmed = ctx.pendingNotesValue;
227
+ const notes = new Map(notesOf(state));
228
+ const answers = new Map(state.answers);
229
+ if (trimmed.length === 0) {
230
+ notes.delete(state.currentTab);
231
+ const prev = answers.get(state.currentTab);
232
+ if (prev?.notes) {
233
+ const stripped = { ...prev };
234
+ delete (stripped as { notes?: string }).notes;
235
+ answers.set(state.currentTab, stripped);
236
+ }
237
+ } else {
238
+ notes.set(state.currentTab, trimmed);
239
+ const prev = answers.get(state.currentTab);
240
+ if (prev) answers.set(state.currentTab, { ...prev, notes: trimmed });
241
+ }
242
+ return {
243
+ state: { ...state, notesByTab: notes, answers, notesVisible: false },
244
+ effects: [{ kind: "set_notes_focused", focused: false }],
245
+ };
246
+ }
247
+ case "submit": {
248
+ return doneFor(state, ctx, false);
249
+ }
250
+ case "submit_nav": {
251
+ return { state: { ...state, submitChoiceIndex: action.nextIndex }, effects: [] };
252
+ }
253
+ case "focus_chat": {
254
+ return { state: { ...state, chatFocused: true }, effects: [] };
255
+ }
256
+ case "focus_options": {
257
+ let optionIndex = state.optionIndex;
258
+ let inputMode = state.inputMode;
259
+ let effects: readonly Effect[] = [];
260
+ if (action.optionIndex !== undefined) {
261
+ optionIndex = action.optionIndex;
262
+ const items = ctx.itemsByTab[state.currentTab] ?? [];
263
+ inputMode = items[optionIndex]?.kind === "other";
264
+ if (!inputMode) effects = [{ kind: "clear_input_buffer" }];
265
+ }
266
+ const next = withFocusedOptionHasPreview(
267
+ { ...state, chatFocused: false, optionIndex, inputMode },
268
+ ctx.questions,
269
+ );
270
+ return { state: next, effects };
271
+ }
272
+ case "ignore": {
273
+ return { state, effects: [] };
274
+ }
275
+ }
276
+ }
@@ -9,28 +9,31 @@ import {
9
9
  type QuestionnaireResult,
10
10
  type QuestionParams,
11
11
  QuestionParamsSchema,
12
+ SENTINEL_LABELS,
12
13
  } from "./types.js";
13
14
  import { validateQuestionnaire } from "./validate-questionnaire.js";
14
15
  import type { WrappingSelectItem } from "./wrapping-select.js";
15
16
 
16
- const TYPE_SOMETHING_LABEL = "Type something.";
17
- const NEXT_LABEL = "Next";
18
17
  const ERROR_NO_UI = "Error: UI not available (running in non-interactive mode)";
19
18
 
20
19
  export { chatNumberingFor } from "./questionnaire-state.js";
21
20
 
22
21
  export function buildItemsForQuestion(question: QuestionData): WrappingSelectItem[] {
23
- const items = question.options.map((o) => ({ label: o.label, description: o.description }));
22
+ const items: WrappingSelectItem[] = question.options.map((o) => ({
23
+ kind: "option",
24
+ label: o.label,
25
+ description: o.description,
26
+ }));
24
27
  // Multi-select gets a "Next" sentinel row at the bottom so `Enter` on regular option rows
25
28
  // can be repurposed as a per-row toggle (matching `Space`); committing + advancing to the
26
- // next tab requires moving focus onto the Next row first. Mirrors the `isOther` pattern.
27
- if (question.multiSelect) return [...items, { label: NEXT_LABEL, isNext: true }];
29
+ // next tab requires moving focus onto the Next row first. Mirrors the `kind: "other"` pattern.
30
+ if (question.multiSelect) return [...items, { kind: "next", label: SENTINEL_LABELS.next }];
28
31
  // Side-by-side preview layout pins the options column to PREVIEW_LEFT_COLUMN_MAX_WIDTH (~40
29
32
  // cols), which truncates inline custom-text input. CC suppresses the row in this layout for
30
33
  // the same reason — the "Chat about this" row remains as the free-form escape hatch.
31
34
  const hasAnyPreview = question.options.some((o) => typeof o.preview === "string" && o.preview.length > 0);
32
35
  if (hasAnyPreview) return items;
33
- return [...items, { label: TYPE_SOMETHING_LABEL, isOther: true }];
36
+ return [...items, { kind: "other", label: SENTINEL_LABELS.other }];
34
37
  }
35
38
 
36
39
  export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
package/dialog-builder.ts CHANGED
@@ -9,19 +9,18 @@ import { QuestionTabStrategy, SubmitTabStrategy, type TabStrategy } from "./tab-
9
9
  import type { QuestionData } from "./types.js";
10
10
  import type { WrappingSelect } from "./wrapping-select.js";
11
11
 
12
- // Hint text — these constants are also referenced by tests as substrings of the rendered
13
- // hint line. Keep them as full "contiguous substrings" of the buildHintText() output so the
14
- // `expect(joined).toContain(HINT_*)` assertions remain valid.
15
- //
16
- // Format (per UX spec):
17
- // <Single> = "Enter to select · ↑/↓ to navigate · Esc to cancel"
18
- // <Multi> = "Enter to select · ↑/↓ to navigate · Tab to switch questions · Esc to cancel"
19
- // + multiSelect = inserts " · Space to toggle"
20
- // + answered = inserts " · n to add notes"
21
- export const HINT_SINGLE = "Enter to select · ↑/↓ to navigate · Esc to cancel";
22
- export const HINT_MULTI = "Enter to select · ↑/↓ to navigate · Tab to switch questions · Esc to cancel";
23
- export const HINT_MULTISELECT_SUFFIX = " · Space to toggle";
24
- export const HINT_NOTES_SUFFIX = " · n to add notes";
12
+ // Hint phrases — single source of truth for both production (`buildHintText`) and the
13
+ // substring assertions in `dialog-container.test.ts`.
14
+ export const HINT_PART_ENTER = "Enter to select";
15
+ export const HINT_PART_NAV = "↑/↓ to navigate";
16
+ export const HINT_PART_TOGGLE = "Space to toggle";
17
+ export const HINT_PART_NOTES = "n to add notes";
18
+ export const HINT_PART_TAB = "Tab to switch questions";
19
+ export const HINT_PART_CANCEL = "Esc to cancel";
20
+ export const HINT_SINGLE = [HINT_PART_ENTER, HINT_PART_NAV, HINT_PART_CANCEL].join(" · ");
21
+ export const HINT_MULTI = [HINT_PART_ENTER, HINT_PART_NAV, HINT_PART_TAB, HINT_PART_CANCEL].join(" · ");
22
+ export const HINT_MULTISELECT_SUFFIX = ` · ${HINT_PART_TOGGLE}`;
23
+ export const HINT_NOTES_SUFFIX = ` · ${HINT_PART_NOTES}`;
25
24
  export const REVIEW_HEADING = "Review your answers";
26
25
  export const READY_PROMPT = "Ready to submit your answers?";
27
26
  export const INCOMPLETE_WARNING_PREFIX = "⚠ Answer remaining questions before submitting:";
package/dispatch.ts CHANGED
@@ -35,14 +35,12 @@ export interface QuestionnaireKeybindings {
35
35
  matches(data: string, name: string): boolean;
36
36
  }
37
37
 
38
- export type QuestionnaireDispatchState = QuestionnaireDispatchSnapshot;
39
-
40
38
  export function wrapTab(index: number, total: number): number {
41
39
  if (total <= 0) return 0;
42
40
  return ((index % total) + total) % total;
43
41
  }
44
42
 
45
- export function allAnswered(state: QuestionnaireDispatchState): boolean {
43
+ export function allAnswered(state: QuestionnaireDispatchSnapshot): boolean {
46
44
  if (state.questions.length === 0) return false;
47
45
  for (let i = 0; i < state.questions.length; i++) {
48
46
  if (!state.answers.has(i)) return false;
@@ -50,17 +48,17 @@ export function allAnswered(state: QuestionnaireDispatchState): boolean {
50
48
  return true;
51
49
  }
52
50
 
53
- function totalTabs(state: QuestionnaireDispatchState): number {
51
+ function totalTabs(state: QuestionnaireDispatchSnapshot): number {
54
52
  return state.isMulti ? state.questions.length + 1 : 1;
55
53
  }
56
54
 
57
- function computeAutoAdvanceTab(state: QuestionnaireDispatchState): number | undefined {
55
+ function computeAutoAdvanceTab(state: QuestionnaireDispatchSnapshot): number | undefined {
58
56
  if (!state.isMulti) return undefined;
59
57
  if (state.currentTab < state.questions.length - 1) return state.currentTab + 1;
60
58
  return state.questions.length;
61
59
  }
62
60
 
63
- function buildSingleSelectAnswer(state: QuestionnaireDispatchState): QuestionAnswer | null {
61
+ function buildSingleSelectAnswer(state: QuestionnaireDispatchSnapshot): QuestionAnswer | null {
64
62
  const q = state.questions[state.currentTab];
65
63
  if (!q) return null;
66
64
 
@@ -68,12 +66,12 @@ function buildSingleSelectAnswer(state: QuestionnaireDispatchState): QuestionAns
68
66
  // currentItem() to return the chat sentinel even if inputMode is still true (e.g. user
69
67
  // navigated from "Type something." and DOWN focused the chat row).
70
68
  const item = state.currentItem;
71
- if (item?.isChat) {
69
+ if (item?.kind === "chat") {
72
70
  return {
73
71
  questionIndex: state.currentTab,
74
72
  question: q.question,
73
+ kind: "chat",
75
74
  answer: item.label,
76
- wasChat: true,
77
75
  };
78
76
  }
79
77
 
@@ -82,23 +80,26 @@ function buildSingleSelectAnswer(state: QuestionnaireDispatchState): QuestionAns
82
80
  return {
83
81
  questionIndex: state.currentTab,
84
82
  question: q.question,
83
+ kind: "custom",
85
84
  answer: label.length > 0 ? label : null,
86
- wasCustom: true,
87
85
  };
88
86
  }
89
87
  if (!item) return null;
90
- if (item.isOther) {
88
+ if (item.kind === "other") {
89
+ return null;
90
+ }
91
+ if (item.kind === "next") {
91
92
  return null;
92
93
  }
93
94
  return {
94
95
  questionIndex: state.currentTab,
95
96
  question: q.question,
97
+ kind: "option",
96
98
  answer: item.label,
97
- wasCustom: false,
98
99
  };
99
100
  }
100
101
 
101
- function buildMultiSelected(state: QuestionnaireDispatchState): string[] {
102
+ function buildMultiSelected(state: QuestionnaireDispatchSnapshot): string[] {
102
103
  const q = state.questions[state.currentTab];
103
104
  if (!q) return [];
104
105
  const out: string[] = [];
@@ -111,7 +112,7 @@ function buildMultiSelected(state: QuestionnaireDispatchState): string[] {
111
112
  return out;
112
113
  }
113
114
 
114
- function tabSwitchAction(data: string, state: QuestionnaireDispatchState): QuestionnaireAction | null {
115
+ function tabSwitchAction(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction | null {
115
116
  if (!state.isMulti) return null;
116
117
  const total = totalTabs(state);
117
118
  if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
@@ -126,7 +127,7 @@ function tabSwitchAction(data: string, state: QuestionnaireDispatchState): Quest
126
127
  // DOWN navigation helper shared by inputMode and normal nav branches.
127
128
  // Emits focus_chat at the boundary (last item) so the host can transfer focus to the chat row
128
129
  // without mutating optionIndex — UP-from-chat then lands on items.length - 1 (continuous cycle).
129
- function nextNavOnDown(state: QuestionnaireDispatchState): QuestionnaireAction {
130
+ function nextNavOnDown(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
130
131
  if (state.items.length > 0 && state.optionIndex === state.items.length - 1) {
131
132
  return { kind: "focus_chat" };
132
133
  }
@@ -136,14 +137,14 @@ function nextNavOnDown(state: QuestionnaireDispatchState): QuestionnaireAction {
136
137
  // UP navigation helper, symmetric with nextNavOnDown. At the TOP boundary (optionIndex 0)
137
138
  // emits focus_chat so the cycle wraps `[chat, option0, …, optionLast]` — without this, UP at
138
139
  // option 0 would skip the chat row entirely (Defect 2). Above the boundary, decrement.
139
- function prevNavOnUp(state: QuestionnaireDispatchState): QuestionnaireAction {
140
+ function prevNavOnUp(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
140
141
  if (state.items.length > 0 && state.optionIndex === 0) {
141
142
  return { kind: "focus_chat" };
142
143
  }
143
144
  return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, state.items.length)) };
144
145
  }
145
146
 
146
- export function handleQuestionnaireInput(data: string, state: QuestionnaireDispatchState): QuestionnaireAction {
147
+ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
147
148
  const kb = state.keybindings;
148
149
 
149
150
  if (state.notesVisible) {
@@ -227,7 +228,7 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
227
228
  }
228
229
 
229
230
  if (q.multiSelect) {
230
- const onNext = state.currentItem?.isNext === true;
231
+ const onNext = state.currentItem?.kind === "next";
231
232
  // Space toggles the focused row's checkbox. Ignored on the Next sentinel — Next is
232
233
  // not a real option and has no checked/unchecked state.
233
234
  if (data === SPACE_KEY) {
package/format-answer.ts CHANGED
@@ -26,14 +26,21 @@ export type FormatAnswerVariant = "summary" | "envelope";
26
26
 
27
27
  /**
28
28
  * Format a `QuestionAnswer` to its scalar string form. Variant controls only the
29
- * `wasChat` branch — the envelope's two-sentence imperative is needed by the LLM, the
30
- * dialog summary's one-sentence reminder is not. All other branches return identical
31
- * strings; the `wasCustom` empty-string handling and the default-fallback both unify
32
- * on `NO_INPUT_PLACEHOLDER`.
29
+ * `kind: "chat"` branch — the envelope's two-sentence imperative is needed by the LLM,
30
+ * the dialog summary's one-sentence reminder is not. All other branches return identical
31
+ * strings; the `kind: "custom"` empty-string handling and the option fallback both unify
32
+ * on `NO_INPUT_PLACEHOLDER`. Switch is exhaustive — non-`void` return enforces every
33
+ * variant is handled.
33
34
  */
34
35
  export function formatAnswerScalar(a: QuestionAnswer, variant: FormatAnswerVariant): string {
35
- if (a.wasChat) return variant === "envelope" ? CHAT_CONTINUATION_MESSAGE : CHAT_SUMMARY_MESSAGE;
36
- if (a.selected && a.selected.length > 0) return a.selected.join(", ");
37
- if (a.wasCustom) return a.answer && a.answer.length > 0 ? a.answer : NO_INPUT_PLACEHOLDER;
38
- return a.answer ?? NO_INPUT_PLACEHOLDER;
36
+ switch (a.kind) {
37
+ case "chat":
38
+ return variant === "envelope" ? CHAT_CONTINUATION_MESSAGE : CHAT_SUMMARY_MESSAGE;
39
+ case "multi":
40
+ return a.selected && a.selected.length > 0 ? a.selected.join(", ") : NO_INPUT_PLACEHOLDER;
41
+ case "custom":
42
+ return a.answer && a.answer.length > 0 ? a.answer : NO_INPUT_PLACEHOLDER;
43
+ case "option":
44
+ return a.answer ?? NO_INPUT_PLACEHOLDER;
45
+ }
39
46
  }
@@ -2,7 +2,7 @@ import type { Theme } from "@mariozechner/pi-coding-agent";
2
2
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@mariozechner/pi-tui";
3
3
  import type { DialogState } from "./dialog-builder.js";
4
4
  import type { StatefulComponent } from "./stateful-component.js";
5
- import type { QuestionData } from "./types.js";
5
+ import { type QuestionData, SENTINEL_LABELS } from "./types.js";
6
6
 
7
7
  const ACTIVE_POINTER = "❯ ";
8
8
  const INACTIVE_POINTER = " ";
@@ -13,7 +13,6 @@ const BOX_LABEL_GAP = " ";
13
13
  // CC parity: description continuation indents to col 2 (past the pointer slot), NOT to the
14
14
  // full prefix column. Wrap width still uses prefixVisibleWidth so naturalHeight matches render.
15
15
  const CONTINUATION_INDENT = " ";
16
- const NEXT_LABEL = "Next";
17
16
 
18
17
  /**
19
18
  * Renders the multi-select option list (one row per option — pointer + checkbox + label —
@@ -90,7 +89,9 @@ export class MultiSelectOptions implements StatefulComponent<DialogState> {
90
89
  const nextIndex = this.question.options.length;
91
90
  const nextActive = this.focused && this.state.optionIndex === nextIndex;
92
91
  const nextPointer = nextActive ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
93
- const nextLabel = nextActive ? this.theme.fg("accent", this.theme.bold(NEXT_LABEL)) : NEXT_LABEL;
92
+ const nextLabel = nextActive
93
+ ? this.theme.fg("accent", this.theme.bold(SENTINEL_LABELS.next))
94
+ : SENTINEL_LABELS.next;
94
95
  lines.push(truncateToWidth(`${nextPointer}${nextLabel}`, width, ""));
95
96
  return lines;
96
97
  }
@@ -0,0 +1,93 @@
1
+ import type { Component } from "@mariozechner/pi-tui";
2
+ import { WrappingSelect, type WrappingSelectItem, type WrappingSelectTheme } from "./wrapping-select.js";
3
+
4
+ /**
5
+ * Maximum number of option rows visible in the WrappingSelect window. Lifted here from
6
+ * `preview-pane.ts` so the cap travels with the option-list owner.
7
+ */
8
+ export const MAX_VISIBLE_OPTIONS = 10;
9
+
10
+ export interface OptionListViewConfig {
11
+ items: readonly WrappingSelectItem[];
12
+ theme: WrappingSelectTheme;
13
+ }
14
+
15
+ /**
16
+ * Sole owner of the option list's interactive state — `selectedIndex`, `focused`, input buffer,
17
+ * confirmed-index marker. Wraps a single `WrappingSelect`.
18
+ *
19
+ * The session targets this directly for input-buffer effects + per-tick `snapshot` input-buffer
20
+ * reads. The view-adapter targets this directly for `setSelectedIndex` / `setFocused` /
21
+ * `setConfirmedIndex`. `PreviewPane` queries `getSelectedIndex()` and `isFocused()` at render
22
+ * time — no mirrored state cells.
23
+ *
24
+ * NOT a `StatefulComponent<S>` — owns its mutable fields directly rather than projecting from a
25
+ * canonical state object.
26
+ */
27
+ export class OptionListView implements Component {
28
+ private readonly select: WrappingSelect;
29
+ private selectedIndex = 0;
30
+ private focused = true;
31
+
32
+ constructor(config: OptionListViewConfig) {
33
+ // Reserve a slot for the chat row in the WrappingSelect's number-padding so the column
34
+ // width is identical whether or not the user navigates into chat (chat row uses
35
+ // items.length + 1).
36
+ this.select = new WrappingSelect(config.items, Math.min(config.items.length, MAX_VISIBLE_OPTIONS), config.theme, {
37
+ numberStartOffset: 0,
38
+ totalItemsForNumbering: config.items.length + 1,
39
+ });
40
+ }
41
+
42
+ setSelectedIndex(index: number): void {
43
+ this.selectedIndex = index;
44
+ this.select.setSelectedIndex(index);
45
+ }
46
+
47
+ getSelectedIndex(): number {
48
+ return this.selectedIndex;
49
+ }
50
+
51
+ setFocused(focused: boolean): void {
52
+ this.focused = focused;
53
+ this.select.setFocused(focused);
54
+ }
55
+
56
+ isFocused(): boolean {
57
+ return this.focused;
58
+ }
59
+
60
+ setConfirmedIndex(index: number | undefined, labelOverride?: string): void {
61
+ this.select.setConfirmedIndex(index, labelOverride);
62
+ }
63
+
64
+ setInputBuffer(text: string): void {
65
+ this.select.setInputBuffer(text);
66
+ }
67
+
68
+ getInputBuffer(): string {
69
+ return this.select.getInputBuffer();
70
+ }
71
+
72
+ appendInput(text: string): void {
73
+ this.select.appendInput(text);
74
+ }
75
+
76
+ backspaceInput(): void {
77
+ this.select.backspaceInput();
78
+ }
79
+
80
+ clearInputBuffer(): void {
81
+ this.select.clearInputBuffer();
82
+ }
83
+
84
+ handleInput(_data: string): void {}
85
+
86
+ invalidate(): void {
87
+ this.select.invalidate();
88
+ }
89
+
90
+ render(width: number): string[] {
91
+ return this.select.render(width);
92
+ }
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Pi extension: lets the model ask you a clarifying question with structured options instead of guessing",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -26,6 +26,7 @@
26
26
  "test": "vitest run"
27
27
  },
28
28
  "files": [
29
+ "apply-action.ts",
29
30
  "ask-user-question.ts",
30
31
  "body-residual-spacer.ts",
31
32
  "dialog-builder.ts",
@@ -35,6 +36,8 @@
35
36
  "LICENSE",
36
37
  "markdown-content-cache.ts",
37
38
  "multi-select-options.ts",
39
+ "option-list-view.ts",
40
+ "preview-block-renderer.ts",
38
41
  "preview-box-renderer.ts",
39
42
  "preview-layout-decider.ts",
40
43
  "preview-pane.ts",
@@ -48,6 +51,7 @@
48
51
  "tab-strategy.ts",
49
52
  "types.ts",
50
53
  "validate-questionnaire.ts",
54
+ "view-adapter.ts",
51
55
  "wrapping-select.ts"
52
56
  ],
53
57
  "pi": {