Files
DeepTutor/web/hooks/useSessionThreads.ts
yuanyyt 43b66ac1ad feat: add a message-level Little Tutor entry
Side chats are filed under the message their quoted passage came from:
the turn carries quoted_message_id, the backend stores it as
tutor_source_message_id, and the chat list shows "Little Tutor x N"
under that message with a popover to open or delete each thread.

Threads are read once per conversation and shared with the viewer, only
side-chat turns refresh the session lists, and a turn that omits the
field leaves the stored anchor untouched.

Refs #2118
2026-10-30 13:55:29 +08:00

62 lines
2.0 KiB
TypeScript

"use client";
/**
* The side chats opened from a conversation, grouped by the message each one
* quotes. Read once per conversation and refreshed whenever the session list
* changes (a new side chat's first turn, a deletion, a rename).
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import {
listSessionThreads,
type SessionSummary,
} from "@/lib/session-api";
import { subscribeSessionChanges } from "@/lib/session-events";
import { groupThreadsByMessage } from "@/lib/session-threads";
const NO_THREADS: SessionSummary[] = [];
export interface SessionThreads {
threads: SessionSummary[];
byMessageId: ReadonlyMap<string, SessionSummary[]>;
refresh: () => void;
}
export function useSessionThreads(
sessionId: string | null | undefined,
workspaceId?: string | null,
): SessionThreads {
// The session the rows belong to travels with them, so switching
// conversations never shows one chat's threads under another's messages.
const [state, setState] = useState<{
sessionId: string;
rows: SessionSummary[];
}>({ sessionId: "", rows: NO_THREADS });
const [revision, setRevision] = useState(0);
const refresh = useCallback(() => setRevision((n) => n + 1), []);
useEffect(() => subscribeSessionChanges(refresh), [refresh]);
useEffect(() => {
if (!sessionId) return;
const controller = new AbortController();
listSessionThreads(sessionId, workspaceId || undefined, controller.signal)
.then((rows) => {
if (!controller.signal.aborted) setState({ sessionId, rows });
})
.catch(() => {
// A conversation whose threads cannot be read simply has none to show.
if (!controller.signal.aborted) {
setState({ sessionId, rows: NO_THREADS });
}
});
return () => controller.abort();
}, [sessionId, revision, workspaceId]);
const rows = state.sessionId === sessionId ? state.rows : NO_THREADS;
const byMessageId = useMemo(() => groupThreadsByMessage(rows), [rows]);
return { threads: rows, byMessageId, refresh };
}