Skip to content

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

17.0 KB
Raw Blame
import { clearFailedSubmission } from "@/lib/failed-submissions";
import { scopedUrl } from "@/lib/workspace-scope";
import { notifySessionsChanged } from "@/lib/session-events";
import { apiFetch, apiUrl } from "@/lib/api";
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
import type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";
import { browserReturnPath, loginHref } from "@/shared/auth/return-url";

/** Fail closed when the configured backend cannot fence an uncertain send. */
export async function supportsSubmissionReplacement(): Promise<boolean> {
  try {
    return await withClientCache("session-store-capabilities", async () => {
      const response = await apiFetch(apiUrl(scopedUrl("/api/sessions/capabilities")));
      if (!response.ok) throw new Error("Session capabilities unavailable");
      const capabilities: unknown = await response.json();
      return typeof capabilities === "object" && capabilities !== null &&
        "submission_replacement" in capabilities && capabilities.submission_replacement === true;
    });
  } catch { return false; }
}

export interface SessionMessage {
  id: number;
  session_id: string;
  role: "user" | "assistant" | "system";
  content: string;
  capability?: string;
  events: StreamEvent[];
  attachments: Array<{
    type: string;
    filename?: string;
    base64?: string;
    url?: string;
    mime_type?: string;
    id?: string;
    extracted_text?: string;
    generated?: boolean;
    size_bytes?: number;
    origin?: "workspace";
    workspace_id?: string;
    workspace_item_id?: string;
    relative_path?: string;
    sha256?: string;
    title?: string;
    caption?: string;
  }>;
  metadata?: Record<string, unknown> & {
    orphaned_failed_turn?: OrphanedFailedTurn;
  };
  trace?: MessageTraceMetadata;
  created_at: number;
  /** Edit-branching: id of the message this row continues. `null` for the
   *  first message in a session. Siblings share the same parent. */
  parent_message_id?: number | null;
}

/** A persisted failed turn with a saved user row but no assistant reply. */
export interface OrphanedFailedTurn {
  turn_id: string;
  error: string;
  failure_code: string;
  retryable: boolean;
  finished_at: number;
}

export interface MessageTraceMetadata {
  turn_id?: string | null;
  total?: number;
  last_seq?: number;
  truncated?: boolean;
  /** Wall-clock start of the whole turn, epoch seconds. Supplied because the
   *  preview keeps only tool and terminal events: the moment the turn began
   *  is never among them, so timing the preview alone starts the clock at the
   *  first tool call. */
  started_at?: number | null;
  /** Wall-clock end of the whole turn, epoch seconds. */
  ended_at?: number | null;
}

export interface MessageTracePage {
  session_id: string;
  message_id: number;
  turn_id?: string | null;
  events: StreamEvent[];
  total: number;
  last_seq: number;
  next_seq: number | null;
  complete: boolean;
}

export interface SessionPreferences {
  workspace_id?: string | null;
  capability?: string;
  timed_media_id?: string;
  /** Stable learning surface, independent of the action used for a turn. */
  workspace_mode?:
    "immersive_reading" | "mastery_path" | "immersive_watching" | "";
  tools?: string[];
  knowledge_bases?: string[];
  language?: string;
  /** Null/absent follows the account default; a code fixes this conversation. */
  reply_language_override?: string | null;
  llm_selection?: LLMSelection | null;
  /** Persistent mastery state associated with this conversation. */
  mastery_path_id?: string;
  /** "outline" | "study" | "review" — what this mastery conversation is for. */
  mastery_session_mode?: string;
  /** Note page a notebook companion conversation is held beside. */
  note_document_id?: string;
  /** Session-level persona preference; "" / absent = Default (no persona). */
  persona?: string;
  /** Who the conversation is handed to — `partner:<id>` / `subagent:<name>`;
   *  "" / absent when DeepTutor answers. Rewritten with every turn. */
  answer_by?: string;
  /** What this conversation narrowed its skill / MCP reach to. Absent or empty
   *  means it inherits everything its workspace allows. */
  skills?: string[];
  mcp?: string[];
  /** Edit-branching: maps a parent_message_id → the child id currently
   *  shown at that branch point. Missing keys default to the latest
   *  sibling (most recently created child). */
  selected_branches?: Record<string, number>;
  /** The conversation a side chat was opened beside. */
  parent_session_id?: string;
  /** ``selection_tutor`` marks a side chat (the name predates side chats). */
  session_kind?: "chat" | "selection_tutor" | "immersive_reading";
  /** The partner group a side chat convenes; a partner or an agent answering
   *  one is ``answer_by``. Written by the backend on each turn. */
  side_chat_group_id?: string;
  /** Owning Immersive Reading workspace, present only for reading sessions. */
  reading_workspace_id?: string;
  /** Material active when the reading conversation was created. */
  reading_material_id?: string;
  /** The book page whose tutor chat this is, written with the book's own record. */
  book_id?: string;
  book_page_id?: string;
  pinned?: boolean;
  archived?: boolean;
}

export interface SessionSummary {
  /** Authoritative storage scope, supplied by the account navigation index. */
  content_workspace_id?: string;
  id: string;
  session_id: string;
  title: string;
  created_at: number;
  updated_at: number;
  message_count: number;
  last_message: string;
  status?:
    "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";
  active_turn_id?: string;
  preferences?: SessionPreferences;
}

export interface SessionSearchResult extends SessionSummary {
  match_excerpt: string;
  match_role?: "user" | "assistant" | null;
  match_message_id?: number | string | null;
  match_created_at?: number | null;
}

export interface SessionSearchPage {
  sessions: SessionSearchResult[];
  total: number;
  limit: number;
  offset: number;
}

export interface ActiveTurnSummary {
  id: string;
  turn_id: string;
  session_id: string;
  capability: string;
  status: "running" | "completed" | "failed" | "cancelled" | "rejected";
  error: string;
  created_at: number;
  updated_at: number;
  finished_at?: number | null;
  last_seq: number;
}

export interface SessionDetail {
  id: string;
  session_id: string;
  title: string;
  created_at: number;
  updated_at: number;
  status?:
    "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";
  active_turn_id?: string;
  compressed_summary?: string;
  summary_up_to_msg_id?: number | string;
  preferences?: SessionPreferences;
  messages: SessionMessage[];
  active_turns?: ActiveTurnSummary[];
}

export interface QuizResultItem {
  question_id?: string;
  question: string;
  question_type?: string;
  options?: Record<string, string>;
  user_answer: string;
  correct_answer: string;
  explanation?: string;
  difficulty?: string;
  is_correct: boolean;
}

async function expectJson<T>(response: Response): Promise<T> {
  if (response.status === 401 && typeof window !== "undefined") {
    window.location.href = loginHref(browserReturnPath(window.location));
    return new Promise(() => {});
  }
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }
  return response.json() as Promise<T>;
}

export async function listSessions(
  limit = 50,
  offset = 0,
  options?: { force?: boolean; workspaceId?: string; allWorkspaces?: boolean },
): Promise<SessionSummary[]> {
  const qs = new URLSearchParams({
    limit: String(limit),
    offset: String(offset),
  });
  if (options?.allWorkspaces) qs.set("all_workspaces", "true");
  if (options?.workspaceId !== undefined) qs.set("dt_workspace", options.workspaceId);
  return withClientCache<SessionSummary[]>(
    `sessions:${limit}:${offset}:${options?.allWorkspaces ? "account" : "scope"}${options?.workspaceId !== undefined ? `:workspace:${options.workspaceId}` : ""}`,
    async () => {
      const response = await apiFetch(
        apiUrl(`/api/sessions?${qs.toString()}`),
        {
          cache: "no-store",
        },
      );
      const data = await expectJson<{ sessions: SessionSummary[] }>(response);
      return data.sessions ?? [];
    },
    {
      force: options?.force,
      ttlMs: 15_000,
    },
  );
}

/** Fetch the complete session index in bounded pages for conversation organization. */
export async function listAllSessions(options?: {
  force?: boolean;
  allWorkspaces?: boolean;
}): Promise<SessionSummary[]> {
  const pageSize = 200;
  const sessions: SessionSummary[] = [];
  const seen = new Set<string>();
  for (let offset = 0; ; offset += pageSize) {
    const page = await listSessions(pageSize, offset, options);
    // Updates can move a row between offset pages while the index is loading.
    // Scope is part of identity: migration/imports can reuse a session id.
    for (const session of page) {
      const key = `${sessionWorkspaceId(session)}:${session.session_id}`;
      if (!seen.has(key)) { seen.add(key); sessions.push(session); }
    }
    if (page.length < pageSize) return sessions;
  }
}

export async function searchSessions(
  query: string,
  limit = 50,
  offset = 0,
  signal?: AbortSignal,
): Promise<SessionSearchPage> {
  const qs = new URLSearchParams({
    q: query,
    limit: String(limit),
    offset: String(offset),
  });
  const response = await apiFetch(apiUrl(`/api/sessions/search?${qs}`), {
    cache: "no-store",
    signal,
  });
  return expectJson<SessionSearchPage>(response);
}

/** Fetch every full-text search hit in bounded pages for the history console. */
export async function searchAllSessions(
  query: string,
  signal?: AbortSignal,
): Promise<SessionSearchResult[]> {
  const pageSize = 100;
  const sessions: SessionSearchResult[] = [];
  const seen = new Set<string>();
  for (let offset = 0; ; offset += pageSize) {
    const page = await searchSessions(
      query,
      pageSize,
      offset,
      signal,
    );
    for (const session of page.sessions) {
      const key = `${sessionWorkspaceId(session)}:${session.session_id}`;
      if (seen.has(key)) continue;
      seen.add(key);
      sessions.push(session);
    }
    if (sessions.length >= page.total || page.sessions.length < pageSize) {
      return sessions;
    }
  }
}

export async function getSession(
  sessionId: string,
  signal?: AbortSignal,
): Promise<SessionDetail> {
  const response = await apiFetch(apiUrl(`/api/sessions/${sessionId}`), {
    cache: "no-store",
    signal,
  });
  return expectJson<SessionDetail>(response);
}

export type SubmissionReplacementReceipt = {
  status: "started"; session_id: string; submission_id: string;
  turn: { id: string; status: string };
};

export async function replaceSubmission(
  originalSubmissionId: string, request: Record<string, unknown>,
): Promise<SubmissionReplacementReceipt> {
  const { type: _type, protocol_version: _version, ...payload } = request;
  return expectJson<SubmissionReplacementReceipt>(await apiFetch(apiUrl("/api/sessions/submission-replacement"), {
    method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ original_submission_id: originalSubmissionId, request: payload }),
  }));
}

/** Opening an old Watching conversation is the explicit migration boundary. */
export async function migrateWatchingSession(sessionId: string): Promise<SessionDetail> {
  return expectJson<SessionDetail>(await apiFetch(apiUrl(`/api/sessions/${encodeURIComponent(sessionId)}/migrate-watching`), { method: "POST" }));
}

/**
 * One line the user is likely to type next, for the home composer's
 * placeholder — "" when there is nothing worth offering (no exchange yet,
 * a timeout, a model that didn't come back with something usable).
 */
export async function fetchSessionAskHint(
  sessionId: string,
  init?: RequestInit,
): Promise<string> {
  try {
    const response = await apiFetch(
      apiUrl(`/api/sessions/${sessionId}/ask-hint`),
      {
        cache: "no-store",
        ...init,
      },
    );
    const result = await expectJson<{ hint?: string }>(response);
    return typeof result.hint === "string" ? result.hint : "";
  } catch {
    // A missing hint is not a failure the composer should ever surface.
    return "";
  }
}

export async function updateSessionTitle(
  sessionId: string,
  title: string,
  workspaceId?: string,
): Promise<SessionDetail> {
  const response = await apiFetch(apiUrl(scopedUrl(`/api/sessions/${sessionId}`, workspaceId)), {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  const data = await expectJson<{ session: SessionDetail }>(response);
  invalidateClientCache("sessions:");
  return data.session;
}

export async function updateSessionReplyLanguage(
  sessionId: string,
  language: string | null,
  workspaceId?: string,
): Promise<{ preferences?: SessionPreferences }> {
  const response = await apiFetch(
    apiUrl(scopedUrl(`/api/sessions/${sessionId}/reply-language`, workspaceId)),
    {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ language }),
    },
  );
  const data = await expectJson<{ session: { preferences?: SessionPreferences } }>(response);
  invalidateClientCache("sessions:");
  return data.session;
}

export async function getMessageTrace(
  sessionId: string,
  messageId: number,
  afterSeq = 0,
  signal?: AbortSignal,
): Promise<MessageTracePage> {
  const response = await apiFetch(
    apiUrl(
      `/api/sessions/${sessionId}/messages/${messageId}/events?after_seq=${afterSeq}&limit=500`,
    ),
    { cache: "no-store", signal },
  );
  return expectJson<MessageTracePage>(response);
}

export type SessionOrganizationPatch = Partial<{
  workspace_id: string | null;
  parent_session_id: string;
  session_kind: "chat" | "selection_tutor";
  pinned: boolean;
  archived: boolean;
}>;

export async function updateSessionOrganization(
  sessionId: string,
  patch: SessionOrganizationPatch,
  workspaceId?: string,
): Promise<SessionDetail> {
  const response = await apiFetch(
    apiUrl(scopedUrl(`/api/sessions/${sessionId}/organization`, workspaceId)),
    {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(patch),
    },
  );
  const data = await expectJson<{ session: SessionDetail }>(response);
  invalidateClientCache("sessions:");
  notifySessionsChanged();
  return data.session;
}

/** A conversation's title, status and preferences — no transcript. */
export async function getSessionOrganization(
  sessionId: string,
  workspaceId?: string,
  signal?: AbortSignal,
): Promise<SessionSummary> {
  const response = await apiFetch(
    apiUrl(scopedUrl(`/api/sessions/${sessionId}/organization`, workspaceId)),
    { cache: "no-store", signal },
  );
  const data = await expectJson<{ session: SessionSummary }>(response);
  return data.session;
}

/** The side chats opened from a conversation, newest first. */
export async function listSessionThreads(
  sessionId: string,
  workspaceId?: string,
  signal?: AbortSignal,
): Promise<SessionSummary[]> {
  const response = await apiFetch(
    apiUrl(scopedUrl(`/api/sessions/${sessionId}/threads`, workspaceId)),
    { cache: "no-store", signal },
  );
  const data = await expectJson<{ threads: SessionSummary[] }>(response);
  return data.threads ?? [];
}

export async function deleteSession(sessionId: string, workspaceId?: string): Promise<void> {
  const response = await apiFetch(apiUrl(scopedUrl(`/api/sessions/${sessionId}`, workspaceId)), {
    method: "DELETE",
  });
  const data = await expectJson<{ deleted: boolean }>(response);
  if (!data.deleted) throw new Error("Session was not deleted");
  clearFailedSubmission(sessionId);
  invalidateClientCache("sessions:");
  notifySessionsChanged();
}

export async function recordQuizResults(
  sessionId: string,
  answers: QuizResultItem[],
  turnId?: string | null,
): Promise<void> {
  const response = await apiFetch(
    apiUrl(`/api/sessions/${sessionId}/quiz-results`),
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ answers, turn_id: turnId || "" }),
    },
  );
  await expectJson<{ recorded: boolean }>(response);
}

export async function deleteMessage(
  sessionId: string,
  messageId: number,
): Promise<void> {
  const response = await apiFetch(
    apiUrl(`/api/sessions/${sessionId}/messages/${messageId}`),
    {
      method: "DELETE",
    },
  );
  await expectJson<{ deleted: boolean }>(response);
}

export async function updateBranchSelection(
  sessionId: string,
  selectedBranches: Record<string, number>,
): Promise<void> {
  const response = await apiFetch(
    apiUrl(`/api/sessions/${sessionId}/branch-selection`),
    {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ selected_branches: selectedBranches }),
    },
  );
  await expectJson<{ selected_branches: Record<string, number> }>(response);
}

export function sessionWorkspaceId(session?: SessionSummary): string {
  return session?.content_workspace_id ?? session?.preferences?.workspace_id ?? '';
}