DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(web): add selector-based chat store
Bingxi Zhao (Frank)422ac501e5b6
diff --git a/web/features/chat/model/types.ts b/web/features/chat/model/types.tsnew file mode 100644index 000000000..cb93d21e4--- /dev/null+++ b/web/features/chat/model/types.ts@@ -0,0 +1,90 @@+import type { StreamEvent, TurnQueryState, TurnStatus } from "@/contracts/generated/turn-protocol";++export interface ChatAttachment {+ id?: string;+ type: string;+ filename?: string;+ mimeType?: string;+ url?: string;+ base64?: string;+ generated?: boolean;+ sizeBytes?: number;+}++export interface ChatRequestSnapshot {+ content: string;+ capability?: string | null;+ tools: string[];+ knowledgeBases: string[];+ language: string;+ attachments?: ChatAttachment[];+ config?: Record<string, unknown>;+}++export interface ChatMessage {+ id: number;+ role: "user" | "assistant" | "system";+ content: string;+ parentMessageId: number | null;+ capability?: string;+ events?: StreamEvent[];+ attachments?: ChatAttachment[];+ requestSnapshot?: ChatRequestSnapshot;+}++export interface ChatSession {+ key: string;+ id: string | null;+ title: string;+ messages: ChatMessage[];+ status: TurnStatus | "idle";+ queryState: TurnQueryState | "idle";+ activeTurnId: string | null;+ lastSeq: number;+ cancellationRequested: boolean;+ selectedBranches: Record<string, number>;+ updatedAt: number;+}++export interface SidebarSessionSummary {+ key: string;+ id: string | null;+ title: string;+ status: TurnStatus | "idle";+ updatedAt: number;+}++export interface ChatSidebarSnapshot {+ revision: number;+ sessions: SidebarSessionSummary[];+}++export interface ChatStoreState {+ activeKey: string | null;+ sessions: Record<string, ChatSession>;+ sidebar: ChatSidebarSnapshot;+}++export type ChatStoreAction =+ | { type: "ensure_session"; key: string }+ | { type: "select_session"; key: string }+ | { type: "load_session"; session: ChatSession }+ | {+ type: "add_optimistic_turn";+ key: string;+ user: ChatMessage;+ assistant: ChatMessage;+ }+ | { type: "stream_event"; key: string; event: StreamEvent }+ | {+ type: "turn_status";+ key: string;+ status: TurnStatus;+ queryState?: TurnQueryState;+ turnId?: string | null;+ }+ | { type: "cancel_requested"; key: string }+ | { type: "session_meta"; key: string; title: string }+ | { type: "set_branch"; key: string; parentKey: string; childId: number }+ | { type: "delete_messages"; key: string; ids: number[] }+ | { type: "regenerate_rollback"; key: string; assistant: ChatMessage };diff --git a/web/features/chat/store/ChatStoreProvider.tsx b/web/features/chat/store/ChatStoreProvider.tsxnew file mode 100644index 000000000..fd856e56f--- /dev/null+++ b/web/features/chat/store/ChatStoreProvider.tsx@@ -0,0 +1,41 @@+"use client";++import {+ createContext,+ useContext,+ useRef,+ useSyncExternalStore,+ type ReactNode,+} from "react";++import { createChatStore, type ChatStore } from "./createChatStore";+import type { ChatStoreState } from "../model/types";++const ChatStoreContext = createContext<ChatStore | null>(null);++export function ChatStoreProvider({+ children,+ store,+}: {+ children: ReactNode;+ store?: ChatStore;+}) {+ const storeRef = useRef<ChatStore | null>(null);+ storeRef.current ??= store ?? createChatStore();+ return <ChatStoreContext.Provider value={storeRef.current}>{children}</ChatStoreContext.Provider>;+}++export function useChatStore(): ChatStore {+ const store = useContext(ChatStoreContext);+ if (!store) throw new Error("useChatStore must be used inside ChatStoreProvider");+ return store;+}++export function useChatSelector<T>(selector: (state: ChatStoreState) => T): T {+ const store = useChatStore();+ return useSyncExternalStore(+ store.subscribe,+ () => selector(store.getState()),+ () => selector(store.getState()),+ );+}diff --git a/web/features/chat/store/createChatStore.ts b/web/features/chat/store/createChatStore.tsnew file mode 100644index 000000000..aa26e2b3a--- /dev/null+++ b/web/features/chat/store/createChatStore.ts@@ -0,0 +1,26 @@+import { chatReducer, initialChatState } from "./reducer";+import type { ChatStoreAction, ChatStoreState } from "../model/types";++export interface ChatStore {+ getState(): ChatStoreState;+ dispatch(action: ChatStoreAction): void;+ subscribe(listener: () => void): () => void;+}++export function createChatStore(initialState: ChatStoreState = initialChatState): ChatStore {+ let state = initialState;+ const listeners = new Set<() => void>();+ return {+ getState: () => state,+ dispatch(action) {+ const next = chatReducer(state, action);+ if (next === state) return;+ state = next;+ for (const listener of listeners) listener();+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+}diff --git a/web/features/chat/store/reducer.ts b/web/features/chat/store/reducer.tsnew file mode 100644index 000000000..947f5e7dd--- /dev/null+++ b/web/features/chat/store/reducer.ts@@ -0,0 +1,197 @@+import type { StreamEvent } from "@/contracts/generated/turn-protocol";++import type {+ ChatSession,+ ChatStoreAction,+ ChatStoreState,+ SidebarSessionSummary,+} from "../model/types";++export const MAX_CACHED_CHAT_SESSIONS = 20;++export const initialChatState: ChatStoreState = {+ activeKey: null,+ sessions: {},+ sidebar: { revision: 0, sessions: [] },+};++export function createChatSession(key: string, now = Date.now()): ChatSession {+ return {+ key,+ id: null,+ title: "",+ messages: [],+ status: "idle",+ queryState: "idle",+ activeTurnId: null,+ lastSeq: 0,+ cancellationRequested: false,+ selectedBranches: {},+ updatedAt: now,+ };+}++function summary(session: ChatSession): SidebarSessionSummary {+ return {+ key: session.key,+ id: session.id,+ title: session.title,+ status: session.status,+ updatedAt: session.updatedAt,+ };+}++function updateSidebar(state: ChatStoreState, session: ChatSession): ChatStoreState["sidebar"] {+ const sessions = [+ summary(session),+ ...state.sidebar.sessions.filter((item) => item.key !== session.key),+ ].sort((left, right) => right.updatedAt - left.updatedAt);+ return { revision: state.sidebar.revision + 1, sessions };+}++function withSession(+ state: ChatStoreState,+ key: string,+ update: (session: ChatSession) => ChatSession,+ sidebar = false,+): ChatStoreState {+ const current = state.sessions[key];+ if (!current) return state;+ const next = update(current);+ return {+ ...state,+ sessions: { ...state.sessions, [key]: next },+ sidebar: sidebar ? updateSidebar(state, next) : state.sidebar,+ };+}++function appendEvent(session: ChatSession, event: StreamEvent): ChatSession {+ const seq = event.seq ?? 0;+ if (seq <= session.lastSeq) return session;+ const messages = [...session.messages];+ const index = messages.length - 1;+ const current = messages[index];+ if (!current || current.role !== "assistant") return session;+ messages[index] = {+ ...current,+ content: event.type === "content" ? current.content + (event.content ?? "") : current.content,+ events: [...(current.events ?? []), event],+ };+ return {+ ...session,+ messages,+ activeTurnId: event.turn_id || session.activeTurnId,+ lastSeq: seq,+ updatedAt: Date.now(),+ };+}++function evictSessions(state: ChatStoreState): ChatStoreState {+ const entries = Object.values(state.sessions);+ if (entries.length <= MAX_CACHED_CHAT_SESSIONS) return state;+ const removable = entries+ .filter((session) => session.key !== state.activeKey && session.status !== "running")+ .sort((left, right) => left.updatedAt - right.updatedAt);+ const sessions = { ...state.sessions };+ for (const session of removable.slice(0, entries.length - MAX_CACHED_CHAT_SESSIONS)) {+ delete sessions[session.key];+ }+ return { ...state, sessions };+}++export function chatReducer(state: ChatStoreState, action: ChatStoreAction): ChatStoreState {+ switch (action.type) {+ case "ensure_session": {+ if (state.sessions[action.key]) return state;+ const session = createChatSession(action.key);+ return evictSessions({+ ...state,+ activeKey: state.activeKey ?? action.key,+ sessions: { ...state.sessions, [action.key]: session },+ sidebar: updateSidebar(state, session),+ });+ }+ case "select_session":+ return state.sessions[action.key] && state.activeKey !== action.key+ ? { ...state, activeKey: action.key }+ : state;+ case "load_session": {+ const next = {+ ...state,+ activeKey: action.session.key,+ sessions: { ...state.sessions, [action.session.key]: action.session },+ sidebar: updateSidebar(state, action.session),+ };+ return evictSessions(next);+ }+ case "add_optimistic_turn":+ return withSession(state, action.key, (session) => ({+ ...session,+ messages: [...session.messages, action.user, action.assistant],+ status: "running",+ queryState: "running",+ cancellationRequested: false,+ updatedAt: Date.now(),+ }));+ case "stream_event":+ return withSession(state, action.key, (session) => appendEvent(session, action.event));+ case "turn_status":+ return withSession(+ state,+ action.key,+ (session) => ({+ ...session,+ status: action.status,+ queryState: action.queryState ?? action.status,+ activeTurnId:+ action.status === "completed" ||+ action.status === "cancelled" ||+ action.status === "failed"+ ? null+ : (action.turnId ?? session.activeTurnId),+ cancellationRequested: false,+ updatedAt: Date.now(),+ }),+ true,+ );+ case "cancel_requested":+ return withSession(state, action.key, (session) => ({+ ...session,+ cancellationRequested: true,+ }));+ case "session_meta":+ return withSession(+ state,+ action.key,+ (session) => ({ ...session, title: action.title, updatedAt: Date.now() }),+ true,+ );+ case "set_branch":+ return withSession(state, action.key, (session) => ({+ ...session,+ selectedBranches: { ...session.selectedBranches, [action.parentKey]: action.childId },+ }));+ case "delete_messages": {+ const ids = new Set(action.ids);+ return withSession(+ state,+ action.key,+ (session) => ({+ ...session,+ messages: session.messages.filter((message) => !ids.has(message.id)),+ updatedAt: Date.now(),+ }),+ true,+ );+ }+ case "regenerate_rollback":+ return withSession(state, action.key, (session) => ({+ ...session,+ messages: [...session.messages.filter((message) => message.content), action.assistant],+ status: "idle",+ queryState: "idle",+ }));+ default:+ return state;+ }+}diff --git a/web/features/chat/store/selectors.ts b/web/features/chat/store/selectors.tsnew file mode 100644index 000000000..43ce9f29a--- /dev/null+++ b/web/features/chat/store/selectors.ts@@ -0,0 +1,15 @@+import type { ChatSession, ChatStoreState } from "../model/types";++export const selectActiveKey = (state: ChatStoreState): string | null => state.activeKey;++export const selectActiveSession = (state: ChatStoreState): ChatSession | null =>+ state.activeKey ? (state.sessions[state.activeKey] ?? null) : null;++export const selectActiveMessages = (state: ChatStoreState) =>+ selectActiveSession(state)?.messages ?? EMPTY_MESSAGES;++export const selectSidebarSnapshot = (state: ChatStoreState) => state.sidebar;++export const selectSession = (key: string) => (state: ChatStoreState) => state.sessions[key] ?? null;++const EMPTY_MESSAGES: ChatSession["messages"] = [];diff --git a/web/tests/chat-store.test.ts b/web/tests/chat-store.test.tsnew file mode 100644index 000000000..cb9a2fb3c--- /dev/null+++ b/web/tests/chat-store.test.ts@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { ChatMessage, ChatSession } from "../features/chat/model/types";+import { createChatStore } from "../features/chat/store/createChatStore";+import { MAX_CACHED_CHAT_SESSIONS } from "../features/chat/store/reducer";++const user = (id: number): ChatMessage => ({+ id,+ role: "user",+ content: "question",+ parentMessageId: null,+});+const assistant = (id: number, content = ""): ChatMessage => ({+ id,+ role: "assistant",+ content,+ parentMessageId: id - 1,+ events: [],+});++test("chat reducer handles optimistic streaming, replay dedupe, and terminal truth", () => {+ const store = createChatStore();+ store.dispatch({ type: "ensure_session", key: "draft" });+ store.dispatch({+ type: "add_optimistic_turn",+ key: "draft",+ user: user(-2),+ assistant: assistant(-1),+ });+ const event = {+ type: "content" as const,+ turn_id: "turn-1",+ seq: 1,+ timestamp: 1,+ content: "answer",+ metadata: {},+ };+ store.dispatch({ type: "stream_event", key: "draft", event });+ store.dispatch({ type: "stream_event", key: "draft", event });+ store.dispatch({+ type: "turn_status",+ key: "draft",+ status: "waiting_input",+ turnId: "turn-1",+ });++ const session = store.getState().sessions.draft;+ assert.equal(session.messages.at(-1)?.content, "answer");+ assert.equal(session.messages.at(-1)?.events?.length, 1);+ assert.equal(session.queryState, "waiting_input");+});++test("branching, delete, regenerate rollback, and metadata remain session scoped", () => {+ const store = createChatStore();+ store.dispatch({ type: "ensure_session", key: "one" });+ store.dispatch({+ type: "add_optimistic_turn",+ key: "one",+ user: user(1),+ assistant: assistant(2, "old"),+ });+ store.dispatch({ type: "set_branch", key: "one", parentKey: "null", childId: 1 });+ store.dispatch({ type: "delete_messages", key: "one", ids: [1, 2] });+ store.dispatch({ type: "regenerate_rollback", key: "one", assistant: assistant(2, "old") });+ store.dispatch({ type: "session_meta", key: "one", title: "Stable title" });+ assert.equal(store.getState().sessions.one.title, "Stable title");+ assert.equal(store.getState().sessions.one.messages.at(-1)?.content, "old");+ assert.equal(store.getState().sessions.one.selectedBranches.null, 1);+});++test("cache bounds evict old idle sessions and retain live work", () => {+ const store = createChatStore();+ for (let index = 0; index < MAX_CACHED_CHAT_SESSIONS + 3; index += 1) {+ const session: ChatSession = {+ key: `s${index}`,+ id: `s${index}`,+ title: `Session ${index}`,+ messages: [],+ status: index === 0 ? "running" : "idle",+ queryState: index === 0 ? "running" : "idle",+ activeTurnId: index === 0 ? "turn-live" : null,+ lastSeq: 0,+ cancellationRequested: false,+ selectedBranches: {},+ updatedAt: index,+ };+ store.dispatch({ type: "load_session", session });+ }+ assert.ok(Object.keys(store.getState().sessions).length <= MAX_CACHED_CHAT_SESSIONS + 1);+ assert.ok(store.getState().sessions.s0);+});diff --git a/web/tests/integration/chat-store-selectors.spec.tsx b/web/tests/integration/chat-store-selectors.spec.tsxnew file mode 100644index 000000000..bab151077--- /dev/null+++ b/web/tests/integration/chat-store-selectors.spec.tsx@@ -0,0 +1,61 @@+import { act, render, screen } from "@testing-library/react";+import { useEffect } from "react";+import { describe, expect, it, vi } from "vitest";++import { ChatStoreProvider, useChatSelector } from "@/features/chat/store/ChatStoreProvider";+import { createChatStore } from "@/features/chat/store/createChatStore";+import { selectActiveMessages, selectSidebarSnapshot } from "@/features/chat/store/selectors";++function MessageConsumer({ onRender }: { onRender: () => void }) {+ const messages = useChatSelector(selectActiveMessages);+ useEffect(onRender);+ return <output data-testid="messages">{messages.at(-1)?.content}</output>;+}++function SidebarConsumer({ onRender }: { onRender: () => void }) {+ const sidebar = useChatSelector(selectSidebarSnapshot);+ useEffect(onRender);+ return <output data-testid="sidebar">{sidebar.sessions.length}</output>;+}++describe("chat selector isolation", () => {+ it("does not rerender sidebar consumers for streamed content", () => {+ const onMessageRender = vi.fn();+ const onSidebarRender = vi.fn();+ const store = createChatStore();+ store.dispatch({ type: "ensure_session", key: "draft" });+ store.dispatch({+ type: "add_optimistic_turn",+ key: "draft",+ user: { id: -2, role: "user", content: "q", parentMessageId: null },+ assistant: { id: -1, role: "assistant", content: "", parentMessageId: -2 },+ });+ render(+ <ChatStoreProvider store={store}>+ <MessageConsumer onRender={onMessageRender} />+ <SidebarConsumer onRender={onSidebarRender} />+ </ChatStoreProvider>,+ );++ const sidebarBefore = screen.getByTestId("sidebar").textContent;+ act(() => {+ store.dispatch({+ type: "stream_event",+ key: "draft",+ event: {+ type: "content",+ turn_id: "turn-1",+ seq: 1,+ timestamp: 1,+ content: "token",+ metadata: {},+ },+ });+ });++ expect(screen.getByTestId("messages")).toHaveTextContent("token");+ expect(screen.getByTestId("sidebar").textContent).toBe(sidebarBefore);+ expect(onMessageRender).toHaveBeenCalledTimes(2);+ expect(onSidebarRender).toHaveBeenCalledTimes(1);+ });+});