All files / client/src/hooks use-tutor.ts

86.58% Statements 213/246
77.01% Branches 124/161
90.9% Functions 40/44
93.96% Lines 187/199

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529                                                                                                      4x         2x                     2x       4x                 2x   2x       2x   1x   2x                           9x 9x 9x 9x 9x       21x 1x             21x 21x 16x       2x               7x         7x 1x   6x               7x                               98x       5x                             7x       7x     7x                 18x 18x 18x 2x 2x             5x 5x                 118x 118x 22x 18x 22x     118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 40x 40x     118x 22x 22x 22x 22x 22x 22x 22x     118x   118x 18x 16x 16x   13x 13x     12x 12x       4x 16x 16x       118x 11x 11x 11x     118x   118x 7x 6x 6x         6x 6x 6x 6x 6x             6x 6x 6x 6x 6x 6x             6x 6x       118x 13x 13x 13x       13x 1x 1x   12x 12x   12x 12x 12x 12x 12x                             12x 12x 11x 11x 11x 11x 11x 11x   1x 1x   12x 12x       118x 2x 2x 2x 2x 2x 2x     118x 14x 13x 1x 1x 1x   12x     118x 10x 9x 9x           9x       9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x                               8x 8x 7x 7x 7x 7x 7x 4x   7x 7x 7x 7x       2x 1x   9x 9x       118x 5x 5x 5x 5x     118x 46x 46x 5x 6x         118x                                                                                                        
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  type TutorDialogTurn,
  calculateNextTutorDifficulty,
  clampTutorDifficulty,
  TUTOR_CONFIGURED_DIFFICULTY_STORAGE_KEY,
  TUTOR_DEFAULT_DIFFICULTY,
  tutorDifficultySchema,
  tutorModelsResponseSchema,
  tutorResponseSchema,
  type TutorAnswerRating,
  type TutorDifficulty,
  type TutorResponse,
  type TutorCourseContentContext,
} from "@shared/tutor";
import { INPUT_LIMITS } from "@shared/input-limits";
import { getServerCapabilities, type ServerCapabilities } from "@/lib/server-capabilities";
import { refreshExternalExamplesCatalog, useExternalExamples } from "@/lib/external-examples";
 
interface TutorConfig {
  readonly provider: string;
}
 
export interface TutorPanelState {
  readonly capabilities: ServerCapabilities;
  readonly config: TutorConfig;
  readonly credential: string;
  readonly setCredential: (value: string) => void;
  readonly clearCredential: () => void;
  readonly selectedModel: string;
  readonly setSelectedModel: (value: string) => void;
  readonly lastUsedModel: string | null;
  readonly configuredDifficulty: TutorDifficulty;
  readonly effectiveDifficulty: TutorDifficulty;
  readonly setConfiguredDifficulty: (value: number) => void;
  readonly sessionRating: number | null;
  readonly ratedAnswerCount: number;
  readonly availableModels: readonly string[];
  readonly modelsLoading: boolean;
  readonly loadModels: () => Promise<void>;
  readonly question: TutorResponse | null;
  readonly history: readonly TutorDialogTurn[];
  readonly answer: string;
  readonly setAnswer: (value: string) => void;
  readonly submitAnswer: (code: string) => Promise<void>;
  readonly resetDialog: () => void;
  readonly isLoading: boolean;
  readonly error: string | null;
  readonly generateQuestion: (code: string) => Promise<void>;
}
 
const DEFAULT_CONFIG: TutorConfig = {
  provider: "kiconnect",
};
 
function getErrorMessage(body: unknown): string {
  const errorMessages = new Map<string, string>([
    ["CREDENTIAL_REQUIRED", "Enter your personal Tutor API key first."],
    ["CREDENTIAL_INVALID", "The Tutor access was rejected."],
    ["PROVIDER_UNAVAILABLE", "The Tutor service is currently unavailable."],
    ["PROVIDER_TIMEOUT", "The Tutor service took too long to respond."],
    ["RATE_LIMITED", "The Tutor request limit has been reached. Please try again later."],
    ["MODEL_UNAVAILABLE", "The selected Tutor model is unavailable."],
    ["INVALID_PROVIDER_RESPONSE", "The Tutor service returned an invalid response."],
    ["INVALID_REQUEST", "The Tutor request is invalid."],
    ["COURSE_CONTENT_STALE", "The course content was updated. Reload the example from the Examples menu to continue."],
  ]);
  return errorMessages.get(getErrorCode(body) ?? "") ?? "The Tutor request failed.";
}
 
function getErrorCode(body: unknown): string | undefined {
  if (
    typeof body === "object" &&
    body !== null &&
    "error" in body &&
    typeof body.error === "object" &&
    body.error !== null &&
    "code" in body.error &&
    typeof body.error.code === "string"
  ) {
    return body.error.code;
  }
  return undefined;
}
 
function getTutorFailure(body: unknown): Error {
  if (getErrorCode(body) === "COURSE_CONTENT_STALE") {
    // The server moved on to a newer Course revision; refresh the catalog so the Examples menu offers it.
    refreshExternalExamplesCatalog().catch(() => undefined);
  }
  return new Error(getErrorMessage(body));
}
 
function getSubmitAnswerValidationError({
  question,
  code,
  answer,
  credential,
}: {
  question: TutorResponse | null;
  code: string;
  answer: string;
  credential: string;
}): string | undefined {
  Iif (!question) return "Generate a learning question first.";
  Iif (!code.trim()) return "Open a sketch with source code first.";
  Iif (!answer.trim()) return "Write an answer first.";
  Iif (!credential.trim()) return "Enter your personal Tutor API key first.";
  return undefined;
}
 
function getRequestedModel(selectedModel: string, availableModels: readonly string[]): string | undefined {
  if (selectedModel === "auto") return undefined;
  return availableModels.includes(selectedModel) ? selectedModel : undefined;
}
 
function getCourseContentRequest(
  courseContentSession: string | undefined,
  courseContent: TutorCourseContentContext | undefined,
): { courseContentSession?: string; courseContent?: TutorCourseContentContext } {
  Iif (courseContentSession) return { courseContentSession };
  if (courseContent) return { courseContent };
  return {};
}
 
function isAbortError(error: unknown): boolean {
  return error instanceof Error && error.name === "AbortError";
}
 
function buildDialogTurn(
  question: string,
  answer: string,
  response: TutorResponse,
): TutorDialogTurn {
  const baseTurn = {
    question,
    answer,
    ...buildDialogTurnMetadata(response),
  };
  if (response.responseStyle === "philosophical") {
    return { ...baseTurn, responseStyle: "philosophical" };
  }
  return {
    ...baseTurn,
    responseStyle: "normal",
    ...(response.answerRating === undefined ? {} : { answerRating: response.answerRating }),
  };
}
 
function buildDialogTurnMetadata(response: TutorResponse): Partial<Omit<TutorDialogTurn, "question" | "answer" | "responseStyle" | "answerRating">> {
  const fields = [
    ["feedback", response.feedback],
    ["topicId", response.topicId],
    ["conceptId", response.conceptId],
    ["questionId", response.questionId],
    ["indicatorId", response.indicatorId],
    ["questionKind", response.questionKind],
    ["strategyId", response.strategyId],
    ["strategySource", response.strategySource],
    ["contentRevision", response.contentRevision],
    ["learningPhase", response.learningPhase],
    ["activeTopicId", response.activeTopicId],
    ["masteredTopicIds", response.masteredTopicIds],
    ["progressionBlockedReason", response.progressionBlockedReason],
    ["extensionTargetTopicId", response.extensionTargetTopicId],
  ] as const;
  return Object.fromEntries(fields.filter(([, value]) => value !== undefined && value !== "")) as Partial<Omit<TutorDialogTurn, "question" | "answer" | "responseStyle" | "answerRating">>;
}
 
function collectAnswerRatings(history: readonly TutorDialogTurn[]): readonly TutorAnswerRating[] {
  return history.flatMap((turn) => turn.answerRating === undefined ? [] : [turn.answerRating]);
}
 
function buildDialogResponseUpdate(
  currentHistory: readonly TutorDialogTurn[],
  currentQuestion: string,
  submittedAnswer: string,
  response: TutorResponse,
  currentSession: string | undefined,
): {
  readonly nextHistory: readonly TutorDialogTurn[];
  readonly answerRatings?: readonly TutorAnswerRating[];
  readonly nextSession?: string;
  readonly lastUsedModel?: string;
} {
  const nextHistory = [
    ...currentHistory,
    buildDialogTurn(currentQuestion, submittedAnswer, response),
  ].slice(-INPUT_LIMITS.tutor.maxHistoryEntries);
  const answerRatings = response.responseStyle === "normal" && response.answerRating !== undefined
    ? collectAnswerRatings(nextHistory)
    : undefined;
  return {
    nextHistory,
    ...(answerRatings === undefined ? {} : { answerRatings }),
    nextSession: response.courseContentSession ?? currentSession,
    ...(response.responseStyle === "normal" ? { lastUsedModel: response.model } : {}),
  };
}
 
function readConfiguredDifficulty(): TutorDifficulty {
  try {
    const stored = globalThis.localStorage?.getItem(TUTOR_CONFIGURED_DIFFICULTY_STORAGE_KEY);
    if (stored === null || stored === undefined) return TUTOR_DEFAULT_DIFFICULTY;
    const parsed = tutorDifficultySchema.safeParse(Number(stored));
    return parsed.success ? parsed.data : TUTOR_DEFAULT_DIFFICULTY;
  } catch {
    return TUTOR_DEFAULT_DIFFICULTY;
  }
}
 
function persistConfiguredDifficulty(value: TutorDifficulty): void {
  try {
    globalThis.localStorage?.setItem(TUTOR_CONFIGURED_DIFFICULTY_STORAGE_KEY, String(value));
  } catch {
    // Browser storage can be unavailable in private/restricted contexts.
  }
}
 
export function useTutor(
  capabilities: ServerCapabilities = getServerCapabilities(true),
): TutorPanelState {
  const externalExamples = useExternalExamples();
  const courseContent = useMemo<TutorCourseContentContext | undefined>(() => {
    if (externalExamples.activeCourseContent) return externalExamples.activeCourseContent;
    const source = externalExamples.catalog?.source;
    if (source?.mode !== "repository-ref" || !source.repository || !source.ref || !source.revision) return undefined;
    return { repository: source.repository, ref: source.ref, revision: source.revision };
  }, [externalExamples.activeCourseContent, externalExamples.catalog]);
  const courseContentKey = JSON.stringify(courseContent ?? null);
  const [courseContentSession, setCourseContentSession] = useState<string | undefined>();
  const [config, setConfig] = useState<TutorConfig>(DEFAULT_CONFIG);
  const [credential, setCredential] = useState("");
  const [selectedModel, setSelectedModel] = useState("auto");
  const [lastUsedModel, setLastUsedModel] = useState<string | null>(null);
  const [configuredDifficulty, setConfiguredDifficulty] = useState<TutorDifficulty>(readConfiguredDifficulty);
  const [effectiveDifficulty, setEffectiveDifficulty] = useState<TutorDifficulty>(() => configuredDifficulty);
  const [availableModels, setAvailableModels] = useState<readonly string[]>([]);
  const [modelsLoading, setModelsLoading] = useState(false);
  const [question, setQuestion] = useState<TutorResponse | null>(null);
  const [history, setHistory] = useState<readonly TutorDialogTurn[]>([]);
  const [answer, setAnswer] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const canLoadConfigOnMount = useRef(capabilities.canUseTutor);
  const activeTutorRequests = useRef(new Set<AbortController>());
  const abortPendingTutorRequests = useCallback(() => {
    for (const controller of activeTutorRequests.current) controller.abort();
    activeTutorRequests.current.clear();
  }, []);
 
  useEffect(() => {
    abortPendingTutorRequests();
    setCourseContentSession(undefined);
    setHistory([]);
    setQuestion(null);
    setAnswer("");
    setError(null);
    setEffectiveDifficulty(configuredDifficulty);
  }, [abortPendingTutorRequests, courseContentKey]);
 
  useEffect(() => () => abortPendingTutorRequests(), [abortPendingTutorRequests]);
 
  useEffect(() => {
    if (!canLoadConfigOnMount.current) return;
    let cancelled = false;
    fetch("/api/config", { cache: "no-store", credentials: "include" })
      .then(async (response) => {
        Iif (!response.ok) throw new Error("Tutor configuration is unavailable.");
        return response.json() as Promise<{ tutor?: Partial<TutorConfig> }>;
      })
      .then((data) => {
        Iif (cancelled || !data.tutor) return;
        setConfig({
          provider: data.tutor.provider ?? DEFAULT_CONFIG.provider,
        });
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, []);
 
  const setTutorCredential = useCallback((value: string) => {
    setCredential(value);
    setAvailableModels([]);
    setSelectedModel("auto");
  }, []);
 
  const clearCredential = useCallback(() => setTutorCredential(""), [setTutorCredential]);
 
  const loadModels = useCallback(async () => {
    if (!capabilities.canUseTutor) return;
    setError(null);
    Iif (!credential.trim()) {
      setError("Enter your personal Tutor API key first.");
      return;
    }
 
    setModelsLoading(true);
    const controller = new AbortController();
    activeTutorRequests.current.add(controller);
    try {
      const response = await fetch("/api/tutor/models", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ credential }),
        signal: controller.signal,
      });
      const body: unknown = await response.json().catch(() => null);
      Iif (!response.ok) throw new Error(getErrorMessage(body));
      const parsed = tutorModelsResponseSchema.safeParse(body);
      Iif (!parsed.success) throw new Error("The Tutor service returned an invalid model list.");
      setAvailableModels(parsed.data.models);
      setSelectedModel((current) => current === "auto" || parsed.data.models.includes(current) ? current : "auto");
    } catch (requestError) {
      if (controller.signal.aborted || isAbortError(requestError)) return;
      setAvailableModels([]);
      setSelectedModel("auto");
      setError(requestError instanceof Error ? requestError.message : "The Tutor models could not be loaded.");
    } finally {
      activeTutorRequests.current.delete(controller);
      setModelsLoading(false);
    }
  }, [capabilities, credential]);
 
  const requestQuestion = useCallback(async (code: string, requestDifficulty: TutorDifficulty, freshSession = false) => {
    Iif (!capabilities.canUseTutor) return;
    setError(null);
    Iif (!code.trim()) {
      setError("Open a sketch with source code first.");
      return;
    }
    if (!credential.trim()) {
      setError("Enter your personal Tutor API key first.");
      return;
    }
    const requestedModel = getRequestedModel(selectedModel, availableModels);
    Iif (selectedModel !== "auto" && !requestedModel) setSelectedModel("auto");
 
    setIsLoading(true);
    const controller = new AbortController();
    activeTutorRequests.current.add(controller);
    try {
      const response = await fetch("/api/tutor/question", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        signal: controller.signal,
        body: JSON.stringify({
          code,
          credential,
          ...(requestedModel ? { model: requestedModel } : {}),
          difficulty: requestDifficulty,
          // A new learning question starts a fresh didactic session (LearningQuestions SSOT 2.3); the
          // reset state of resetDialog is not visible to this callback yet.
          ...getCourseContentRequest(freshSession ? undefined : courseContentSession, courseContent),
        }),
      });
      const body: unknown = await response.json().catch(() => null);
      if (!response.ok) throw getTutorFailure(body);
      const parsed = tutorResponseSchema.safeParse(body);
      Iif (!parsed.success) throw new Error("The Tutor service returned an invalid response.");
      setQuestion(parsed.data);
      setCourseContentSession(parsed.data.courseContentSession);
      setLastUsedModel(parsed.data.model);
      setAnswer("");
    } catch (requestError) {
      Iif (controller.signal.aborted || isAbortError(requestError)) return;
      setError(requestError instanceof Error ? requestError.message : "The Tutor request failed.");
    } finally {
      activeTutorRequests.current.delete(controller);
      setIsLoading(false);
    }
  }, [availableModels, capabilities, courseContent, courseContentSession, credential, selectedModel]);
 
  const resetDialog = useCallback(() => {
    setHistory([]);
    setQuestion(null);
    setAnswer("");
    setError(null);
    setEffectiveDifficulty(configuredDifficulty);
    setCourseContentSession(undefined);
  }, [configuredDifficulty]);
 
  const generateQuestion = useCallback(async (code: string) => {
    if (!capabilities.canUseTutor) return;
    if (question !== null || history.length > 0) {
      resetDialog();
      await requestQuestion(code, configuredDifficulty, true);
      return;
    }
    await requestQuestion(code, effectiveDifficulty);
  }, [capabilities, configuredDifficulty, effectiveDifficulty, history.length, question, requestQuestion, resetDialog]);
 
  const submitAnswer = useCallback(async (code: string) => {
    if (!capabilities.canUseTutor) return;
    setError(null);
    const validationError = getSubmitAnswerValidationError({
      question,
      code,
      answer,
      credential,
    });
    Iif (validationError) {
      setError(validationError);
      return;
    }
    Iif (!question) return;
    const requestedModel = getRequestedModel(selectedModel, availableModels);
    Iif (selectedModel !== "auto" && !requestedModel) setSelectedModel("auto");
    const submittedAnswer = answer.trim();
    const currentQuestion = question.question;
    const currentHistory = history;
 
    setIsLoading(true);
    const controller = new AbortController();
    activeTutorRequests.current.add(controller);
    try {
      const response = await fetch("/api/tutor/dialog", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        signal: controller.signal,
        body: JSON.stringify({
          code,
          history: currentHistory,
          question: currentQuestion,
          answer: submittedAnswer,
          credential,
          ...(requestedModel ? { model: requestedModel } : {}),
          difficulty: effectiveDifficulty,
          ...getCourseContentRequest(courseContentSession, courseContent),
        }),
      });
      const body: unknown = await response.json().catch(() => null);
      if (!response.ok) throw getTutorFailure(body);
      const parsed = tutorResponseSchema.safeParse(body);
      Iif (!parsed.success) throw new Error("The Tutor service returned an invalid response.");
      const update = buildDialogResponseUpdate(currentHistory, currentQuestion, submittedAnswer, parsed.data, courseContentSession);
      setHistory(update.nextHistory);
      if (update.answerRatings !== undefined) {
        setEffectiveDifficulty((current) => calculateNextTutorDifficulty(current, update.answerRatings!));
      }
      setQuestion(parsed.data);
      setCourseContentSession(update.nextSession);
      if (update.lastUsedModel !== undefined) setLastUsedModel(update.lastUsedModel);
      setAnswer("");
    } catch (requestError) {
      // Keep the current question, answer, and history intact so a failed
      // request can be retried deliberately by the learner.
      if (controller.signal.aborted || isAbortError(requestError)) return;
      setError(requestError instanceof Error ? requestError.message : "The Tutor request failed.");
    } finally {
      activeTutorRequests.current.delete(controller);
      setIsLoading(false);
    }
  }, [answer, availableModels, capabilities, courseContent, courseContentSession, credential, effectiveDifficulty, history, question, selectedModel]);
 
  const updateConfiguredDifficulty = useCallback((value: number) => {
    const nextDifficulty = clampTutorDifficulty(value);
    setConfiguredDifficulty(nextDifficulty);
    persistConfiguredDifficulty(nextDifficulty);
    Eif (history.length === 0 && question === null) setEffectiveDifficulty(nextDifficulty);
  }, [history.length, question]);
 
  const { sessionRating, ratedAnswerCount } = useMemo(() => {
    const ratings = history.flatMap((turn) => turn.answerRating === undefined ? [] : [turn.answerRating]);
    if (ratings.length === 0) return { sessionRating: null, ratedAnswerCount: 0 };
    return {
      sessionRating: ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length,
      ratedAnswerCount: ratings.length,
    };
  }, [history]);
 
  return useMemo(() => ({
    capabilities,
    config,
    credential,
    setCredential: setTutorCredential,
    clearCredential,
    selectedModel,
    setSelectedModel,
    lastUsedModel,
    configuredDifficulty,
    effectiveDifficulty,
    setConfiguredDifficulty: updateConfiguredDifficulty,
    sessionRating,
    ratedAnswerCount,
    availableModels,
    modelsLoading,
    loadModels,
    question,
    history,
    answer,
    setAnswer,
    submitAnswer,
    resetDialog,
    isLoading,
    error,
    generateQuestion,
  }), [
    capabilities,
    config,
    credential,
    clearCredential,
    error,
    generateQuestion,
    loadModels,
    isLoading,
    modelsLoading,
    question,
    history,
    answer,
    submitAnswer,
    resetDialog,
    selectedModel,
    setTutorCredential,
    availableModels,
    lastUsedModel,
    configuredDifficulty,
    effectiveDifficulty,
    updateConfiguredDifficulty,
    sessionRating,
    ratedAnswerCount,
  ]);
}