Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Support multi-select pending user inputs (#1797)

Julius Marminge11d456f6c840
diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts
index b5eb873e8..db91e8da0 100644
--- a/apps/server/src/provider/Layers/CodexAdapter.test.ts
+++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts
@@ -723,6 +723,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
description: "Allow workspace writes only",
},
],
+ multiSelect: true,
},
],
},
@@ -749,6 +750,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
if (events[0]?.type === "user-input.requested") {
assert.equal(events[0].requestId, "req-user-input-1");
assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
+ assert.equal(events[0].payload.questions[0]?.multiSelect, true);
}
assert.equal(events[1]?.type, "user-input.resolved");
diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts
index 8b9f3b59e..957ae1b2b 100644
--- a/apps/server/src/provider/Layers/CodexAdapter.ts
+++ b/apps/server/src/provider/Layers/CodexAdapter.ts
@@ -382,6 +382,7 @@ function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
header,
question: prompt,
options,
+ multiSelect: question.multiSelect === true,
};
})
.filter(
@@ -392,6 +393,7 @@ function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
header: string;
question: string;
options: Array<{ label: string; description: string }>;
+ multiSelect: boolean;
} => question !== undefined,
);
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx
index 1d9108aab..8e848205d 100644
--- a/apps/web/src/components/ChatView.browser.tsx
+++ b/apps/web/src/components/ChatView.browser.tsx
@@ -12,6 +12,7 @@ import {
type ServerLifecycleWelcomePayload,
type ThreadId,
type TurnId,
+ type UserInputQuestion,
WS_METHODS,
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
@@ -541,12 +542,51 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
};
}
-function createSnapshotWithPendingUserInput(): OrchestrationReadModel {
+function createSnapshotWithPendingUserInput(options?: {
+ questions?: ReadonlyArray<UserInputQuestion>;
+}): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-pending-input-target" as MessageId,
targetText: "question thread",
});
+ const questions =
+ options?.questions ??
+ ([
+ {
+ id: "scope",
+ header: "Scope",
+ question: "What should this change cover?",
+ options: [
+ {
+ label: "Tight",
+ description: "Touch only the footer layout logic.",
+ },
+ {
+ label: "Broad",
+ description: "Also adjust the related composer controls.",
+ },
+ ],
+ multiSelect: false,
+ },
+ {
+ id: "risk",
+ header: "Risk",
+ question: "How aggressive should the imaginary plan be?",
+ options: [
+ {
+ label: "Conservative",
+ description: "Favor reliability and low-risk changes.",
+ },
+ {
+ label: "Balanced",
+ description: "Mix quick wins with one structural improvement.",
+ },
+ ],
+ multiSelect: false,
+ },
+ ] satisfies ReadonlyArray<UserInputQuestion>);
+
return {
...snapshot,
threads: snapshot.threads.map((thread) =>
@@ -561,38 +601,7 @@ function createSnapshotWithPendingUserInput(): OrchestrationReadModel {
summary: "User input requested",
payload: {
requestId: "req-browser-user-input",
- questions: [
- {
- id: "scope",
- header: "Scope",
- question: "What should this change cover?",
- options: [
- {
- label: "Tight",
- description: "Touch only the footer layout logic.",
- },
- {
- label: "Broad",
- description: "Also adjust the related composer controls.",
- },
- ],
- },
- {
- id: "risk",
- header: "Risk",
- question: "How aggressive should the imaginary plan be?",
- options: [
- {
- label: "Conservative",
- description: "Favor reliability and low-risk changes.",
- },
- {
- label: "Balanced",
- description: "Mix quick wins with one structural improvement.",
- },
- ],
- },
- ],
+ questions,
},
turnId: null,
sequence: 1,
@@ -2902,6 +2911,143 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
+ it("does not trigger numeric option shortcuts while the composer is focused", async () => {
+ const mounted = await mountChatView({
+ viewport: WIDE_FOOTER_VIEWPORT,
+ snapshot: createSnapshotWithPendingUserInput(),
+ });
+
+ try {
+ const composerEditor = await waitForComposerEditor();
+ composerEditor.focus();
+
+ const event = new KeyboardEvent("keydown", {
+ key: "2",
+ bubbles: true,
+ cancelable: true,
+ });
+ composerEditor.dispatchEvent(event);
+ await waitForLayout();
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(document.body.textContent).toContain("What should this change cover?");
+ expect(document.body.textContent).not.toContain(
+ "How aggressive should the imaginary plan be?",
+ );
+ await waitForButtonByText("Next question");
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("submits multi-select questionnaire answers as arrays", async () => {
+ const mounted = await mountChatView({
+ viewport: WIDE_FOOTER_VIEWPORT,
+ snapshot: createSnapshotWithPendingUserInput({
+ questions: [
+ {
+ id: "scope",
+ header: "Scope",
+ question: "Which areas should this change cover?",
+ options: [
+ {
+ label: "Server",
+ description: "Touch server orchestration.",
+ },
+ {
+ label: "Web",
+ description: "Touch the browser UI.",
+ },
+ ],
+ multiSelect: true,
+ },
+ {
+ id: "risk",
+ header: "Risk",
+ question: "How aggressive should the imaginary plan be?",
+ options: [
+ {
+ label: "Balanced",
+ description: "Mix quick wins with one structural improvement.",
+ },
+ ],
+ multiSelect: false,
+ },
+ ],
+ }),
+ resolveRpc: (body) => {
+ if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
+ return {
+ sequence: fixture.snapshot.snapshotSequence + 1,
+ };
+ }
+ return undefined;
+ },
+ });
+
+ try {
+ const serverOption = await waitForButtonContainingText("Server");
+ serverOption.click();
+ await waitForLayout();
+
+ expect(document.body.textContent).toContain("Which areas should this change cover?");
+
+ const webOption = await waitForButtonContainingText("Web");
+ webOption.click();
+ await waitForLayout();
+
+ expect(document.body.textContent).toContain("Which areas should this change cover?");
+
+ const nextButton = await waitForButtonByText("Next question");
+ expect(nextButton.disabled).toBe(false);
+ nextButton.click();
+
+ await vi.waitFor(
+ () => {
+ expect(document.body.textContent).toContain(
+ "How aggressive should the imaginary plan be?",
+ );
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ const balancedOption = await waitForButtonContainingText("Balanced");
+ balancedOption.click();
+
+ const submitButton = await waitForButtonByText("Submit answers");
+ expect(submitButton.disabled).toBe(false);
+ submitButton.click();
+
+ await vi.waitFor(
+ () => {
+ const dispatchRequest = wsRequests.find(
+ (request) =>
+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
+ request.type === "thread.user-input.respond",
+ ) as
+ | {
+ _tag: string;
+ type?: string;
+ answers?: Record<string, unknown>;
+ }
+ | undefined;
+
+ expect(dispatchRequest).toMatchObject({
+ _tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
+ type: "thread.user-input.respond",
+ answers: {
+ scope: ["Server", "Web"],
+ risk: "Balanced",
+ },
+ });
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 5d160f4bd..7c649b500 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -61,6 +61,7 @@ import {
buildPendingUserInputAnswers,
derivePendingUserInputProgress,
setPendingUserInputCustomAnswer,
+ togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
@@ -3207,19 +3208,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
[activePendingUserInput],
);
- const onSelectActivePendingUserInputOption = useCallback(
+ const onToggleActivePendingUserInputOption = useCallback(
(questionId: string, optionLabel: string) => {
if (!activePendingUserInput) {
return;
}
+ const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
+ if (!question) {
+ return;
+ }
setPendingUserInputAnswersByRequestId((existing) => ({
...existing,
[activePendingUserInput.requestId]: {
...existing[activePendingUserInput.requestId],
- [questionId]: {
- selectedOptionLabel: optionLabel,
- customAnswer: "",
- },
+ [questionId]: togglePendingUserInputOptionSelection(
+ question,
+ existing[activePendingUserInput.requestId]?.[questionId],
+ optionLabel,
+ ),
},
}));
promptRef.current = "";
@@ -4063,7 +4069,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
respondingRequestIds={respondingRequestIds}
answers={activePendingDraftAnswers}
questionIndex={activePendingQuestionIndex}
- onSelectOption={onSelectActivePendingUserInputOption}
+ onToggleOption={onToggleActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
/>
</div>
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index c8cad7bf3..2a1efb4b2 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -13,7 +13,7 @@ interface PendingUserInputPanelProps {
respondingRequestIds: ApprovalRequestId[];
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
- onSelectOption: (questionId: string, optionLabel: string) => void;
+ onToggleOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}
@@ -22,7 +22,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
respondingRequestIds,
answers,
questionIndex,
- onSelectOption,
+ onToggleOption,
onAdvance,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
@@ -36,7 +36,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
isResponding={respondingRequestIds.includes(activePrompt.requestId)}
answers={answers}
questionIndex={questionIndex}
- onSelectOption={onSelectOption}
+ onToggleOption={onToggleOption}
onAdvance={onAdvance}
/>
);
@@ -47,14 +47,14 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
isResponding,
answers,
questionIndex,
- onSelectOption,
+ onToggleOption,
onAdvance,
}: {
prompt: PendingUserInput;
isResponding: boolean;
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
- onSelectOption: (questionId: string, optionLabel: string) => void;
+ onToggleOption: (questionId: string, optionLabel: string) => void;
onAdvance: () => void;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
@@ -70,9 +70,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
}, []);
- const selectOptionAndAutoAdvance = useCallback(
+ const handleOptionSelection = useCallback(
(questionId: string, optionLabel: string) => {
- onSelectOption(questionId, optionLabel);
+ onToggleOption(questionId, optionLabel);
+ if (activeQuestion?.multiSelect) {
+ return;
+ }
if (autoAdvanceTimerRef.current !== null) {
window.clearTimeout(autoAdvanceTimerRef.current);
}
@@ -81,13 +84,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onAdvance();
}, 200);
},
- [onSelectOption, onAdvance],
+ [activeQuestion?.multiSelect, onAdvance, onToggleOption],
);
- // Keyboard shortcut: number keys 1-9 select corresponding option and auto-advance.
- // Works even when the Lexical composer (contenteditable) has focus — the composer
- // doubles as a custom-answer field during user input, and when it's empty the digit
- // keys should pick options instead of typing into the editor.
+ // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
+ // outside editable fields. Multi-select prompts toggle options in place; single-
+ // select prompts keep the existing auto-advance behavior.
useEffect(() => {
if (!activeQuestion || isResponding) return;
const handler = (event: globalThis.KeyboardEvent) => {
@@ -96,11 +98,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
return;
}
- // If the user has started typing a custom answer in the contenteditable
- // composer, let digit keys pass through so they can type numbers.
if (target instanceof HTMLElement && target.isContentEditable) {
- const hasCustomText = progress.customAnswer.length > 0;
- if (hasCustomText) return;
+ return;
}
const digit = Number.parseInt(event.key, 10);
if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
@@ -109,11 +108,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const option = activeQuestion.options[optionIndex];
if (!option) return;
event.preventDefault();
- selectOptionAndAutoAdvance(activeQuestion.id, option.label);
+ handleOptionSelection(activeQuestion.id, option.label);
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
- }, [activeQuestion, isResponding, selectOptionAndAutoAdvance, progress.customAnswer.length]);
+ }, [activeQuestion, handleOptionSelection, isResponding]);
if (!activeQuestion) {
return null;
@@ -134,16 +133,19 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
</div>
</div>
<p className="mt-1.5 text-sm text-foreground/90">{activeQuestion.question}</p>
+ {activeQuestion.multiSelect ? (
+ <p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
+ ) : null}
<div className="mt-3 space-y-1">
{activeQuestion.options.map((option, index) => {
- const isSelected = progress.selectedOptionLabel === option.label;
+ const isSelected = progress.selectedOptionLabels.includes(option.label);
const shortcutKey = index < 9 ? index + 1 : null;
return (
<button
key={`${activeQuestion.id}:${option.label}`}
type="button"
disabled={isResponding}
- onClick={() => selectOptionAndAutoAdvance(activeQuestion.id, option.label)}
+ onClick={() => handleOptionSelection(activeQuestion.id, option.label)}
className={cn(
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-all duration-150",
isSelected
diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts
index 153b31535..d06fbeaf2 100644
--- a/apps/web/src/pendingUserInput.test.ts
+++ b/apps/web/src/pendingUserInput.test.ts
@@ -7,57 +7,109 @@ import {
findFirstUnansweredPendingUserInputQuestionIndex,
resolvePendingUserInputAnswer,
setPendingUserInputCustomAnswer,
+ togglePendingUserInputOptionSelection,
} from "./pendingUserInput";
+const singleSelectQuestion = {
+ id: "scope",
+ header: "Scope",
+ question: "What should the plan target first?",
+ options: [
+ {
+ label: "Orchestration-first",
+ description: "Focus on orchestration first",
+ },
+ ],
+ multiSelect: false,
+} as const;
+
+const multiSelectQuestion = {
+ id: "areas",
+ header: "Areas",
+ question: "Which areas should this change cover?",
+ options: [
+ {
+ label: "Server",
+ description: "Server",
+ },
+ {
+ label: "Web",
+ description: "Web",
+ },
+ ],
+ multiSelect: true,
+} as const;
+
describe("resolvePendingUserInputAnswer", () => {
- it("prefers a custom answer over a selected option", () => {
+ it("prefers a custom answer over selected options", () => {
expect(
- resolvePendingUserInputAnswer({
- selectedOptionLabel: "Keep current envelope",
+ resolvePendingUserInputAnswer(singleSelectQuestion, {
+ selectedOptionLabels: ["Orchestration-first"],
customAnswer: "Keep the existing envelope for one release",
}),
).toBe("Keep the existing envelope for one release");
});
- it("falls back to the selected option", () => {
+ it("falls back to the selected option for single-select questions", () => {
expect(
- resolvePendingUserInputAnswer({
- selectedOptionLabel: "Scaffold only",
+ resolvePendingUserInputAnswer(singleSelectQuestion, {
+ selectedOptionLabels: ["Orchestration-first"],
}),
- ).toBe("Scaffold only");
+ ).toBe("Orchestration-first");
+ });
+
+ it("returns all selected labels for multi-select questions", () => {
+ expect(
+ resolvePendingUserInputAnswer(multiSelectQuestion, {
+ selectedOptionLabels: ["Server", "Web"],
+ }),
+ ).toEqual(["Server", "Web"]);
});
it("clears the preset selection when a custom answer is entered", () => {
expect(
setPendingUserInputCustomAnswer(
{
- selectedOptionLabel: "Preserve existing tags",
+ selectedOptionLabels: ["Server", "Web"],
},
"doesn't matter",
),
).toEqual({
- selectedOptionLabel: undefined,
customAnswer: "doesn't matter",
});
});
});
+describe("togglePendingUserInputOptionSelection", () => {
+ it("toggles options for multi-select questions", () => {
+ expect(togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Server")).toEqual(
+ {
+ customAnswer: "",
+ selectedOptionLabels: ["Server"],
+ },
+ );
+
+ expect(
+ togglePendingUserInputOptionSelection(
+ multiSelectQuestion,
+ {
+ selectedOptionLabels: ["Server", "Web"],
+ },
+ "Server",
+ ),
+ ).toEqual({
+ customAnswer: "",
+ selectedOptionLabels: ["Web"],
+ });
+ });
+});
+
describe("buildPendingUserInputAnswers", () => {
it("returns a canonical answer map for complete prompts", () => {
expect(
buildPendingUserInputAnswers(
[
- {
- id: "scope",
- header: "Scope",
- question: "What should the plan target first?",
- options: [
- {
- label: "Orchestration-first",
- description: "Focus on orchestration first",
- },
- ],
- },
+ singleSelectQuestion,
{
id: "compat",
header: "Compat",
@@ -68,11 +120,12 @@ describe("buildPendingUserInputAnswers", () => {
description: "Preserve current wire format",
},
],
+ multiSelect: false,
},
],
{
scope: {
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
},
compat: {
customAnswer: "Keep the current envelope for one release window",
@@ -85,41 +138,26 @@ describe("buildPendingUserInputAnswers", () => {
});
});
- it("returns null when any question is unanswered", () => {
+ it("returns arrays for answered multi-select prompts", () => {
expect(
- buildPendingUserInputAnswers(
- [
- {
- id: "scope",
- header: "Scope",
- question: "What should the plan target first?",
- options: [
- {
- label: "Orchestration-first",
- description: "Focus on orchestration first",
- },
- ],
- },
- ],
- {},
- ),
- ).toBeNull();
+ buildPendingUserInputAnswers([multiSelectQuestion], {
+ areas: {
+ selectedOptionLabels: ["Server", "Web"],
+ },
+ }),
+ ).toEqual({
+ areas: ["Server", "Web"],
+ });
+ });
+
+ it("returns null when any question is unanswered", () => {
+ expect(buildPendingUserInputAnswers([singleSelectQuestion], {})).toBeNull();
});
});
describe("pending user input question progress", () => {
const questions = [
- {
- id: "scope",
- header: "Scope",
- question: "What should the plan target first?",
- options: [
- {
- label: "Orchestration-first",
- description: "Focus on orchestration first",
- },
- ],
- },
+ singleSelectQuestion,
{
id: "compat",
header: "Compat",
@@ -130,6 +168,7 @@ describe("pending user input question progress", () => {
description: "Preserve current wire format",
},
],
+ multiSelect: false,
},
] as const;
@@ -137,7 +176,7 @@ describe("pending user input question progress", () => {
expect(
countAnsweredPendingUserInputQuestions(questions, {
scope: {
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
},
}),
).toBe(1);
@@ -147,7 +186,7 @@ describe("pending user input question progress", () => {
expect(
findFirstUnansweredPendingUserInputQuestionIndex(questions, {
scope: {
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
},
}),
).toBe(1);
@@ -157,7 +196,7 @@ describe("pending user input question progress", () => {
expect(
findFirstUnansweredPendingUserInputQuestionIndex(questions, {
scope: {
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
},
compat: {
customAnswer: "Keep it for one release window",
@@ -172,7 +211,7 @@ describe("pending user input question progress", () => {
questions,
{
scope: {
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
},
},
0,
@@ -180,7 +219,7 @@ describe("pending user input question progress", () => {
).toMatchObject({
questionIndex: 0,
activeQuestion: questions[0],
- selectedOptionLabel: "Orchestration-first",
+ selectedOptionLabels: ["Orchestration-first"],
customAnswer: "",
resolvedAnswer: "Orchestration-first",
answeredQuestionCount: 1,
@@ -189,4 +228,23 @@ describe("pending user input question progress", () => {
canAdvance: true,
});
});
+
+ it("treats multi-select questions as answered when they have selected options", () => {
+ expect(
+ derivePendingUserInputProgress(
+ [multiSelectQuestion],
+ {
+ areas: {
+ selectedOptionLabels: ["Server", "Web"],
+ },
+ },
+ 0,
+ ),
+ ).toMatchObject({
+ selectedOptionLabels: ["Server", "Web"],
+ resolvedAnswer: ["Server", "Web"],
+ canAdvance: true,
+ isComplete: true,
+ });
+ });
});
diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.ts
index 86e41285a..cdfc73cb8 100644
--- a/apps/web/src/pendingUserInput.ts
+++ b/apps/web/src/pendingUserInput.ts
@@ -1,7 +1,7 @@
import type { UserInputQuestion } from "@t3tools/contracts";
export interface PendingUserInputDraftAnswer {
- selectedOptionLabel?: string;
+ selectedOptionLabels?: string[];
customAnswer?: string;
}
@@ -9,9 +9,9 @@ export interface PendingUserInputProgress {
questionIndex: number;
activeQuestion: UserInputQuestion | null;
activeDraft: PendingUserInputDraftAnswer | undefined;
- selectedOptionLabel: string | undefined;
+ selectedOptionLabels: string[];
customAnswer: string;
- resolvedAnswer: string | null;
+ resolvedAnswer: string | string[] | null;
usingCustomAnswer: boolean;
answeredQuestionCount: number;
isLastQuestion: boolean;
@@ -28,38 +28,84 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
+function normalizeSelectedOptionLabels(value: string[] | undefined): string[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+
+ const normalized = value
+ .filter((entry): entry is string => typeof entry === "string")
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0);
+
+ return Array.from(new Set(normalized));
+}
+
export function resolvePendingUserInputAnswer(
+ question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
-): string | null {
+): string | string[] | null {
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
- return normalizeDraftAnswer(draft?.selectedOptionLabel);
+ const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
+ if (question.multiSelect) {
+ return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
+ }
+
+ return selectedOptionLabels[0] ?? null;
}
export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
- const selectedOptionLabel =
- customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
+ const selectedOptionLabels =
+ customAnswer.trim().length > 0
+ ? undefined
+ : normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
return {
customAnswer,
- ...(selectedOptionLabel ? { selectedOptionLabel } : {}),
+ ...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
+ };
+}
+
+export function togglePendingUserInputOptionSelection(
+ question: UserInputQuestion,
+ draft: PendingUserInputDraftAnswer | undefined,
+ optionLabel: string,
+): PendingUserInputDraftAnswer {
+ if (question.multiSelect) {
+ const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
+ const nextSelectedOptionLabels = selectedOptionLabels.includes(optionLabel)
+ ? selectedOptionLabels.filter((label) => label !== optionLabel)
+ : [...selectedOptionLabels, optionLabel];
+
+ return {
+ customAnswer: "",
+ ...(nextSelectedOptionLabels.length > 0
+ ? { selectedOptionLabels: nextSelectedOptionLabels }
+ : {}),
+ };
+ }
+
+ return {
+ customAnswer: "",
+ selectedOptionLabels: [optionLabel],
};
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
-): Record<string, string> | null {
- const answers: Record<string, string> = {};
+): Record<string, string | string[]> | null {
+ const answers: Record<string, string | string[]> = {};
for (const question of questions) {
- const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
+ const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
if (!answer) {
return null;
}
@@ -74,7 +120,7 @@ export function countAnsweredPendingUserInputQuestions(
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): number {
return questions.reduce((count, question) => {
- return resolvePendingUserInputAnswer(draftAnswers[question.id]) ? count + 1 : count;
+ return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) ? count + 1 : count;
}, 0);
}
@@ -83,7 +129,7 @@ export function findFirstUnansweredPendingUserInputQuestionIndex(
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): number {
const unansweredIndex = questions.findIndex(
- (question) => !resolvePendingUserInputAnswer(draftAnswers[question.id]),
+ (question) => !resolvePendingUserInputAnswer(question, draftAnswers[question.id]),
);
return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
@@ -98,7 +144,9 @@ export function derivePendingUserInputProgress(
questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
const activeQuestion = questions[normalizedQuestionIndex] ?? null;
const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
- const resolvedAnswer = resolvePendingUserInputAnswer(activeDraft);
+ const resolvedAnswer = activeQuestion
+ ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
+ : null;
const customAnswer = activeDraft?.customAnswer ?? "";
const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
const isLastQuestion =
@@ -108,7 +156,7 @@ export function derivePendingUserInputProgress(
questionIndex: normalizedQuestionIndex,
activeQuestion,
activeDraft,
- selectedOptionLabel: activeDraft?.selectedOptionLabel,
+ selectedOptionLabels: normalizeSelectedOptionLabels(activeDraft?.selectedOptionLabels),
customAnswer,
resolvedAnswer,
usingCustomAnswer: customAnswer.trim().length > 0,
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index 1c976a53c..a1234dff6 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -197,6 +197,7 @@ describe("derivePendingUserInputs", () => {
description: "Allow workspace writes only",
},
],
+ multiSelect: true,
},
],
},
@@ -233,6 +234,7 @@ describe("derivePendingUserInputs", () => {
description: "Continue execution",
},
],
+ multiSelect: false,
},
],
},
@@ -254,6 +256,7 @@ describe("derivePendingUserInputs", () => {
description: "Allow workspace writes only",
},
],
+ multiSelect: true,
},
],
},
@@ -281,6 +284,7 @@ describe("derivePendingUserInputs", () => {
description: "Allow workspace writes only",
},
],
+ multiSelect: false,
},
],
},
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index b818dc106..06bfee980 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -279,6 +279,7 @@ function parseUserInputQuestions(
header: question.header,
question: question.question,
options,
+ multiSelect: question.multiSelect === true,
};
})
.filter((question): question is UserInputQuestion => question !== null);