Merge pull request #10845 from uinstinct/cli-quiz

feat(cli): quiz answers
This commit is contained in:
Nate Sesti 2026-03-01 09:30:25 -08:00 • committed by GitHub
commit b70d69ff83
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 424 additions and 3 deletions

View file

@ -13,6 +13,7 @@ export function getDefaultToolPolicies(
{ tool: "MultiEdit", permission: "ask" },
{ tool: "Write", permission: "ask" },
{ tool: "AskQuestion", permission: "allow" },
{ tool: "Checklist", permission: "allow" },
{ tool: "Diff", permission: "allow" },
{ tool: "Exit", permission: "allow" }, // Exit tool is generally safe (headless mode only)
@ -46,6 +47,7 @@ export const PLAN_MODE_POLICIES: ToolPermissionPolicy[] = [
// TODO address bash read only concerns, maybe make permissions more granular
{ tool: "Bash", permission: "allow" },
{ tool: "AskQuestion", permission: "allow" },
{ tool: "Checklist", permission: "allow" },
{ tool: "Diff", permission: "allow" },
{ tool: "Exit", permission: "allow" },

View file

@ -0,0 +1,112 @@
import { EventEmitter } from "events";
/**Types */
export interface QuizQuestion {
question: string;
options?: string[];
defaultAnswer?: string;
}
export interface PendingQuestion extends QuizQuestion {
requestId: string;
timestamp: number;
}
export interface QuizAnswer {
requestId: string;
answer: string;
isCustomAnswer: boolean;
}
export interface QuizServiceState {
pendingQuestion: PendingQuestion | null;
}
export interface QuestionRequestedEvent {
requestId: string;
question: QuizQuestion;
}
export interface QuestionAnsweredEvent {
requestId: string;
answer: string;
isCustomAnswer: boolean;
}
/**Quiz service */
export class QuizService extends EventEmitter {
private pendingRequests = new Map<
string,
{
question: QuizQuestion;
resolve: (answer: string) => void;
}
>();
private currentState: QuizServiceState = {
pendingQuestion: null,
};
/**set a pending question to be answered and return a promise that resolves when the question is answered */
async askQuestion(question: QuizQuestion): Promise<string> {
const requestId = `quiz-${Date.now()}`;
return new Promise<string>((resolve) => {
const pendingQuestion: PendingQuestion = {
...question,
requestId,
timestamp: Date.now(),
};
this.pendingRequests.set(requestId, {
question,
resolve,
});
this.currentState.pendingQuestion = pendingQuestion;
const event: QuestionRequestedEvent = {
requestId,
question,
};
this.emit("questionRequested", event);
});
}
/**answer the pending question request and resolve the answer */
answerQuestion(
requestId: string,
answer: string,
isCustomAnswer = false,
): boolean {
const pending = this.pendingRequests.get(requestId);
if (!pending) {
return false;
}
this.pendingRequests.delete(requestId);
this.currentState.pendingQuestion = null;
const event: QuestionAnsweredEvent = {
requestId,
answer,
isCustomAnswer,
};
this.emit("questionAnswered", event);
pending.resolve(answer);
return true;
}
async initialize(): Promise<QuizServiceState> {
this.currentState = {
pendingQuestion: null,
};
this.pendingRequests.clear();
return this.currentState;
}
}
export const quizService = new QuizService();

View file

@ -17,6 +17,7 @@ import { FileIndexService } from "./FileIndexService.js";
import { GitAiIntegrationService } from "./GitAiIntegrationService.js";
import { MCPService } from "./MCPService.js";
import { ModelService } from "./ModelService.js";
import { quizService } from "./QuizService.js";
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { StorageSyncService } from "./StorageSyncService.js";
@ -325,6 +326,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.QUIZ,
() => quizService.initialize(),
[], // No dependencies
);
// Eagerly initialize all services to ensure they're ready when needed
// This avoids race conditions and "service not ready" errors
await serviceContainer.initializeAll();
@ -389,6 +396,7 @@ export const services = {
artifactUpload: artifactUploadService,
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobService,
quiz: quizService,
} as const;
export type ServicesType = typeof services;

View file

@ -158,6 +158,7 @@ export const SERVICE_NAMES = {
ARTIFACT_UPLOAD: "artifactUpload",
GIT_AI_INTEGRATION: "gitAiIntegration",
BACKGROUND_JOBS: "backgroundJobs",
QUIZ: "quiz",
} as const;
/**

View file

@ -1,5 +1,6 @@
import { SUBAGENT_TOOL_META } from "../subagent/index.js";
import { askQuestionTool } from "./askQuestion.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
@ -18,6 +19,7 @@ import { writeFileTool } from "./writeFile.js";
// putting in here for circular import issue
export const ALL_BUILT_IN_TOOLS = [
askQuestionTool,
editTool,
exitTool,
fetchTool,

View file

@ -0,0 +1,61 @@
import { quizService } from "../services/QuizService.js";
import { Tool } from "./types.js";
export const askQuestionTool: Tool = {
name: "AskQuestion",
displayName: "Ask Question",
description: `Ask the user a clarifying question to gather requirements, preferences, or implementation details before proceeding.
Guidelines:
- You should use this tool **whenever you want to clarify your assumption or need answers to build your plan**.
- DO NOT supply "other" or "none of the above" or similar as an option. User can always provide a free-form answer when needed.
`,
parameters: {
type: "object",
required: ["question", "options"],
properties: {
question: {
type: "string",
description: "The question to ask the user",
},
options: {
type: "array",
description:
"The list of choices. Leave as empty array if user should provide a free-form answer.",
items: {
type: "string",
},
},
defaultAnswer: {
type: "string",
description:
"Default answer if user presses Enter without providing input",
},
},
},
readonly: true,
isBuiltIn: true,
run: async (args: {
question: string;
options?: string[];
defaultAnswer?: string;
}): Promise<string> => {
const { question, options, defaultAnswer } = args;
const answer = await quizService.askQuestion({
question,
options,
defaultAnswer,
});
if (options && options.length > 0) {
const selectedIndex = options.indexOf(answer);
if (selectedIndex !== -1) {
return `User selected option ${selectedIndex + 1}: "${answer}"`;
}
return `User provided custom answer: "${answer}"`;
}
return `User answered: "${answer}"`;
},
};

View file

@ -6,6 +6,7 @@
* When adding a new built-in tool, update both this list and ALL_BUILT_IN_TOOLS in allBuiltIns.ts.
*/
export const BUILT_IN_TOOL_NAMES = [
"AskQuestion",
"Edit",
"Exit",
"Fetch",

View file

@ -19,6 +19,7 @@ import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";
import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js";
import { askQuestionTool } from "./askQuestion.js";
import { checkBackgroundJobTool } from "./checkBackgroundJob.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
@ -70,6 +71,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [
fetchTool,
writeChecklistTool,
checkBackgroundJobTool,
askQuestionTool,
];
const BUILTIN_SEARCH_TOOLS: Tool[] = [searchCodeTool];

View file

@ -184,6 +184,7 @@ function useChatHandlers(
};
}
// eslint-disable-next-line complexity
const TUIChat: React.FC<TUIChatProps> = ({
remoteUrl,
configPath,
@ -261,6 +262,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
compactionStartTime,
inputMode,
activePermissionRequest,
activeQuizQuestion,
wasInterrupted,
queuedMessages,
handleUserMessage,
@ -269,6 +271,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
resetChatHistory,
handleEditMessage,
handleToolPermissionResponse,
handleQuizAnswer,
} = useChat({
assistant: services.config?.config || undefined,
model: services.model?.model || undefined,
@ -332,7 +335,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
// Determine if input should be disabled
// Allow input even when services are loading, but disable for UI overlays
const isInputDisabled =
navState.currentScreen !== "chat" || !!activePermissionRequest;
navState.currentScreen !== "chat" ||
!!activePermissionRequest ||
!!activeQuizQuestion;
// Check if verbose mode is enabled for resource debugging
const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []);
@ -430,7 +435,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
handleReload={handleReload}
closeCurrentScreen={closeCurrentScreen}
activePermissionRequest={activePermissionRequest}
activeQuizQuestion={activeQuizQuestion}
handleToolPermissionResponse={handleToolPermissionResponse}
handleQuizAnswer={handleQuizAnswer}
handleUserMessage={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
isCompacting={isCompacting}

View file

@ -1,19 +1,25 @@
import type { AssistantConfig } from "@continuedev/sdk";
import React from "react";
import type { ActivePermissionRequest } from "../hooks/useChat.types.js";
import type {
ActivePermissionRequest,
ActiveQuizQuestion,
} from "../hooks/useChat.types.js";
import { UserInput } from "../UserInput.js";
import { QuizPrompt } from "./QuizPrompt.js";
import { ToolPermissionSelector } from "./ToolPermissionSelector.js";
interface ChatScreenContentProps {
activePermissionRequest: ActivePermissionRequest | null;
activeQuizQuestion: ActiveQuizQuestion | null;
handleToolPermissionResponse: (
requestId: string,
approved: boolean,
createPolicy?: boolean,
stopStream?: boolean,
) => void;
handleQuizAnswer: (requestId: string, answer: string) => void;
handleUserMessage: (message: string, imageMap?: Map<string, Buffer>) => void;
isWaitingForResponse: boolean;
isCompacting: boolean;
@ -30,7 +36,9 @@ interface ChatScreenContentProps {
export const ChatScreenContent: React.FC<ChatScreenContentProps> = ({
activePermissionRequest,
activeQuizQuestion,
handleToolPermissionResponse,
handleQuizAnswer,
handleUserMessage,
isWaitingForResponse,
isCompacting,
@ -44,6 +52,18 @@ export const ChatScreenContent: React.FC<ChatScreenContentProps> = ({
onImageInClipboardChange,
onShowEditSelector,
}) => {
if (activeQuizQuestion) {
return (
<QuizPrompt
question={activeQuizQuestion.question.question}
options={activeQuizQuestion.question.options}
defaultAnswer={activeQuizQuestion.question.defaultAnswer}
requestId={activeQuizQuestion.requestId}
onAnswer={handleQuizAnswer}
/>
);
}
if (activePermissionRequest) {
return (
<ToolPermissionSelector

View file

@ -0,0 +1,162 @@
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
import { defaultBoxStyles } from "../styles.js";
interface QuizPromptProps {
question: string;
options?: string[];
defaultAnswer?: string;
requestId: string;
onAnswer: (
requestId: string,
answer: string,
isCustomAnswer: boolean,
) => void;
}
/**Quiz prompt component for answering for the AskQuestion tool and QuizService */
export const QuizPrompt: React.FC<QuizPromptProps> = ({
question,
options: rawOptions,
defaultAnswer,
requestId,
onAnswer,
}) => {
const options = Array.isArray(rawOptions) ? rawOptions : undefined;
const [selectedIndex, setSelectedIndex] = useState(0);
const [isCustomMode, setIsCustomMode] = useState(
!options || options.length === 0,
); // allows typing out an answer even when there are options
const [customInput, setCustomInput] = useState("");
const [submitted, setSubmitted] = useState(false);
const hasOptions = options && options.length > 0;
useInput((input, key) => {
if (submitted) return;
if (isCustomMode) {
// submit the typed answer
if (key.return) {
const answer = customInput.trim() || defaultAnswer || "";
if (answer) {
setSubmitted(true);
onAnswer(requestId, answer, true);
}
return;
}
if (key.backspace || key.delete) {
setCustomInput((prev) => prev.slice(0, -1));
return;
}
if (hasOptions && key.upArrow && customInput === "") {
// exit out of typing a custom answer
setIsCustomMode(false);
setSelectedIndex(options.length - 1);
return;
}
if (input && !key.ctrl && !key.meta) {
// handle typing a custom answer
setCustomInput((prev) => prev + input);
}
return;
}
if (key.return) {
// submit the selected option
if (hasOptions && options[selectedIndex]) {
setSubmitted(true);
onAnswer(requestId, options[selectedIndex], false);
}
return;
}
// navigate between options
if (key.upArrow) {
setSelectedIndex((prev) =>
prev === 0 ? (hasOptions ? options.length - 1 : 0) : prev - 1,
);
} else if (key.downArrow) {
if (hasOptions) {
if (selectedIndex === options.length - 1) {
setIsCustomMode(true);
setSelectedIndex(0);
} else {
setSelectedIndex((prev) =>
prev === options.length - 1 ? 0 : prev + 1,
);
}
}
}
if (input && !key.ctrl && !key.meta && !key.upArrow && !key.downArrow) {
setIsCustomMode(true);
setCustomInput(input);
}
});
if (submitted) {
return null;
}
return (
<Box {...defaultBoxStyles("magenta")} marginBottom={1}>
<Box marginBottom={1}>
<Text color="magenta" bold>
?{" "}
</Text>
<Text bold>{question}</Text>
</Box>
{hasOptions && !isCustomMode && (
<Box flexDirection="column" marginLeft={2}>
{options.map((option, index) => {
const isSelected = index === selectedIndex;
return (
<Box key={index}>
<Text color={isSelected ? "cyan" : "white"} bold={isSelected}>
{isSelected ? "❯ " : " "}
{option}
</Text>
</Box>
);
})}
<Box>
<Text color="gray" dimColor>
{" "}(or start typing for custom answer)
</Text>
</Box>
</Box>
)}
{isCustomMode && (
<Box marginLeft={2} flexDirection="column">
<Box>
<Text color="cyan">❯ </Text>
<Text>{customInput}</Text>
<Text color="gray">▊</Text>
</Box>
{defaultAnswer && !customInput && (
<Box marginTop={1}>
<Text color="gray" dimColor>
(Press Enter for default: {defaultAnswer})
</Text>
</Box>
)}
</Box>
)}
<Box marginTop={1}>
<Text color="gray" dimColor>
{hasOptions && !isCustomMode
? "↑/↓ navigate, Enter select"
: "Type answer, Enter submit"}
</Text>
</Box>
</Box>
);
};

View file

@ -9,7 +9,10 @@ import type { NavigationScreen } from "../context/NavigationContext.js";
import { DiffViewer } from "../DiffViewer.js";
import { EditMessageSelector } from "../EditMessageSelector.js";
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
import type { ActivePermissionRequest } from "../hooks/useChat.types.js";
import type {
ActivePermissionRequest,
ActiveQuizQuestion,
} from "../hooks/useChat.types.js";
import { JobsSelector } from "../JobsSelector.js";
import { MCPSelector } from "../MCPSelector.js";
import { ModelSelector } from "../ModelSelector.js";
@ -31,12 +34,14 @@ interface ScreenContentProps {
handleReload: () => Promise<void>;
closeCurrentScreen: () => void;
activePermissionRequest: ActivePermissionRequest | null;
activeQuizQuestion: ActiveQuizQuestion | null;
handleToolPermissionResponse: (
requestId: string,
approved: boolean,
createPolicy?: boolean,
stopStream?: boolean,
) => void;
handleQuizAnswer: (requestId: string, answer: string) => void;
handleUserMessage: (message: string, imageMap?: Map<string, Buffer>) => void;
isWaitingForResponse: boolean;
isCompacting: boolean;
@ -72,7 +77,9 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
handleReload,
closeCurrentScreen,
activePermissionRequest,
activeQuizQuestion,
handleToolPermissionResponse,
handleQuizAnswer,
handleUserMessage,
isWaitingForResponse,
isCompacting,
@ -198,7 +205,9 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
return (
<ChatScreenContent
activePermissionRequest={activePermissionRequest}
activeQuizQuestion={activeQuizQuestion}
handleToolPermissionResponse={handleToolPermissionResponse}
handleQuizAnswer={handleQuizAnswer}
handleUserMessage={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
isCompacting={isCompacting}

View file

@ -40,6 +40,7 @@ import {
} from "./useChat.stream.helpers.js";
import {
ActivePermissionRequest,
ActiveQuizQuestion,
AttachedFile,
UseChatProps,
} from "./useChat.types.js";
@ -168,6 +169,8 @@ export function useChat({
const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]);
const [activePermissionRequest, setActivePermissionRequest] =
useState<ActivePermissionRequest | null>(null);
const [activeQuizQuestion, setActiveQuizQuestion] =
useState<ActiveQuizQuestion | null>(null);
const [compactionIndex, setCompactionIndex] = useState<number | null>(() => {
// When resuming or forking, check for compaction markers in the loaded history
if ((resume || fork) && currentSession.history.length > 0) {
@ -195,6 +198,27 @@ export function useChat({
};
}, []);
// Set up quiz service listeners
useEffect(() => {
const quizSvc = services.quiz;
const onQuestionRequested = (pending: ActiveQuizQuestion) => {
setActiveQuizQuestion(pending);
};
const onQuestionAnswered = () => {
setActiveQuizQuestion(null);
};
quizSvc.on("questionRequested", onQuestionRequested);
quizSvc.on("questionAnswered", onQuestionAnswered);
return () => {
quizSvc.off("questionRequested", onQuestionRequested);
quizSvc.off("questionAnswered", onQuestionAnswered);
};
}, []);
// Clean up abort controller on unmount
useEffect(() => {
return () => {
@ -829,6 +853,11 @@ export function useChat({
}
};
const handleQuizAnswer = (requestId: string, answer: string) => {
setActiveQuizQuestion(null);
services.quiz.answerQuestion(requestId, answer);
};
return {
chatHistory,
setChatHistory: setChatHistory,
@ -839,6 +868,7 @@ export function useChat({
inputMode,
attachedFiles,
activePermissionRequest,
activeQuizQuestion,
wasInterrupted,
queuedMessages,
handleUserMessage,
@ -847,5 +877,6 @@ export function useChat({
resetChatHistory,
handleEditMessage,
handleToolPermissionResponse,
handleQuizAnswer,
};
}

View file

@ -2,6 +2,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { Session } from "core/index.js";
import { QuestionRequestedEvent } from "../../services/QuizService.js";
import { ToolCallPreview } from "../../tools/types.js";
export interface UseChatProps {
@ -42,6 +43,8 @@ export interface ActivePermissionRequest {
hasDynamicEvaluation?: boolean;
}
export type ActiveQuizQuestion = QuestionRequestedEvent;
export interface RemoteServerState {
session: Session;
isProcessing: boolean;