@juicesharp/rpiv-ask-user-question 1.0.4 → 1.0.6

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 (41) hide show
  1. package/ask-user-question.ts +10 -17
  2. package/index.ts +2 -7
  3. package/package.json +32 -24
  4. package/state/build-questionnaire.ts +147 -0
  5. package/state/input-buffer.ts +31 -0
  6. package/{dispatch.ts → state/key-router.ts} +66 -64
  7. package/state/questionnaire-session.ts +192 -0
  8. package/state/row-intent.ts +159 -0
  9. package/state/selectors/derivations.ts +91 -0
  10. package/state/selectors/focus.ts +19 -0
  11. package/state/selectors/projections.ts +143 -0
  12. package/{apply-action.ts → state/state-reducer.ts} +21 -34
  13. package/state/state.ts +39 -0
  14. package/{types.ts → tool/types.ts} +17 -16
  15. package/{validate-questionnaire.ts → tool/validate-questionnaire.ts} +3 -5
  16. package/view/components/chat-row-view.ts +58 -0
  17. package/{multi-select-options.ts → view/components/multi-select-view.ts} +32 -37
  18. package/view/components/option-list-view.ts +64 -0
  19. package/{markdown-content-cache.ts → view/components/preview/markdown-content-cache.ts} +1 -1
  20. package/{preview-block-renderer.ts → view/components/preview/preview-block-renderer.ts} +1 -1
  21. package/{preview-pane.ts → view/components/preview/preview-pane.ts} +40 -23
  22. package/{submit-picker.ts → view/components/submit-picker.ts} +19 -15
  23. package/view/components/tab-bar.ts +60 -0
  24. package/{wrapping-select.ts → view/components/wrapping-select.ts} +5 -4
  25. package/view/dialog-builder.ts +128 -0
  26. package/view/props-adapter.ts +102 -0
  27. package/view/stateful-view.ts +25 -0
  28. package/view/tab-components.ts +10 -0
  29. package/{tab-strategy.ts → view/tab-content-strategy.ts} +25 -40
  30. package/dialog-builder.ts +0 -153
  31. package/option-list-view.ts +0 -93
  32. package/questionnaire-session.ts +0 -293
  33. package/questionnaire-state.ts +0 -161
  34. package/stateful-component.ts +0 -14
  35. package/tab-bar.ts +0 -61
  36. package/view-adapter.ts +0 -133
  37. /package/{format-answer.ts → tool/format-answer.ts} +0 -0
  38. /package/{response-envelope.ts → tool/response-envelope.ts} +0 -0
  39. /package/{body-residual-spacer.ts → view/body-residual-spacer.ts} +0 -0
  40. /package/{preview-box-renderer.ts → view/components/preview/preview-box-renderer.ts} +0 -0
  41. /package/{preview-layout-decider.ts → view/components/preview/preview-layout-decider.ts} +0 -0
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
- import { QuestionnaireSession } from "./questionnaire-session.js";
3
- import { buildQuestionnaireResponse, buildToolResult } from "./response-envelope.js";
2
+ import { QuestionnaireSession } from "./state/questionnaire-session.js";
3
+ import { ROW_INTENT_META, sentinelsToAppend } from "./state/row-intent.js";
4
+ import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
4
5
  import {
5
6
  MAX_OPTIONS,
6
7
  MAX_QUESTIONS,
@@ -9,31 +10,23 @@ import {
9
10
  type QuestionnaireResult,
10
11
  type QuestionParams,
11
12
  QuestionParamsSchema,
12
- SENTINEL_LABELS,
13
- } from "./types.js";
14
- import { validateQuestionnaire } from "./validate-questionnaire.js";
15
- import type { WrappingSelectItem } from "./wrapping-select.js";
13
+ } from "./tool/types.js";
14
+ import { validateQuestionnaire } from "./tool/validate-questionnaire.js";
15
+ import type { WrappingSelectItem } from "./view/components/wrapping-select.js";
16
16
 
17
17
  const ERROR_NO_UI = "Error: UI not available (running in non-interactive mode)";
18
18
 
19
- export { chatNumberingFor } from "./questionnaire-state.js";
20
-
21
19
  export function buildItemsForQuestion(question: QuestionData): WrappingSelectItem[] {
22
20
  const items: WrappingSelectItem[] = question.options.map((o) => ({
23
21
  kind: "option",
24
22
  label: o.label,
25
23
  description: o.description,
26
24
  }));
27
- // Multi-select gets a "Next" sentinel row at the bottom so `Enter` on regular option rows
28
- // can be repurposed as a per-row toggle (matching `Space`); committing + advancing to the
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 }];
31
- // Side-by-side preview layout pins the options column to PREVIEW_LEFT_COLUMN_MAX_WIDTH (~40
32
- // cols), which truncates inline custom-text input. CC suppresses the row in this layout for
33
- // the same reason — the "Chat about this" row remains as the free-form escape hatch.
34
25
  const hasAnyPreview = question.options.some((o) => typeof o.preview === "string" && o.preview.length > 0);
35
- if (hasAnyPreview) return items;
36
- return [...items, { kind: "other", label: SENTINEL_LABELS.other }];
26
+ for (const kind of sentinelsToAppend(question, hasAnyPreview)) {
27
+ items.push({ kind, label: ROW_INTENT_META[kind].label });
28
+ }
29
+ return items;
37
30
  }
38
31
 
39
32
  export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
package/index.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  /**
2
- * rpiv-ask-user-question — Pi extension
3
- *
4
- * Registers the `ask_user_question` tool, which surfaces a structured
5
- * option selector (plus free-text "Other" fallback) to disambiguate
6
- * underspecified user requests.
7
- *
8
- * Extracted from rpiv-pi@7525a5d. Tool name preserved verbatim.
2
+ * rpiv-ask-user-question — Pi extension. Registers the `ask_user_question`
3
+ * tool: a structured option selector with a free-text "Other" fallback.
9
4
  */
10
5
 
11
6
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
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,33 +26,41 @@
26
26
  "test": "vitest run"
27
27
  },
28
28
  "files": [
29
- "apply-action.ts",
30
29
  "ask-user-question.ts",
31
- "body-residual-spacer.ts",
32
- "dialog-builder.ts",
33
- "dispatch.ts",
34
- "format-answer.ts",
35
30
  "index.ts",
36
31
  "LICENSE",
37
- "markdown-content-cache.ts",
38
- "multi-select-options.ts",
39
- "option-list-view.ts",
40
- "preview-block-renderer.ts",
41
- "preview-box-renderer.ts",
42
- "preview-layout-decider.ts",
43
- "preview-pane.ts",
44
- "questionnaire-session.ts",
45
- "questionnaire-state.ts",
46
32
  "README.md",
47
- "response-envelope.ts",
48
- "stateful-component.ts",
49
- "submit-picker.ts",
50
- "tab-bar.ts",
51
- "tab-strategy.ts",
52
- "types.ts",
53
- "validate-questionnaire.ts",
54
- "view-adapter.ts",
55
- "wrapping-select.ts"
33
+ "state/build-questionnaire.ts",
34
+ "state/input-buffer.ts",
35
+ "state/key-router.ts",
36
+ "state/questionnaire-session.ts",
37
+ "state/row-intent.ts",
38
+ "state/selectors/derivations.ts",
39
+ "state/selectors/focus.ts",
40
+ "state/selectors/projections.ts",
41
+ "state/state-reducer.ts",
42
+ "state/state.ts",
43
+ "tool/format-answer.ts",
44
+ "tool/response-envelope.ts",
45
+ "tool/types.ts",
46
+ "tool/validate-questionnaire.ts",
47
+ "view/body-residual-spacer.ts",
48
+ "view/components/chat-row-view.ts",
49
+ "view/components/multi-select-view.ts",
50
+ "view/components/option-list-view.ts",
51
+ "view/components/preview/markdown-content-cache.ts",
52
+ "view/components/preview/preview-block-renderer.ts",
53
+ "view/components/preview/preview-box-renderer.ts",
54
+ "view/components/preview/preview-layout-decider.ts",
55
+ "view/components/preview/preview-pane.ts",
56
+ "view/components/submit-picker.ts",
57
+ "view/components/tab-bar.ts",
58
+ "view/components/wrapping-select.ts",
59
+ "view/dialog-builder.ts",
60
+ "view/props-adapter.ts",
61
+ "view/stateful-view.ts",
62
+ "view/tab-components.ts",
63
+ "view/tab-content-strategy.ts"
56
64
  ],
57
65
  "pi": {
58
66
  "extensions": [
@@ -0,0 +1,147 @@
1
+ import { getMarkdownTheme, type Theme } from "@mariozechner/pi-coding-agent";
2
+ import { Input } from "@mariozechner/pi-tui";
3
+ import { type QuestionData, SENTINEL_LABELS } from "../tool/types.js";
4
+ import { ChatRowView } from "../view/components/chat-row-view.js";
5
+ import { MultiSelectView } from "../view/components/multi-select-view.js";
6
+ import { OptionListView } from "../view/components/option-list-view.js";
7
+ import { PreviewBlockRenderer } from "../view/components/preview/preview-block-renderer.js";
8
+ import { PreviewPane } from "../view/components/preview/preview-pane.js";
9
+ import { SubmitPicker } from "../view/components/submit-picker.js";
10
+ import { TabBar } from "../view/components/tab-bar.js";
11
+ import type { WrappingSelectItem, WrappingSelectTheme } from "../view/components/wrapping-select.js";
12
+ import { buildDialog } from "../view/dialog-builder.js";
13
+ import { QuestionnairePropsAdapter } from "../view/props-adapter.js";
14
+ import type { TabComponents } from "../view/tab-components.js";
15
+ import type { InputBuffer } from "./input-buffer.js";
16
+ import { chatNumberingFor, selectActivePreviewPaneIndex } from "./selectors/derivations.js";
17
+ import { selectActiveView } from "./selectors/focus.js";
18
+ import { selectMultiSelectProps, selectSubmitPickerProps, selectTabBarProps } from "./selectors/projections.js";
19
+ import type { QuestionnaireState } from "./state.js";
20
+
21
+ export interface QuestionnaireBuildConfig {
22
+ tui: { terminal: { columns: number }; requestRender(): void };
23
+ theme: Theme;
24
+ questions: readonly QuestionData[];
25
+ itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
26
+ isMulti: boolean;
27
+ initialState: QuestionnaireState;
28
+ inputBuffer: InputBuffer;
29
+ getCurrentTab: () => number;
30
+ }
31
+
32
+ export interface QuestionnaireBuilt {
33
+ adapter: QuestionnairePropsAdapter;
34
+ notesInput: Input;
35
+ render: (width: number) => string[];
36
+ invalidate: () => void;
37
+ }
38
+
39
+ /**
40
+ * Pure factory: assembles every TUI component, the props adapter, and a
41
+ * lifecycle handle. Session-state dependencies arrive via `getCurrentTab` and
42
+ * the `inputBuffer` cell.
43
+ */
44
+ export function buildQuestionnaire(config: QuestionnaireBuildConfig): QuestionnaireBuilt {
45
+ const { tui, theme, questions, itemsByTab, isMulti, initialState, inputBuffer, getCurrentTab } = config;
46
+ const totalQuestions = questions.length;
47
+
48
+ const selectTheme: WrappingSelectTheme = {
49
+ selectedText: (t) => theme.fg("accent", theme.bold(t)),
50
+ description: (t) => theme.fg("muted", t),
51
+ scrollInfo: (t) => theme.fg("dim", t),
52
+ };
53
+
54
+ const chatRow = new ChatRowView({
55
+ item: { kind: "chat", label: SENTINEL_LABELS.chat },
56
+ theme: selectTheme,
57
+ initialProps: {
58
+ focused: false,
59
+ numbering: chatNumberingFor(itemsByTab[0] ?? []),
60
+ },
61
+ });
62
+ const notesInput = new Input();
63
+
64
+ const markdownTheme = getMarkdownTheme();
65
+ const getTerminalWidth = () => tui.terminal.columns;
66
+ const initialActiveView = selectActiveView(initialState, totalQuestions);
67
+
68
+ const tabsByIndex: ReadonlyArray<TabComponents> = questions.map((q, i) => {
69
+ const optionList = new OptionListView({ items: itemsByTab[i] ?? [], theme: selectTheme });
70
+ const previewBlock = new PreviewBlockRenderer({ question: q, theme, markdownTheme });
71
+ const preview = new PreviewPane({
72
+ question: q,
73
+ getTerminalWidth,
74
+ optionListView: optionList,
75
+ previewBlock,
76
+ initialProps: { notesVisible: false, selectedIndex: 0, focused: false },
77
+ });
78
+ const multiSelect = q.multiSelect
79
+ ? new MultiSelectView(theme, q, selectMultiSelectProps(initialState, q, initialActiveView))
80
+ : undefined;
81
+ return { optionList, preview, multiSelect };
82
+ });
83
+
84
+ const submitPicker = isMulti
85
+ ? new SubmitPicker(theme, selectSubmitPickerProps(initialState, totalQuestions, initialActiveView))
86
+ : undefined;
87
+ const tabBar = isMulti ? new TabBar(selectTabBarProps(initialState, questions), theme) : undefined;
88
+
89
+ const computeGlobalContentHeight = (width: number): number => {
90
+ let max = 0;
91
+ for (let i = 0; i < questions.length; i++) {
92
+ const q = questions[i];
93
+ const tab = tabsByIndex[i];
94
+ const h = q?.multiSelect
95
+ ? (tab?.multiSelect?.naturalHeight(width) ?? 0)
96
+ : (tab?.preview.maxNaturalHeight(width) ?? 0);
97
+ if (h > max) max = h;
98
+ }
99
+ return Math.max(1, max);
100
+ };
101
+ const computeCurrentContentHeight = (width: number): number => {
102
+ const idx = Math.min(getCurrentTab(), questions.length - 1);
103
+ const q = questions[idx];
104
+ const tab = tabsByIndex[idx];
105
+ if (!q || !tab) return 0;
106
+ const h = q.multiSelect ? (tab.multiSelect?.naturalHeight(width) ?? 0) : tab.preview.naturalHeight(width);
107
+ return Math.max(0, h);
108
+ };
109
+
110
+ const dialog = buildDialog({
111
+ theme,
112
+ questions,
113
+ initialProps: {
114
+ state: initialState,
115
+ activePreviewPane:
116
+ tabsByIndex[selectActivePreviewPaneIndex(initialState.currentTab, totalQuestions)]?.preview ??
117
+ tabsByIndex[0]!.preview,
118
+ },
119
+ tabBar,
120
+ notesInput,
121
+ chatRow,
122
+ isMulti,
123
+ tabsByIndex,
124
+ submitPicker,
125
+ getBodyHeight: computeGlobalContentHeight,
126
+ getCurrentBodyHeight: computeCurrentContentHeight,
127
+ });
128
+
129
+ const adapter = new QuestionnairePropsAdapter({
130
+ tui,
131
+ questions,
132
+ itemsByTab,
133
+ tabsByIndex,
134
+ chatRow,
135
+ submitPicker,
136
+ tabBar,
137
+ dialog,
138
+ inputBuffer,
139
+ });
140
+
141
+ return {
142
+ adapter,
143
+ notesInput,
144
+ render: (w) => dialog.render(w),
145
+ invalidate: () => dialog.invalidate(),
146
+ };
147
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Session-owned input-buffer cell. Mutable by design — the reducer never
3
+ * touches it. Mutation paths: effect handlers (`set_input_buffer`,
4
+ * `clear_input_buffer`) and the inline-key fast path (`handleIgnoreInline`
5
+ * for printable keys + backspace). The value flows to the view per tick via
6
+ * `runtime.inputBuffer` → `selectOptionListProps` → OptionListView.
7
+ */
8
+ export class InputBuffer {
9
+ private value = "";
10
+
11
+ get(): string {
12
+ return this.value;
13
+ }
14
+
15
+ set(value: string): void {
16
+ this.value = value;
17
+ }
18
+
19
+ clear(): void {
20
+ this.value = "";
21
+ }
22
+
23
+ append(chunk: string): void {
24
+ this.value = this.value + chunk;
25
+ }
26
+
27
+ backspace(): void {
28
+ if (this.value.length === 0) return;
29
+ this.value = this.value.slice(0, -1);
30
+ }
31
+ }
@@ -1,6 +1,7 @@
1
1
  import { Key, matchesKey } from "@mariozechner/pi-tui";
2
- import type { QuestionnaireDispatchSnapshot } from "./questionnaire-state.js";
3
- import type { QuestionAnswer } from "./types.js";
2
+ import type { QuestionAnswer } from "../tool/types.js";
3
+ import { ROW_INTENT_META } from "./row-intent.js";
4
+ import type { QuestionnaireRuntime, QuestionnaireState } from "./state.js";
4
5
 
5
6
  const KEYBIND_UP = "tui.select.up";
6
7
  const KEYBIND_DOWN = "tui.select.down";
@@ -23,12 +24,10 @@ export type QuestionnaireAction =
23
24
  | { kind: "submit_nav"; nextIndex: 0 | 1 }
24
25
  | { kind: "focus_chat" }
25
26
  /**
26
- * Optional `optionIndex` lets the dispatcher tell the host where to land when leaving the
27
- * chat row, so UP/DOWN form a continuous cycle through `[chat, option0, …, optionLast]`
28
- * (Defect 2). When omitted, the host preserves the existing optionIndex (UP-from-chat
29
- * legacy behavior — currently still emitted by some branches and consumers).
27
+ * Carries the target index so UP/DOWN form a continuous cycle through
28
+ * `[chat, option0, …, optionLast]`.
30
29
  */
31
- | { kind: "focus_options"; optionIndex?: number }
30
+ | { kind: "focus_options"; optionIndex: number }
32
31
  | { kind: "ignore" };
33
32
 
34
33
  export interface QuestionnaireKeybindings {
@@ -40,32 +39,32 @@ export function wrapTab(index: number, total: number): number {
40
39
  return ((index % total) + total) % total;
41
40
  }
42
41
 
43
- export function allAnswered(state: QuestionnaireDispatchSnapshot): boolean {
44
- if (state.questions.length === 0) return false;
45
- for (let i = 0; i < state.questions.length; i++) {
42
+ export function allAnswered(state: QuestionnaireState, runtime: QuestionnaireRuntime): boolean {
43
+ if (runtime.questions.length === 0) return false;
44
+ for (let i = 0; i < runtime.questions.length; i++) {
46
45
  if (!state.answers.has(i)) return false;
47
46
  }
48
47
  return true;
49
48
  }
50
49
 
51
- function totalTabs(state: QuestionnaireDispatchSnapshot): number {
52
- return state.isMulti ? state.questions.length + 1 : 1;
50
+ function totalTabs(runtime: QuestionnaireRuntime): number {
51
+ return runtime.isMulti ? runtime.questions.length + 1 : 1;
53
52
  }
54
53
 
55
- function computeAutoAdvanceTab(state: QuestionnaireDispatchSnapshot): number | undefined {
56
- if (!state.isMulti) return undefined;
57
- if (state.currentTab < state.questions.length - 1) return state.currentTab + 1;
58
- return state.questions.length;
54
+ function computeAutoAdvanceTab(state: QuestionnaireState, runtime: QuestionnaireRuntime): number | undefined {
55
+ if (!runtime.isMulti) return undefined;
56
+ if (state.currentTab < runtime.questions.length - 1) return state.currentTab + 1;
57
+ return runtime.questions.length;
59
58
  }
60
59
 
61
- function buildSingleSelectAnswer(state: QuestionnaireDispatchSnapshot): QuestionAnswer | null {
62
- const q = state.questions[state.currentTab];
60
+ function buildSingleSelectAnswer(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionAnswer | null {
61
+ const q = runtime.questions[state.currentTab];
63
62
  if (!q) return null;
64
63
 
65
64
  // Chat sentinel takes priority over inputMode: when chatFocused=true, the host overrides
66
65
  // currentItem() to return the chat sentinel even if inputMode is still true (e.g. user
67
66
  // navigated from "Type something." and DOWN focused the chat row).
68
- const item = state.currentItem;
67
+ const item = runtime.currentItem;
69
68
  if (item?.kind === "chat") {
70
69
  return {
71
70
  questionIndex: state.currentTab,
@@ -76,7 +75,7 @@ function buildSingleSelectAnswer(state: QuestionnaireDispatchSnapshot): Question
76
75
  }
77
76
 
78
77
  if (state.inputMode) {
79
- const label = state.inputBuffer;
78
+ const label = runtime.inputBuffer;
80
79
  return {
81
80
  questionIndex: state.currentTab,
82
81
  question: q.question,
@@ -99,8 +98,8 @@ function buildSingleSelectAnswer(state: QuestionnaireDispatchSnapshot): Question
99
98
  };
100
99
  }
101
100
 
102
- function buildMultiSelected(state: QuestionnaireDispatchSnapshot): string[] {
103
- const q = state.questions[state.currentTab];
101
+ function buildMultiSelected(state: QuestionnaireState, runtime: QuestionnaireRuntime): string[] {
102
+ const q = runtime.questions[state.currentTab];
104
103
  if (!q) return [];
105
104
  const out: string[] = [];
106
105
  for (let i = 0; i < q.options.length; i++) {
@@ -112,9 +111,13 @@ function buildMultiSelected(state: QuestionnaireDispatchSnapshot): string[] {
112
111
  return out;
113
112
  }
114
113
 
115
- function tabSwitchAction(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction | null {
116
- if (!state.isMulti) return null;
117
- const total = totalTabs(state);
114
+ function tabSwitchAction(
115
+ data: string,
116
+ state: QuestionnaireState,
117
+ runtime: QuestionnaireRuntime,
118
+ ): QuestionnaireAction | null {
119
+ if (!runtime.isMulti) return null;
120
+ const total = totalTabs(runtime);
118
121
  if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
119
122
  return { kind: "tab_switch", nextTab: wrapTab(state.currentTab + 1, total) };
120
123
  }
@@ -124,28 +127,24 @@ function tabSwitchAction(data: string, state: QuestionnaireDispatchSnapshot): Qu
124
127
  return null;
125
128
  }
126
129
 
127
- // DOWN navigation helper shared by inputMode and normal nav branches.
128
- // Emits focus_chat at the boundary (last item) so the host can transfer focus to the chat row
129
- // without mutating optionIndex — UP-from-chat then lands on items.length - 1 (continuous cycle).
130
- function nextNavOnDown(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
131
- if (state.items.length > 0 && state.optionIndex === state.items.length - 1) {
130
+ // DOWN at the last item emits focus_chat so the cycle [chat, option0, …, optionLast] wraps.
131
+ function nextNavOnDown(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
132
+ if (runtime.items.length > 0 && state.optionIndex === runtime.items.length - 1) {
132
133
  return { kind: "focus_chat" };
133
134
  }
134
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, state.items.length)) };
135
+ return { kind: "nav", nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)) };
135
136
  }
136
137
 
137
- // UP navigation helper, symmetric with nextNavOnDown. At the TOP boundary (optionIndex 0)
138
- // emits focus_chat so the cycle wraps `[chat, option0, …, optionLast]` — without this, UP at
139
- // option 0 would skip the chat row entirely (Defect 2). Above the boundary, decrement.
140
- function prevNavOnUp(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
141
- if (state.items.length > 0 && state.optionIndex === 0) {
138
+ // UP at the top item emits focus_chat (symmetric with nextNavOnDown).
139
+ function prevNavOnUp(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
140
+ if (runtime.items.length > 0 && state.optionIndex === 0) {
142
141
  return { kind: "focus_chat" };
143
142
  }
144
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, state.items.length)) };
143
+ return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)) };
145
144
  }
146
145
 
147
- export function handleQuestionnaireInput(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
148
- const kb = state.keybindings;
146
+ export function routeKey(data: string, state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
147
+ const kb = runtime.keybindings;
149
148
 
150
149
  if (state.notesVisible) {
151
150
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "notes_exit" };
@@ -156,45 +155,45 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
156
155
  if (state.chatFocused) {
157
156
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
158
157
  if (kb.matches(data, KEYBIND_CONFIRM)) {
159
- const answer = buildSingleSelectAnswer(state);
158
+ const answer = buildSingleSelectAnswer(state, runtime);
160
159
  if (!answer) return { kind: "ignore" };
161
- return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state) };
160
+ return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
162
161
  }
163
162
  // Continuous cycle: UP from chat → bottom of options (last navigable row), DOWN from
164
163
  // chat → top of options (option 0). Symmetric with UP-at-top → focus_chat and
165
164
  // DOWN-at-bottom → focus_chat below; together they form one wrapping cycle through
166
165
  // `[chat, option0, …, optionLast]`.
167
166
  if (kb.matches(data, KEYBIND_UP)) {
168
- const last = Math.max(0, state.items.length - 1);
167
+ const last = Math.max(0, runtime.items.length - 1);
169
168
  return { kind: "focus_options", optionIndex: last };
170
169
  }
171
170
  if (kb.matches(data, KEYBIND_DOWN)) {
172
171
  return { kind: "focus_options", optionIndex: 0 };
173
172
  }
174
- const tab = tabSwitchAction(data, state);
173
+ const tab = tabSwitchAction(data, state, runtime);
175
174
  if (tab) return tab;
176
175
  return { kind: "ignore" };
177
176
  }
178
177
 
179
178
  if (state.inputMode) {
180
179
  if (kb.matches(data, KEYBIND_CONFIRM)) {
181
- const answer = buildSingleSelectAnswer(state);
180
+ const answer = buildSingleSelectAnswer(state, runtime);
182
181
  if (!answer) return { kind: "ignore" };
183
- return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state) };
182
+ return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
184
183
  }
185
184
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
186
185
  if (kb.matches(data, KEYBIND_UP)) {
187
- return prevNavOnUp(state);
186
+ return prevNavOnUp(state, runtime);
188
187
  }
189
188
  if (kb.matches(data, KEYBIND_DOWN)) {
190
- return nextNavOnDown(state);
189
+ return nextNavOnDown(state, runtime);
191
190
  }
192
191
  return { kind: "ignore" };
193
192
  }
194
193
 
195
- if (state.isMulti && state.currentTab === state.questions.length) {
194
+ if (runtime.isMulti && state.currentTab === runtime.questions.length) {
196
195
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
197
- const tab = tabSwitchAction(data, state);
196
+ const tab = tabSwitchAction(data, state, runtime);
198
197
  if (tab) return tab;
199
198
  if (kb.matches(data, KEYBIND_UP) || kb.matches(data, KEYBIND_DOWN)) {
200
199
  const delta = kb.matches(data, KEYBIND_DOWN) ? 1 : -1;
@@ -210,10 +209,10 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
210
209
  return { kind: "ignore" };
211
210
  }
212
211
 
213
- const tab = tabSwitchAction(data, state);
212
+ const tab = tabSwitchAction(data, state, runtime);
214
213
  if (tab) return tab;
215
214
 
216
- const q = state.questions[state.currentTab];
215
+ const q = runtime.questions[state.currentTab];
217
216
  if (!q) return { kind: "ignore" };
218
217
 
219
218
  if (data === NOTES_ACTIVATE_KEY && !q.multiSelect && state.focusedOptionHasPreview) {
@@ -221,33 +220,36 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
221
220
  }
222
221
 
223
222
  if (kb.matches(data, KEYBIND_UP)) {
224
- return prevNavOnUp(state);
223
+ return prevNavOnUp(state, runtime);
225
224
  }
226
225
  if (kb.matches(data, KEYBIND_DOWN)) {
227
- return nextNavOnDown(state);
226
+ return nextNavOnDown(state, runtime);
228
227
  }
229
228
 
230
229
  if (q.multiSelect) {
231
- const onNext = state.currentItem?.kind === "next";
232
- // Space toggles the focused row's checkbox. Ignored on the Next sentinel — Next is
233
- // not a real option and has no checked/unchecked state.
230
+ const focusedKind = runtime.currentItem?.kind;
231
+ const focusedMeta = focusedKind ? ROW_INTENT_META[focusedKind] : undefined;
232
+ // Space toggles the focused row's checkbox. Suppressed on rows whose META declares
233
+ // `blocksMultiToggle` (the Next sentinel) — Next is not a real option and has no
234
+ // checked/unchecked state.
234
235
  if (data === SPACE_KEY) {
235
- if (onNext) return { kind: "ignore" };
236
+ if (focusedMeta?.blocksMultiToggle) return { kind: "ignore" };
236
237
  return { kind: "toggle", index: state.optionIndex };
237
238
  }
238
239
  if (kb.matches(data, KEYBIND_CONFIRM)) {
239
240
  // Enter on a regular row toggles (matching Space) — committing the question is now
240
- // gated behind explicit focus on the Next row, so Enter on options is a no-cost
241
- // way to flip checkboxes without leaving the keyboard home row.
242
- if (!onNext) return { kind: "toggle", index: state.optionIndex };
241
+ // gated behind explicit focus on a row whose META declares `autoSubmitsInMulti`
242
+ // (the Next sentinel), so Enter on options is a no-cost way to flip checkboxes
243
+ // without leaving the keyboard home row.
244
+ if (!focusedMeta?.autoSubmitsInMulti) return { kind: "toggle", index: state.optionIndex };
243
245
  // Enter on Next: carry autoAdvanceTab so the host can advance to the next tab in
244
246
  // multi-question mode, OR submit the dialog in single-question mode
245
247
  // (autoAdvanceTab === undefined when !isMulti). Without this, a single multi-select
246
248
  // question would have no way to commit at all.
247
249
  return {
248
250
  kind: "multi_confirm",
249
- selected: buildMultiSelected(state),
250
- autoAdvanceTab: computeAutoAdvanceTab(state),
251
+ selected: buildMultiSelected(state, runtime),
252
+ autoAdvanceTab: computeAutoAdvanceTab(state, runtime),
251
253
  };
252
254
  }
253
255
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
@@ -255,9 +257,9 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
255
257
  }
256
258
 
257
259
  if (kb.matches(data, KEYBIND_CONFIRM)) {
258
- const answer = buildSingleSelectAnswer(state);
260
+ const answer = buildSingleSelectAnswer(state, runtime);
259
261
  if (!answer) return { kind: "ignore" };
260
- return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state) };
262
+ return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
261
263
  }
262
264
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
263
265
  return { kind: "ignore" };