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 { 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 & { 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; /** Create mode: the artifact kind ("skill" | "persona") every turn of this * conversation authors towards; "" / absent when not in create mode. */ create_target?: string; /** Session-level persona preference; "" / absent = Default (no persona). */ persona?: string; /** Who the conversation is handed to — `partner:` / `subagent:`; * "" / 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; /** 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; /** ``selection`` tutored one passage; ``conversation`` is about the whole * parent conversation. Written by the backend on each side-chat turn. */ tutor_scope?: "selection" | "conversation"; /** The passage a ``selection`` thread was opened from, clipped by the server. */ tutor_selected_text?: string; /** The message a side chat was opened from; absent for a bare side chat and * for threads created before this was recorded. Drives the message-level * Little Tutor entry. */ tutor_source_message_id?: number | string | null; /** Internal: the legacy-thread backfill has already run for this row, so a * detached thread is not attached again. */ tutor_source_backfill_attempted?: boolean; /** 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; user_answer: string; correct_answer: string; explanation?: string; difficulty?: string; is_correct: boolean; } async function expectJson(response: Response): Promise { 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; } export async function listSessions( limit = 50, offset = 0, options?: { force?: boolean; workspaceId?: string; allWorkspaces?: boolean }, ): Promise { 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( `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 { const pageSize = 200; const sessions: SessionSummary[] = []; const seen = new Set(); 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 { 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(response); } /** Fetch every full-text search hit in bounded pages for the history console. */ export async function searchAllSessions( query: string, signal?: AbortSignal, ): Promise { const pageSize = 100; const sessions: SessionSearchResult[] = []; const seen = new Set(); 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 { const response = await apiFetch(apiUrl(`/api/sessions/${sessionId}`), { cache: "no-store", signal, }); return expectJson(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, ): Promise { const { type: _type, protocol_version: _version, ...payload } = request; return expectJson(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 { return expectJson(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 { 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 { 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 { const response = await apiFetch( apiUrl( `/api/sessions/${sessionId}/messages/${messageId}/events?after_seq=${afterSeq}&limit=500`, ), { cache: "no-store", signal }, ); return expectJson(response); } export type SessionOrganizationPatch = Partial<{ workspace_id: string | null; parent_session_id: string; session_kind: "chat" | "selection_tutor"; pinned: boolean; archived: boolean; /** Which message a Little Tutor thread is filed under; null detaches it. */ tutor_source_message_id: number | string | null; }>; export async function updateSessionOrganization( sessionId: string, patch: SessionOrganizationPatch, workspaceId?: string, ): Promise { 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 { 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 { 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 { 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 { 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 interface DeleteMessageResult { /** Little Tutor threads the server detached from the deleted messages. */ detachedThreadIds: string[]; /** Every message row the delete removed (a turn's user + assistant rows). */ deletedMessageIds: number[]; } export async function deleteMessage( sessionId: string, messageId: number, ): Promise { const response = await apiFetch( apiUrl(`/api/sessions/${sessionId}/messages/${messageId}`), { method: "DELETE", }, ); const payload = await expectJson<{ deleted: boolean; detached_thread_ids?: string[]; deleted_message_ids?: number[]; }>(response); // Older servers omit both lists. Keep the caller's own id as the only known // deleted row; never invent thread ids for a response that has none. return { detachedThreadIds: Array.isArray(payload.detached_thread_ids) ? payload.detached_thread_ids.filter( (threadId): threadId is string => typeof threadId === "string" && threadId.length > 0, ) : [], deletedMessageIds: Array.isArray(payload.deleted_message_ids) ? payload.deleted_message_ids.filter( (deletedId): deletedId is number => typeof deletedId === "number" && Number.isFinite(deletedId), ) : [messageId], }; } export async function updateBranchSelection( sessionId: string, selectedBranches: Record, ): Promise { 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 }>(response); } export function sessionWorkspaceId(session?: SessionSummary): string { return session?.content_workspace_id ?? session?.preferences?.workspace_id ?? ''; }