@juicesharp/rpiv-ask-user-question 1.19.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/reconcile.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * reconcile — mid-session lifecycle reconciliation for ask_user_question.
3
+ *
4
+ * Strips or re-adds the tool to the active set so it is invisible to the LLM
5
+ * in non-interactive runs (no UI) and present in interactive ones. Mirrors the
6
+ * advisor's reconcileAdvisorTool / registerAdvisorBeforeAgentStart pattern
7
+ * (packages/rpiv-advisor/advisor/handlers.ts), simplified: ask_user_question's
8
+ * only gating signal is ctx.hasUI (no model or executor blocklist), so it
9
+ * reads the flag directly and omits the notify.
10
+ *
11
+ * RPC hosts (ctx.mode === "rpc": VSCode pendant, Zed, Paseo) are deliberately
12
+ * NOT stripped: since PR #100 the tool renders there via the select/input
13
+ * dialog walker (rpc-fallback.ts), so hasUI is the honest signal again. The
14
+ * brief period where RPC was stripped (872ef1c) predates that fallback.
15
+ */
16
+
17
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
+ import { ASK_USER_QUESTION_TOOL_NAME } from "./ask-user-question.js";
19
+
20
+ /**
21
+ * Strip-or-restore `ask_user_question` to match `ctx.hasUI`. Reads the active
22
+ * tool list itself. Idempotent: when the tool is already in the right state it
23
+ * leaves the active set (and sibling tools) untouched.
24
+ */
25
+ export function reconcileAskUserQuestionTool(pi: ExtensionAPI, ctx: ExtensionContext): void {
26
+ const active = pi.getActiveTools();
27
+ const hasTool = active.includes(ASK_USER_QUESTION_TOOL_NAME);
28
+ // !hasUI → strip so the tool never reaches the LLM's tool list in
29
+ // non-interactive runs; hasUI → restore. The in-handler guards in
30
+ // ask-user-question.ts (!hasUI, and the custom()-undefined → dialog-walker /
31
+ // no_custom_ui backstop) remain as one-turn backstops if a future Pi change
32
+ // reorders the tool-list snapshot ahead of before_agent_start, or a host
33
+ // reports hasUI without any usable rendering primitive.
34
+ if (!ctx.hasUI && hasTool) {
35
+ pi.setActiveTools(active.filter((n) => n !== ASK_USER_QUESTION_TOOL_NAME));
36
+ } else if (ctx.hasUI && !hasTool) {
37
+ pi.setActiveTools([...active, ASK_USER_QUESTION_TOOL_NAME]);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Attach the reconciler to `before_agent_start` so the active set is fixed up
43
+ * before each turn's tool-list snapshot is read. Safe to call once at load.
44
+ */
45
+ export function registerAskUserQuestionReconciler(pi: ExtensionAPI): void {
46
+ pi.on("before_agent_start", (_event, ctx) => reconcileAskUserQuestionTool(pi, ctx));
47
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * RPC / dialog-primitive fallback for `ask_user_question`.
3
+ *
4
+ * The canonical TUI path (`ctx.ui.custom()`) renders a tabbed overlay that
5
+ * needs a real terminal. RPC-mode hosts (the VSCode pendant, ACP clients such
6
+ * as Zed or Paseo) report `hasUI: true` because pi's dialog sub-protocol
7
+ * (`extension_ui_request`/`extension_ui_response`) works, but `ui.custom()`
8
+ * resolves `undefined` without rendering anything (issue #78). `ui.select()`
9
+ * and `ui.input()` ARE functional there — the host renders them natively — so
10
+ * this module walks the questions sequentially with those primitives and
11
+ * returns the same `QuestionnaireResult` shapes the TUI produces, feeding the
12
+ * shared `buildQuestionnaireResponse` envelope.
13
+ *
14
+ * Parity trade-offs vs the TUI, inherent to the select/input API surface: no
15
+ * side-by-side preview pane (previews are folded into the prompt title), no
16
+ * tabbed multi-question review (one dialog per question), and multi-select is
17
+ * a free-text numbers input instead of checkbox rows. The "Type something."
18
+ * escape is preserved on both variants — multi-select treats any non-index
19
+ * input as a typed custom answer — matching
20
+ * `ROW_INTENT_META.other.autoAppendOnMultiSelect`.
21
+ */
22
+
23
+ import { displayLabel, t } from "./state/i18n-bridge.js";
24
+ import type { QuestionAnswer, QuestionData, QuestionnaireResult, QuestionParams } from "./tool/types.js";
25
+
26
+ /**
27
+ * Canonical-English fallbacks; resolved through `t()` at dialog time so the
28
+ * live locale applies (top-level `const x = t(...)` would bake load-time
29
+ * English in — see i18n-bridge.ts). The sentinel row label comes from
30
+ * `displayLabel("other")` — same source as the TUI row.
31
+ */
32
+ const MULTI_SELECT_INSTRUCTIONS =
33
+ 'Enter the numbers of all that apply, comma-separated (e.g. "1,3"), or type a custom answer as plain text.';
34
+ const CUSTOM_ANSWER_TITLE = "Type your answer:";
35
+ const MULTI_SELECT_PLACEHOLDER = "1,3";
36
+
37
+ /** Longest preview slice folded into a select title before truncation. */
38
+ const MAX_PREVIEW_CHARS = 600;
39
+
40
+ /**
41
+ * The dialog-primitive slice of `ExtensionUIContext` this walker needs.
42
+ * Structural on purpose: the pinned pi 0.74 peer types predate `ctx.mode`,
43
+ * and jiti transpiles without type-checking — `hasDialogUI` is the runtime
44
+ * gate that makes the shape trustworthy.
45
+ */
46
+ export type DialogUI = {
47
+ select: (title: string, options: string[]) => Promise<string | undefined>;
48
+ input: (title: string, placeholder?: string) => Promise<string | undefined>;
49
+ };
50
+
51
+ /** True when the host implements the select/input dialog primitives. */
52
+ export function hasDialogUI(ui: unknown): ui is DialogUI {
53
+ const u = ui as Partial<Record<"select" | "input", unknown>> | null | undefined;
54
+ return typeof u?.select === "function" && typeof u?.input === "function";
55
+ }
56
+
57
+ type Option = QuestionData["options"][number];
58
+
59
+ function formatOptionLine(option: Option, index: number): string {
60
+ return `${index + 1}. ${option.label} — ${option.description}`;
61
+ }
62
+
63
+ /**
64
+ * Parse a user-entered (or select-returned) "N…" token to a 0-based option
65
+ * index. `parseInt` reads the leading digits of "2. B — b" as 2; NaN and
66
+ * out-of-range fail the bounds check and return null.
67
+ */
68
+ function parseIndex(token: string, count: number): number | null {
69
+ const i = Number.parseInt(token, 10) - 1;
70
+ return i >= 0 && i < count ? i : null;
71
+ }
72
+
73
+ /** Previews folded into the select title — RPC has no side-by-side pane. */
74
+ function buildPreviewBlock(question: QuestionData): string {
75
+ const blocks = question.options.flatMap((o, i) =>
76
+ o.preview && o.preview.length > 0
77
+ ? [`--- ${i + 1}. ${o.label} preview ---\n${o.preview.slice(0, MAX_PREVIEW_CHARS)}`]
78
+ : [],
79
+ );
80
+ return blocks.length > 0 ? `\n\n${blocks.join("\n\n")}` : "";
81
+ }
82
+
83
+ /**
84
+ * Walk the questionnaire one native dialog at a time. Dismissing any dialog
85
+ * (the primitive resolves `undefined`) cancels the whole questionnaire —
86
+ * mirroring Esc in the TUI — and the shared envelope emits DECLINE. A
87
+ * `QuestionAnswer` is produced per question otherwise, so the envelope is
88
+ * identical to the TUI path's.
89
+ */
90
+ export async function runRpcQuestionnaire(ui: DialogUI, params: QuestionParams): Promise<QuestionnaireResult> {
91
+ const answers: QuestionAnswer[] = [];
92
+ for (let qi = 0; qi < params.questions.length; qi++) {
93
+ const q = params.questions[qi];
94
+ const header = q.header ? `[${q.header}] ` : "";
95
+ const answer = q.multiSelect ? await askMultiSelect(ui, q, qi, header) : await askSingleSelect(ui, q, qi, header);
96
+ if (answer === undefined) return { answers, cancelled: true };
97
+ answers.push(answer);
98
+ }
99
+ return { answers, cancelled: false };
100
+ }
101
+
102
+ /** `undefined` means the user dismissed the dialog (cancel the questionnaire). */
103
+ async function askSingleSelect(
104
+ ui: DialogUI,
105
+ q: QuestionData,
106
+ questionIndex: number,
107
+ header: string,
108
+ ): Promise<QuestionAnswer | undefined> {
109
+ const options = q.options.map(formatOptionLine);
110
+ options.push(`${q.options.length + 1}. ${displayLabel("other")}`);
111
+ const chosen = await ui.select(`${header}${q.question}${buildPreviewBlock(q)}`, options);
112
+ if (chosen == null) return undefined;
113
+ const idx = parseIndex(chosen, options.length);
114
+ // A host returning something outside the offered list is indistinguishable
115
+ // from a dismissal — treat it as one rather than fabricate an answer.
116
+ if (idx == null) return undefined;
117
+ if (idx < q.options.length) {
118
+ const o = q.options[idx];
119
+ return {
120
+ questionIndex,
121
+ question: q.question,
122
+ kind: "option",
123
+ answer: o.label,
124
+ preview: o.preview && o.preview.length > 0 ? o.preview : undefined,
125
+ };
126
+ }
127
+ // "Type something." sentinel → free-text follow-up.
128
+ const typed = await ui.input(`${header}${q.question}\n\n${t("rpc.custom_answer_title", CUSTOM_ANSWER_TITLE)}`, "");
129
+ if (typed == null) return undefined;
130
+ return { questionIndex, question: q.question, kind: "custom", answer: typed };
131
+ }
132
+
133
+ /** `undefined` means the user dismissed the dialog (cancel the questionnaire). */
134
+ async function askMultiSelect(
135
+ ui: DialogUI,
136
+ q: QuestionData,
137
+ questionIndex: number,
138
+ header: string,
139
+ ): Promise<QuestionAnswer | undefined> {
140
+ const list = q.options.map(formatOptionLine).join("\n");
141
+ const value = await ui.input(
142
+ `${header}${q.question}\n\n${list}\n\n${t("rpc.multi_instructions", MULTI_SELECT_INSTRUCTIONS)}`,
143
+ MULTI_SELECT_PLACEHOLDER,
144
+ );
145
+ if (value == null) return undefined;
146
+ const trimmed = value.trim();
147
+ if (trimmed.length === 0) {
148
+ // Deliberate empty commit — same as pressing "Next" with nothing toggled.
149
+ return { questionIndex, question: q.question, kind: "multi", answer: null, selected: [] };
150
+ }
151
+ const tokens = trimmed.split(/[,\s]+/).filter((tok) => tok.length > 0);
152
+ const indices = tokens.map((tok) => (/^\d+\.?$/.test(tok) ? parseIndex(tok, q.options.length) : null));
153
+ if (indices.every((i): i is number => i != null)) {
154
+ const selected: string[] = [];
155
+ for (const i of indices) {
156
+ const label = q.options[i].label;
157
+ if (!selected.includes(label)) selected.push(label);
158
+ }
159
+ return { questionIndex, question: q.question, kind: "multi", answer: null, selected };
160
+ }
161
+ // Any non-index token (words, or an out-of-range number like "13" for three
162
+ // options) means the user typed an answer, not a selection. Preserve it
163
+ // verbatim as a custom answer instead of silently dropping their input —
164
+ // this is also the multi-select "Type something." escape.
165
+ return { questionIndex, question: q.question, kind: "custom", answer: trimmed };
166
+ }
@@ -7,7 +7,6 @@ import {
7
7
  globalBinding,
8
8
  perTabBinding,
9
9
  } from "../view/component-binding.js";
10
- import { ChatRowView } from "../view/components/chat-row-view.js";
11
10
  import { MultiSelectView } from "../view/components/multi-select-view.js";
12
11
  import { OptionListView } from "../view/components/option-list-view.js";
13
12
  import { PreviewBlockRenderer } from "../view/components/preview/preview-block-renderer.js";
@@ -21,11 +20,9 @@ import { DialogView } from "../view/dialog-builder.js";
21
20
  import { QuestionnairePropsAdapter } from "../view/props-adapter.js";
22
21
  import type { StatefulView } from "../view/stateful-view.js";
23
22
  import type { TabBodyHeights, TabComponents } from "../view/tab-components.js";
24
- import { displayLabel } from "./i18n-bridge.js";
25
23
  import type { PerTabSelector } from "./selectors/contract.js";
26
24
  import { selectActivePreviewPaneIndex } from "./selectors/derivations.js";
27
25
  import {
28
- selectChatRowProps,
29
26
  selectDialogProps,
30
27
  selectMultiSelectProps,
31
28
  selectOptionListProps,
@@ -102,7 +99,6 @@ class QuestionnaireBuilder {
102
99
 
103
100
  private readonly selectTheme: WrappingSelectTheme;
104
101
  private readonly markdownTheme = getMarkdownTheme();
105
- private readonly chatRow: ChatRowView;
106
102
  private readonly notesInput = new Input();
107
103
  private readonly inlineInput = new Input();
108
104
  private readonly getTerminalWidth = () => this.tui.terminal.columns;
@@ -118,10 +114,6 @@ class QuestionnaireBuilder {
118
114
  this.getCurrentTab = config.getCurrentTab;
119
115
 
120
116
  this.selectTheme = this.makeSelectTheme();
121
- this.chatRow = new ChatRowView({
122
- item: { kind: "chat", label: displayLabel("chat") },
123
- theme: this.selectTheme,
124
- });
125
117
  }
126
118
 
127
119
  build(): QuestionnaireBuilt {
@@ -237,7 +229,6 @@ class QuestionnaireBuilder {
237
229
  questions: this.questions,
238
230
  tabBar,
239
231
  notesInput: this.notesInput,
240
- chatRow: this.chatRow,
241
232
  isMulti: this.isMulti,
242
233
  tabsByIndex: tabs,
243
234
  submitPicker,
@@ -256,7 +247,6 @@ class QuestionnaireBuilder {
256
247
  ): ReadonlyArray<BoundGlobalBinding> {
257
248
  return [
258
249
  globalBinding({ component: dialog, select: selectDialogProps }),
259
- globalBinding({ component: this.chatRow, select: selectChatRowProps }),
260
250
  ...(submitPicker ? [globalBinding({ component: submitPicker, select: selectSubmitPickerProps })] : []),
261
251
  ...(tabBar ? [globalBinding({ component: tabBar, select: selectTabBarProps })] : []),
262
252
  ];
@@ -22,12 +22,6 @@ export type QuestionnaireAction =
22
22
  | { kind: "notes_exit" }
23
23
  | { kind: "submit" }
24
24
  | { kind: "submit_nav"; nextIndex: 0 | 1 }
25
- | { kind: "focus_chat" }
26
- /**
27
- * Carries the target index so UP/DOWN form a continuous cycle through
28
- * `[chat, option0, …, optionLast]`.
29
- */
30
- | { kind: "focus_options"; optionIndex: number }
31
25
  | { kind: "notes_forward"; data: string }
32
26
  /** Flip `state.collapsed`. Always available, regardless of inner mode (see top intercept in `routeKey`). */
33
27
  | { kind: "toggle_collapsed" }
@@ -64,18 +58,7 @@ function buildSingleSelectAnswer(state: QuestionnaireState, runtime: Questionnai
64
58
  const q = runtime.questions[state.currentTab];
65
59
  if (!q) return null;
66
60
 
67
- // Chat sentinel takes priority over inputMode: when chatFocused=true, the host overrides
68
- // currentItem() to return the chat sentinel even if inputMode is still true (e.g. user
69
- // navigated from "Type something." and DOWN focused the chat row).
70
61
  const item = runtime.currentItem;
71
- if (item?.kind === "chat") {
72
- return {
73
- questionIndex: state.currentTab,
74
- question: q.question,
75
- kind: "chat",
76
- answer: item.label,
77
- };
78
- }
79
62
 
80
63
  if (state.inputMode) {
81
64
  const label = runtime.inputBuffer;
@@ -130,19 +113,13 @@ function tabSwitchAction(
130
113
  return null;
131
114
  }
132
115
 
133
- // DOWN at the last item emits focus_chat so the cycle [chat, option0, …, optionLast] wraps.
116
+ // DOWN at the last item wraps to the first (cycle through [option0, …, optionLast]).
134
117
  function nextNavOnDown(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
135
- if (runtime.items.length > 0 && state.optionIndex === runtime.items.length - 1) {
136
- return { kind: "focus_chat" };
137
- }
138
118
  return { kind: "nav", nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)) };
139
119
  }
140
120
 
141
- // UP at the top item emits focus_chat (symmetric with nextNavOnDown).
121
+ // UP at the first item wraps to the last (symmetric with nextNavOnDown).
142
122
  function prevNavOnUp(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
143
- if (runtime.items.length > 0 && state.optionIndex === 0) {
144
- return { kind: "focus_chat" };
145
- }
146
123
  return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)) };
147
124
  }
148
125
 
@@ -150,19 +127,24 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
150
127
  const kb = runtime.keybindings;
151
128
 
152
129
  // Collapse/expand toggle is a UI-level affordance — intercepted at the top so it
153
- // works from every inner state (notes, inputMode, chat, submit tab, multi-select)
130
+ // works from every inner state (notes, inputMode, submit tab, multi-select)
154
131
  // without reaching any branch that would otherwise consume the keystroke. The
155
- // questionnaire stays in pi-tui's overlay stack with focus while collapsed, so the
156
- // expand key never falls through to a lower overlay (e.g. `/btw`) — that's why we
157
- // toggle state instead of calling `OverlayHandle.setHidden(true)`.
132
+ // questionnaire overlay is fully hidden via `OverlayHandle.setHidden(true)` while
133
+ // collapsed; pi-tui's overlay stack updates accordingly, so overlay-aware consumers
134
+ // (e.g. `pi-station`) see no visible modal and chat scroll resumes. The toggle key is
135
+ // also captured at the raw terminal level via `ctx.ui.onTerminalInput` so it still
136
+ // routes here when the overlay is hidden (pi-tui does not deliver input to a hidden
137
+ // overlay's `component.handleInput`).
158
138
  //
159
- // Ctrl+] (GS, 0x1d): chosen after Alt+Tab (OS-reserved on macOS), Ctrl+P (collides
160
- // with pi-coding-agent "cycle model" + the user's virtual terminal), and F2 (taken
161
- // by macOS function-key behavior) were all eliminated. Ctrl+] is free in every
162
- // mainstream macOS terminal (Terminal.app, iTerm2, Warp), every multiplexer (tmux,
163
- // zellij, screen — none use it as a prefix), and the legacy telnet/ssh escape role
164
- // doesn't apply because our overlay runs in-process.
165
- if (matchesKey(data, Key.ctrl("]"))) return { kind: "toggle_collapsed" };
139
+ // The default `ctrl+]` is free in every mainstream macOS terminal (Terminal.app,
140
+ // iTerm2, Warp), every multiplexer (tmux, zellij, screen — none use it as a prefix),
141
+ // and the legacy telnet/ssh escape role doesn't apply because our overlay runs
142
+ // in-process. It is, however, awkward on keyboard layouts where `]` is on the
143
+ // shifted layer (Latin American `es-AR`/`es-MX` require `Ctrl+Shift+}` for `Ctrl+]`)
144
+ // — use the `collapseKey` config field to override.
145
+ if (runtime.collapseKey !== "off" && matchesKey(data, runtime.collapseKey as Parameters<typeof matchesKey>[1])) {
146
+ return { kind: "toggle_collapsed" };
147
+ }
166
148
 
167
149
  // Collapsed-mode lockout: while collapsed, swallow every keystroke except cancel so
168
150
  // the user can read the now-uncovered transcript without accidentally mutating
@@ -178,29 +160,6 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
178
160
  return { kind: "notes_forward", data };
179
161
  }
180
162
 
181
- if (state.chatFocused) {
182
- if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
183
- if (kb.matches(data, KEYBIND_CONFIRM)) {
184
- const answer = buildSingleSelectAnswer(state, runtime);
185
- if (!answer) return { kind: "ignore" };
186
- return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
187
- }
188
- // Continuous cycle: UP from chat → bottom of options (last navigable row), DOWN from
189
- // chat → top of options (option 0). Symmetric with UP-at-top → focus_chat and
190
- // DOWN-at-bottom → focus_chat below; together they form one wrapping cycle through
191
- // `[chat, option0, …, optionLast]`.
192
- if (kb.matches(data, KEYBIND_UP)) {
193
- const last = Math.max(0, runtime.items.length - 1);
194
- return { kind: "focus_options", optionIndex: last };
195
- }
196
- if (kb.matches(data, KEYBIND_DOWN)) {
197
- return { kind: "focus_options", optionIndex: 0 };
198
- }
199
- const tab = tabSwitchAction(data, state, runtime);
200
- if (tab) return tab;
201
- return { kind: "ignore" };
202
- }
203
-
204
163
  if (state.inputMode) {
205
164
  if (kb.matches(data, KEYBIND_CONFIRM)) {
206
165
  const answer = buildSingleSelectAnswer(state, runtime);
@@ -256,13 +215,18 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
256
215
  const focusedKind = runtime.currentItem?.kind;
257
216
  const focusedMeta = focusedKind ? ROW_INTENT_META[focusedKind] : undefined;
258
217
  // Space toggles the focused row's checkbox. Suppressed on rows whose META declares
259
- // `blocksMultiToggle` (the Next sentinel) — Next is not a real option and has no
260
- // checked/unchecked state.
218
+ // `blocksMultiToggle` (the Next sentinel) or `activatesInputMode` (the "Type
219
+ // something." row — it is an inline input, not a checkable option).
261
220
  if (data === SPACE_KEY) {
262
221
  if (focusedMeta?.blocksMultiToggle) return { kind: "ignore" };
222
+ if (focusedMeta?.activatesInputMode) return { kind: "ignore" };
263
223
  return { kind: "toggle", index: state.optionIndex };
264
224
  }
265
225
  if (kb.matches(data, KEYBIND_CONFIRM)) {
226
+ // Enter on the "Type something." row is handled by the inputMode block above
227
+ // (→ confirm kind:"custom"). Defensive: never enter the toggle/multi_confirm
228
+ // path for an inputMode-activating row.
229
+ if (focusedMeta?.activatesInputMode) return { kind: "ignore" };
266
230
  // Enter on a regular row toggles (matching Space) — committing the question is now
267
231
  // gated behind explicit focus on a row whose META declares `autoSubmitsInMulti`
268
232
  // (the Next sentinel), so Enter on options is a no-cost way to flip checkboxes
@@ -1,11 +1,11 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { getKeybindings, type Input } from "@earendil-works/pi-tui";
2
+ import { getKeybindings, type Input, type OverlayHandle } from "@earendil-works/pi-tui";
3
3
  import type { QuestionData, QuestionnaireResult, QuestionParams } from "../tool/types.js";
4
4
  import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
5
5
  import { COLLAPSED_HINT } from "../view/dialog-builder.js";
6
6
  import type { QuestionnairePropsAdapter } from "../view/props-adapter.js";
7
7
  import { buildQuestionnaire } from "./build-questionnaire.js";
8
- import { displayLabel, t } from "./i18n-bridge.js";
8
+ import { t } from "./i18n-bridge.js";
9
9
  import { type QuestionnaireAction, routeKey } from "./key-router.js";
10
10
  import { computeFocusedOptionHasPreview } from "./selectors/derivations.js";
11
11
  import type { QuestionnaireRuntime, QuestionnaireState } from "./state.js";
@@ -21,6 +21,8 @@ export interface QuestionnaireSessionConfig {
21
21
  params: QuestionParams;
22
22
  itemsByTab: WrappingSelectItem[][];
23
23
  done: (result: QuestionnaireResult) => void;
24
+ /** Key spec for the collapse/expand shortcut, e.g. `"ctrl+]"` or `"alt+o"`. */
25
+ collapseKey: string;
24
26
  }
25
27
 
26
28
  export interface QuestionnaireSessionComponent {
@@ -35,7 +37,6 @@ function initialState(): QuestionnaireState {
35
37
  optionIndex: 0,
36
38
  inputMode: false,
37
39
  notesVisible: false,
38
- chatFocused: false,
39
40
  answers: new Map(),
40
41
  multiSelectChecked: new Set(),
41
42
  notesByTab: new Map(),
@@ -62,10 +63,17 @@ export class QuestionnaireSession {
62
63
  private readonly notesInput: Input;
63
64
  private readonly inlineInput: Input;
64
65
  private readonly viewAdapter: QuestionnairePropsAdapter;
66
+ private readonly collapseKey: string;
67
+
68
+ /**
69
+ * Overlay handle captured by `ctx.ui.custom`'s `onHandle` callback. Lets the session
70
+ * call `setHidden(true/false)` so pi-tui's overlay stack reflects the collapsed state
71
+ * and overlay-aware consumers (e.g. `pi-station`) can resume normal behaviour.
72
+ */
73
+ private overlayHandle: OverlayHandle | undefined;
65
74
 
66
75
  private readonly tui: QuestionnaireSessionConfig["tui"];
67
76
  private readonly done: QuestionnaireSessionConfig["done"];
68
-
69
77
  readonly component: QuestionnaireSessionComponent;
70
78
 
71
79
  constructor(config: QuestionnaireSessionConfig) {
@@ -74,6 +82,7 @@ export class QuestionnaireSession {
74
82
  this.questions = config.params.questions;
75
83
  this.isMulti = this.questions.length > 1;
76
84
  this.itemsByTab = config.itemsByTab;
85
+ this.collapseKey = config.collapseKey;
77
86
  // Seed from the focused option at start; the reducer keeps it in sync via withFocusedOptionHasPreview.
78
87
  this.state = { ...this.state, focusedOptionHasPreview: computeFocusedOptionHasPreview(this.questions, 0, 0) };
79
88
 
@@ -150,6 +159,11 @@ export class QuestionnaireSession {
150
159
  case "forward_notes_keystroke":
151
160
  this.notesInput.handleInput(effect.data);
152
161
  return;
162
+ case "set_overlay_hidden":
163
+ // No-op until `setOverlayHandle` has been called (the handle arrives via
164
+ // `ctx.ui.custom`'s `onHandle` right after the overlay is shown).
165
+ this.overlayHandle?.setHidden(effect.hidden);
166
+ return;
153
167
  case "done":
154
168
  this.done(effect.result);
155
169
  return;
@@ -183,6 +197,7 @@ export class QuestionnaireSession {
183
197
  isMulti: this.isMulti,
184
198
  currentItem: this.currentItem(),
185
199
  items: this.itemsByTab[this.state.currentTab] ?? [],
200
+ collapseKey: this.collapseKey,
186
201
  };
187
202
  }
188
203
 
@@ -194,9 +209,28 @@ export class QuestionnaireSession {
194
209
  }
195
210
 
196
211
  private currentItem(): WrappingSelectItem | undefined {
197
- if (this.state.chatFocused) return { kind: "chat", label: displayLabel("chat") };
198
212
  const arr = this.itemsByTab[this.state.currentTab] ?? [];
199
- if (this.state.optionIndex < arr.length) return arr[this.state.optionIndex];
200
- return { kind: "chat", label: displayLabel("chat") };
213
+ return this.state.optionIndex < arr.length ? arr[this.state.optionIndex] : undefined;
214
+ }
215
+
216
+ /**
217
+ * Setter for the overlay handle, called by `ctx.ui.custom`'s `onHandle` callback once
218
+ * the TUI has created the overlay. Until this is called, `set_overlay_hidden` effects
219
+ * are no-ops — the session still tracks `state.collapsed` for the view layer.
220
+ */
221
+ setOverlayHandle(handle: OverlayHandle): void {
222
+ this.overlayHandle = handle;
223
+ }
224
+
225
+ /**
226
+ * Public toggle used by the raw terminal input listener registered in `execute()`.
227
+ * pi-tui does not route input to a hidden overlay's `component.handleInput`, so the
228
+ * raw listener (which fires for terminal data regardless of overlay visibility)
229
+ * reaches the session through this method instead of the dispatch path. Routed
230
+ * through `commit` so the transition stays in the reducer and the overlay hide
231
+ * happens via the `set_overlay_hidden` effect like every other side effect.
232
+ */
233
+ toggleCollapsedExternal(): void {
234
+ this.commit({ kind: "toggle_collapsed" });
201
235
  }
202
236
  }
@@ -15,7 +15,7 @@ export type RowKind = WrappingSelectItem["kind"];
15
15
  * derivation, and `LABELS_BY_KIND` consumers iterate this list.
16
16
  */
17
17
  export type SentinelKind = Exclude<RowKind, "option">;
18
- export const SENTINEL_KINDS: readonly SentinelKind[] = ["other", "chat", "next"];
18
+ export const SENTINEL_KINDS: readonly SentinelKind[] = ["other", "next"];
19
19
 
20
20
  /**
21
21
  * Per-kind static metadata. Pure data — no closures, no per-kind handler
@@ -28,8 +28,7 @@ export const SENTINEL_KINDS: readonly SentinelKind[] = ["other", "chat", "next"]
28
28
  * 1. Add the variant to `WrappingSelectItem` (`wrapping-select.ts:18-22`).
29
29
  * 2. Add an entry here. Compile fails until both edits are present.
30
30
  * 3. (If user-facing) author wherever the row is synthesized — typically
31
- * `buildItemsForQuestion` for main-list residents, or the `chatList`
32
- * construction site for non-main-list rows.
31
+ * `buildItemsForQuestion` for main-list residents.
33
32
  *
34
33
  * Field semantics:
35
34
  * - `label` — user-facing string. For `option` it's an empty placeholder
@@ -37,25 +36,22 @@ export const SENTINEL_KINDS: readonly SentinelKind[] = ["other", "chat", "next"]
37
36
  * sentinel uses its META entry as the single source of truth.
38
37
  * - `reserved` — author-facing labels matching this string trigger
39
38
  * `reserved_label` at validation time. `RESERVED_LABEL_SET` is derived.
40
- * - `livesInMainList` — true iff the row appears in `itemsByTab[i]`. Chat
41
- * lives in its own `chatList` (`questionnaire-session.ts:95`) so its row
42
- * never enters the main list.
43
- * - `numbered` — true iff the row contributes to the main-list numbering
44
- * offset that `chatNumberingFor` reads. Multi-select Next is the only
45
- * numberable=false row that lives in the list; chat is numbered=true but
46
- * `livesInMainList=false` so the flag is moot for chat.
39
+ * - `livesInMainList` — true iff the row appears in `itemsByTab[i]`. Every
40
+ * current sentinel lives in the main list (the `next` row is synthesized by
41
+ * `sentinelsToAppend`).
42
+ * - `numbered` — true iff the row contributes to the main-list numbering.
43
+ * Multi-select Next is the only `numbered=false` row that lives in the list.
47
44
  * - `activatesInputMode` — true iff focusing the row should toggle
48
- * `state.inputMode = true`. Read by `state-reducer.ts` `nav` /
49
- * `focus_options` cases.
45
+ * `state.inputMode = true`. Read by `state-reducer.ts` `nav` case.
50
46
  * - `blocksMultiToggle` — in multiSelect mode, Space (and Enter-as-toggle)
51
47
  * on this row is suppressed. The Next sentinel is the only true.
52
48
  * - `autoSubmitsInMulti` — in multiSelect mode, Enter on this row commits
53
49
  * the question (emits `multi_confirm`). The Next sentinel is the only true.
54
- * - `autoAppendOnSingleSelectNoPreview` — `buildItemsForQuestion` appends
55
- * this row when the question is single-select AND no option carries a
56
- * `preview`. The "other" sentinel is the only true.
50
+ * - `autoAppendOnSingleSelect` — `buildItemsForQuestion` appends
51
+ * this row when the question is single-select, regardless of whether any
52
+ * option carries a `preview`. The "other" sentinel is the only true.
57
53
  * - `autoAppendOnMultiSelect` — `buildItemsForQuestion` appends this row
58
- * when the question is multi-select. The Next sentinel is the only true.
54
+ * when the question is multi-select. The `other` and `next` sentinels are both true.
59
55
  */
60
56
  export interface RowIntentMeta {
61
57
  label: string;
@@ -65,7 +61,7 @@ export interface RowIntentMeta {
65
61
  activatesInputMode: boolean;
66
62
  blocksMultiToggle: boolean;
67
63
  autoSubmitsInMulti: boolean;
68
- autoAppendOnSingleSelectNoPreview: boolean;
64
+ autoAppendOnSingleSelect: boolean;
69
65
  autoAppendOnMultiSelect: boolean;
70
66
  }
71
67
 
@@ -78,7 +74,7 @@ export const ROW_INTENT_META: Record<RowKind, RowIntentMeta> = {
78
74
  activatesInputMode: false,
79
75
  blocksMultiToggle: false,
80
76
  autoSubmitsInMulti: false,
81
- autoAppendOnSingleSelectNoPreview: false,
77
+ autoAppendOnSingleSelect: false,
82
78
  autoAppendOnMultiSelect: false,
83
79
  },
84
80
  other: {
@@ -89,19 +85,8 @@ export const ROW_INTENT_META: Record<RowKind, RowIntentMeta> = {
89
85
  activatesInputMode: true,
90
86
  blocksMultiToggle: false,
91
87
  autoSubmitsInMulti: false,
92
- autoAppendOnSingleSelectNoPreview: true,
93
- autoAppendOnMultiSelect: false,
94
- },
95
- chat: {
96
- label: "Chat about this",
97
- reserved: true,
98
- livesInMainList: false,
99
- numbered: true,
100
- activatesInputMode: false,
101
- blocksMultiToggle: false,
102
- autoSubmitsInMulti: false,
103
- autoAppendOnSingleSelectNoPreview: false,
104
- autoAppendOnMultiSelect: false,
88
+ autoAppendOnSingleSelect: true,
89
+ autoAppendOnMultiSelect: true,
105
90
  },
106
91
  next: {
107
92
  label: "Next",
@@ -111,7 +96,7 @@ export const ROW_INTENT_META: Record<RowKind, RowIntentMeta> = {
111
96
  activatesInputMode: false,
112
97
  blocksMultiToggle: true,
113
98
  autoSubmitsInMulti: true,
114
- autoAppendOnSingleSelectNoPreview: false,
99
+ autoAppendOnSingleSelect: false,
115
100
  autoAppendOnMultiSelect: true,
116
101
  },
117
102
  };
@@ -122,7 +107,6 @@ export const ROW_INTENT_META: Record<RowKind, RowIntentMeta> = {
122
107
  */
123
108
  export const LABELS_BY_KIND: { readonly [K in SentinelKind]: string } = {
124
109
  other: ROW_INTENT_META.other.label,
125
- chat: ROW_INTENT_META.chat.label,
126
110
  next: ROW_INTENT_META.next.label,
127
111
  };
128
112
 
@@ -138,13 +122,13 @@ export const RESERVED_LABEL_SET: ReadonlySet<string> = new Set<string>([
138
122
  /**
139
123
  * Walk the META table to synthesize sentinel rows for one question. The two
140
124
  * append predicates are mutually exclusive in practice (`multiSelect` vs
141
- * `!multiSelect && !hasAnyPreview`) but the walker doesn't enforce that —
142
- * adding a third bucket only requires a new META flag.
125
+ * single-select) but the walker doesn't enforce that — adding a third bucket
126
+ * only requires a new META flag.
143
127
  *
144
128
  * Returns sentinel descriptors in declaration order of `SENTINEL_KINDS`. The
145
129
  * caller wraps each with the `WrappingSelectItem` shape (kind + label).
146
130
  */
147
- export function sentinelsToAppend(question: QuestionData, hasAnyPreview: boolean): SentinelKind[] {
131
+ export function sentinelsToAppend(question: QuestionData): SentinelKind[] {
148
132
  const out: SentinelKind[] = [];
149
133
  for (const k of SENTINEL_KINDS) {
150
134
  const meta = ROW_INTENT_META[k];
@@ -152,7 +136,7 @@ export function sentinelsToAppend(question: QuestionData, hasAnyPreview: boolean
152
136
  if (question.multiSelect === true) {
153
137
  if (meta.autoAppendOnMultiSelect) out.push(k);
154
138
  } else {
155
- if (meta.autoAppendOnSingleSelectNoPreview && !hasAnyPreview) out.push(k);
139
+ if (meta.autoAppendOnSingleSelect) out.push(k);
156
140
  }
157
141
  }
158
142
  return out;