Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

9.8 KB
Raw Blame
"use client";

import { masterySessionRoute as existingMasterySessionRoute } from "@/lib/learning-routes";

import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";

import {
  useChatStateAdapter,
  type SessionConfiguration,
} from "@/features/chat/ChatStateAdapter";
import { MASTERY_CAPABILITY_VALUE } from "@/features/capabilities/presentation";
import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";
import {
  fetchMasteryTopic,
  fetchMasteryTopicSessions,
  type MasteryTopic,
} from "@/lib/learning-api";
import {
  isMasteryDraftSessionReady,
  isMasteryDraftSendReady,
  type MasteryDraftRouteGuard,
} from "@/lib/mastery-study-route";
import type { MasteryMode } from "@/lib/mastery-mode";
import { MASTERY_WORKSPACE_MODE } from "@/lib/workspace-mode";

/**
 * Resolves which topic and which chat session a study route is showing.
 *
 * Route → session is a small state machine: a bare `/sessions` route opens a
 * draft and rewrites the URL once the session exists, while a route that
 * names a session must first prove that session belongs to this topic. Both
 * paths key their bookkeeping on the route so a fast topic switch can never
 * apply a stale answer to the wrong screen.
 */
export function useMasteryStudySession(
  pathId: string,
  routeSessionId?: string,
  /**
   * What a conversation opened on this route is for. Only meaningful for a
   * new one: an existing conversation's kind was decided when it was opened
   * and is read back from the server, because letting a URL restate it would
   * let a link hand a session tools its kind withholds.
   */
  requestedMode: MasteryMode = "study",
) {
  const router = useRouter();
  const { t } = useTranslation();
  const {
    state,
    newSession,
    configureSession,
    loadSession,
    showCachedSession,
  } = useChatStateAdapter();

  const [topic, setTopic] = useState<MasteryTopic | null>(null);
  const [topicError, setTopicError] = useState<string | null>(null);
  const currentRouteKey = `${pathId}:${routeSessionId || "new"}`;
  const [sessionResolution, setSessionResolution] = useState<{
    routeKey: string;
    error: string | null;
  } | null>(null);
  const [draftBinding, setDraftBinding] = useState<{
    routeKey: string;
    draftKey: string;
    previousSessionId: string | null;
  } | null>(null);
  const initializedRouteRef = useRef("");
  const sessionLoadRef = useRef<AbortController | null>(null);
  const draftRouteGuardRef = useRef<MasteryDraftRouteGuard | null>(null);
  const activity = useMasteryPathActivity(pathId || null);

  useEffect(() => {
    let active = true;
    // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the route-owned request state before fetching.
    setTopicError(null);
    void fetchMasteryTopic(pathId, { cache: "no-store" })
      .then((result) => {
        if (active) setTopic(result);
      })
      .catch((reason: unknown) => {
        if (!active) return;
        setTopicError(
          reason instanceof Error
            ? reason.message
            : t("The learning map could not be loaded"),
        );
      });
    return () => {
      active = false;
    };
  }, [activity.revision, pathId, t]);

  // A turn that just ended is the moment the map is most likely to have moved:
  // grading an answer and recording an assessment both happen inside one. The
  // socket normally says so first — but it is the only thing that does, and it
  // is the part most likely to be missing, since a reverse proxy that will not
  // upgrade WebSockets fails silently. Without this the rail then sits frozen
  // until the learner happens to switch windows and come back, which is the
  // one thing someone working through a question never does.
  const wasStreamingRef = useRef(false);
  const refreshActivity = activity.refresh;
  useEffect(() => {
    const streaming = state.isStreaming;
    if (wasStreamingRef.current && !streaming) refreshActivity();
    wasStreamingRef.current = streaming;
  }, [refreshActivity, state.isStreaming]);

  const knowledgeBases = useMemo(
    () =>
      topic?.sources
        .filter(
          (source) =>
            source.kind === "knowledge_base" &&
            source.available &&
            source.source_id,
        )
        .map((source) => source.source_id) ?? [],
    [topic],
  );
  const sessionConfiguration = useMemo<SessionConfiguration>(
    () => ({
      workspaceMode: MASTERY_WORKSPACE_MODE,
      // Sent only when opening a new conversation; a route that names an
      // existing one leaves the stored kind alone (see the parameter's note).
      ...(routeSessionId ? {} : { masterySessionMode: requestedMode }),
      // The study screen runs one action: the tutor loop. Stated here, at the
      // session's source of truth, rather than only asserted by the composer —
      // otherwise every configuration pass would reset it to chat and the
      // composer would set it back, once per render.
      capability: MASTERY_CAPABILITY_VALUE,
      masteryPathId: pathId,
      knowledgeBases,
    }),
    [knowledgeBases, pathId, requestedMode, routeSessionId],
  );

  // Only leaving the route cancels its load. A refreshed learning map must
  // not reload the conversation while a turn is streaming (#1392).
  useEffect(
    () => () => {
      sessionLoadRef.current?.abort();
      initializedRouteRef.current = "";
    },
    [currentRouteKey],
  );

  useEffect(() => {
    if (topic?.path_id !== pathId) return;
    const routeKey = currentRouteKey;
    if (initializedRouteRef.current === routeKey) return;
    initializedRouteRef.current = routeKey;

    if (!routeSessionId) {
      draftRouteGuardRef.current = {
        routeKey,
        previousSessionId: state.sessionId,
      };
      const draftKey = newSession(
        sessionConfiguration,
      );
      // eslint-disable-next-line react-hooks/set-state-in-effect -- record the draft created for this route.
      setDraftBinding({
        routeKey,
        draftKey,
        previousSessionId: state.sessionId,
      });
      return;
    }

    draftRouteGuardRef.current = null;
    const controller = new AbortController();
    sessionLoadRef.current = controller;

    void fetchMasteryTopicSessions(pathId, { cache: "no-store" })
      .then((topicSessions) => {
        if (controller.signal.aborted) return;
        if (
          !topicSessions.some(
            (candidate) => candidate.session_id === routeSessionId,
          )
        ) {
          throw new Error(
            t(
              "This session belongs to a different topic. Open a session from this topic instead.",
            ),
          );
        }
        const cached = showCachedSession(routeSessionId);
        if (cached) {
          configureSession(
            sessionConfiguration,
            routeSessionId,
          );
        }
        return loadSession(routeSessionId, {
          signal: controller.signal,
          revalidate: Boolean(cached),
        });
      })
      .then(() => {
        if (controller.signal.aborted) return;
        configureSession(
          sessionConfiguration,
          routeSessionId,
        );
        setSessionResolution({ routeKey, error: null });
      })
      .catch((reason: unknown) => {
        if (controller.signal.aborted) return;
        setSessionResolution({
          routeKey,
          error:
            reason instanceof Error
              ? reason.message
              : t("This learning session could not be opened"),
        });
      });
  }, [
    configureSession,
    currentRouteKey,
    loadSession,
    newSession,
    pathId,
    routeSessionId,
    sessionConfiguration,
    showCachedSession,
    state.sessionId,
    t,
    topic,
  ]);

  useEffect(() => {
    const newSessionId = state.sessionId;
    if (
      routeSessionId ||
      !newSessionId ||
      !isMasteryDraftSessionReady({
        guard: draftRouteGuardRef.current,
        routeKey: currentRouteKey,
        sessionId: newSessionId,
        masteryPathId: state.masteryPathId,
        pathId,
      })
    )
      return;
    const destination = new URL(existingMasterySessionRoute(pathId, newSessionId), window.location.origin);
    router.replace(
      `${destination.pathname}${destination.search}`,
      { scroll: false },
    );
  }, [
    currentRouteKey,
    pathId,
    routeSessionId,
    router,
    state.masteryPathId,
    state.sessionId,
  ]);

  const sessionError =
    sessionResolution?.routeKey === currentRouteKey
      ? sessionResolution.error
      : null;
  const bindingMatches =
    topic?.path_id === pathId &&
    state.workspaceMode === MASTERY_WORKSPACE_MODE &&
    state.masteryPathId === pathId;
  const sessionLoading = routeSessionId
    ? sessionResolution?.routeKey !== currentRouteKey ||
      (!sessionError && (!bindingMatches || state.sessionId !== routeSessionId))
    : !bindingMatches ||
      !(
        isMasteryDraftSendReady({
          binding: draftBinding,
          routeKey: currentRouteKey,
          sessionKey: state.sessionKey,
          workspaceMode: state.workspaceMode,
          masteryPathId: state.masteryPathId,
          pathId,
          masterySessionMode: state.masterySessionMode,
          requestedMode,
        }) ||
        isMasteryDraftSessionReady({
          guard: draftBinding,
          routeKey: currentRouteKey,
          sessionId: state.sessionId,
          masteryPathId: state.masteryPathId,
          pathId,
        })
      );

  // The kind actually in force: what the server remembers for an existing
  // conversation, and what this route asked for while a new one is still
  // being created.
  const sessionMode: MasteryMode =
    (state.masterySessionMode as MasteryMode | null) || requestedMode;

  return {
    topic,
    topicError,
    knowledgeBases,
    sessionError,
    sessionLoading,
    sessionMode,
  };
}