DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(web): route chat through the v2 runtime provider
Bingxi Zhao (Frank)a366cfa8961b
diff --git a/web/app/(utility)/mastery/[pathId]/study/layout.tsx b/web/app/(utility)/mastery/[pathId]/study/layout.tsxindex f4e871d7b..f919cbfb5 100644--- a/web/app/(utility)/mastery/[pathId]/study/layout.tsx+++ b/web/app/(utility)/mastery/[pathId]/study/layout.tsx@@ -1,6 +1,6 @@import { GeogebraTabProvider } from "@/context/GeogebraTabContext";import { QuizFollowupProvider } from "@/context/QuizFollowupContext";-import { UnifiedChatProvider } from "@/context/UnifiedChatContext";+import { ChatRuntimeProvider } from "@/features/chat";import { ReadingProvider } from "@/context/ReadingContext";import { WatchingProvider } from "@/context/WatchingContext";@@ -16,11 +16,11 @@ export default function MasteryStudyLayout({return (<ReadingProvider><WatchingProvider>- <UnifiedChatProvider>+ <ChatRuntimeProvider><QuizFollowupProvider><GeogebraTabProvider>{children}</GeogebraTabProvider></QuizFollowupProvider>- </UnifiedChatProvider>+ </ChatRuntimeProvider></WatchingProvider></ReadingProvider>);diff --git a/web/app/(workspace)/layout.tsx b/web/app/(workspace)/layout.tsxindex ea0e73c11..0c2b30dee 100644--- a/web/app/(workspace)/layout.tsx+++ b/web/app/(workspace)/layout.tsx@@ -2,7 +2,7 @@ import WorkspaceSidebar from "@/components/sidebar/WorkspaceSidebar";import AppShell from "@/components/layout/AppShell";import { CapabilityAccessProvider } from "@/components/access/CapabilityAccessContext";import CapabilityGate from "@/components/access/CapabilityGate";-import { UnifiedChatProvider } from "@/context/UnifiedChatContext";+import { ChatRuntimeProvider } from "@/features/chat";import { ReadingProvider } from "@/context/ReadingContext";import { WatchingProvider } from "@/context/WatchingContext";@@ -13,7 +13,7 @@ export default function WorkspaceLayout({}>) {return (<CapabilityAccessProvider>- <UnifiedChatProvider>+ <ChatRuntimeProvider>{/* Above the page on purpose: sending the first message navigates/home → /home/<id>, which remounts the page. The open documentmust not die with it. */}@@ -24,7 +24,7 @@ export default function WorkspaceLayout({</AppShell></WatchingProvider></ReadingProvider>- </UnifiedChatProvider>+ </ChatRuntimeProvider></CapabilityAccessProvider>);}diff --git a/web/app/(workspace)/reading/layout.tsx b/web/app/(workspace)/reading/layout.tsxindex 0094d7ddb..e4e5cbc81 100644--- a/web/app/(workspace)/reading/layout.tsx+++ b/web/app/(workspace)/reading/layout.tsx@@ -1,20 +1,16 @@import { GeogebraTabProvider } from "@/context/GeogebraTabContext";import { QuizFollowupProvider } from "@/context/QuizFollowupContext";-import { UnifiedChatProvider } from "@/context/UnifiedChatContext";/**- * Reading owns its conversation runtime. The workspace shell above also hosts- * Home's provider so Home can keep a turn alive while navigation occurs, but a- * reader must never render that provider's transcript or live stream.+ * Reading uses the workspace-level runtime. Route/session selection isolates+ * its transcript without opening a second WebSocket or store.*/export default function ReadingLayout({children,}: Readonly<{ children: React.ReactNode }>) {return (- <UnifiedChatProvider>- <QuizFollowupProvider>- <GeogebraTabProvider>{children}</GeogebraTabProvider>- </QuizFollowupProvider>- </UnifiedChatProvider>+ <QuizFollowupProvider>+ <GeogebraTabProvider>{children}</GeogebraTabProvider>+ </QuizFollowupProvider>);}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 305dec1ce..482d6eb32 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -2354,6 +2354,7 @@ export function UnifiedChatProvider({return <ChatCtx.Provider value={value}>{children}</ChatCtx.Provider>;}+/** @deprecated Migrate to narrow selectors/actions from `@/features/chat` (Task 14). */export function useUnifiedChat() {const ctx = useContext(ChatCtx);if (!ctx)diff --git a/web/features/chat/ChatRuntimeProvider.tsx b/web/features/chat/ChatRuntimeProvider.tsxnew file mode 100644index 000000000..101f303a4--- /dev/null+++ b/web/features/chat/ChatRuntimeProvider.tsx@@ -0,0 +1,72 @@+"use client";++import { createContext, useContext, useEffect, useState, type ReactNode } from "react";+import type { StreamEvent } from "@/contracts/generated/turn-protocol";++import { UnifiedChatProvider } from "@/context/UnifiedChatContext";++import { ChatActions } from "./store/ChatActions";+import { ChatStoreProvider } from "./store/ChatStoreProvider";+import { createChatStore, type ChatStore } from "./store/createChatStore";+import { TurnRuntimeClient } from "./transport/TurnRuntimeClient";++interface ChatRuntimeValue {+ actions: ChatActions;+ store: ChatStore;+}++const ChatRuntimeContext = createContext<ChatRuntimeValue | null>(null);++export function ChatRuntimeProvider({ children }: { children: ReactNode }) {+ const parent = useContext(ChatRuntimeContext);+ if (parent && process.env.NODE_ENV !== "production") {+ throw new Error("ChatRuntimeProvider cannot be nested; scope one runtime per route subtree");+ }++ const [value] = useState<ChatRuntimeValue>(() => {+ const store = createChatStore();+ const actions = new ChatActions(store, (sessionKey) =>+ new TurnRuntimeClient({+ onEvent(event) {+ if (event.type === "active_turn_info" || event.type === "pong") return;+ store.dispatch({+ type: "stream_event",+ key: sessionKey,+ event: event as StreamEvent,+ });+ if (event.type === "wait_for_input") {+ store.dispatch({+ type: "turn_status",+ key: sessionKey,+ status: "waiting_input",+ turnId: event.turn_id,+ });+ }+ if (event.type === "done") {+ const candidate = event.metadata?.status;+ const terminal =+ candidate === "failed" || candidate === "cancelled" ? candidate : "completed";+ store.dispatch({ type: "turn_status", key: sessionKey, status: terminal });+ }+ },+ }),+ );+ return { actions, store };+ });++ useEffect(() => () => value.actions.close(), [value]);++ return (+ <ChatRuntimeContext.Provider value={value}>+ <ChatStoreProvider store={value.store}>+ <UnifiedChatProvider>{children}</UnifiedChatProvider>+ </ChatStoreProvider>+ </ChatRuntimeContext.Provider>+ );+}++export function useChatActions(): ChatActions {+ const runtime = useContext(ChatRuntimeContext);+ if (!runtime) throw new Error("useChatActions must be used inside ChatRuntimeProvider");+ return runtime.actions;+}diff --git a/web/features/chat/api/session-client.ts b/web/features/chat/api/session-client.tsnew file mode 100644index 000000000..11cf8a289--- /dev/null+++ b/web/features/chat/api/session-client.ts@@ -0,0 +1,75 @@+import { requestJson, requestVoid } from "@/shared/api/client";++export interface SessionWireMessage {+ id: number;+ role: "user" | "assistant" | "system";+ content: string;+ parent_message_id?: number | null;+ capability?: string;+ events?: unknown[];+}++export interface SessionWireDetail {+ id?: string;+ session_id?: string;+ title: string;+ status?: string;+ active_turn_id?: string | null;+ messages: SessionWireMessage[];+ preferences?: Record<string, unknown>;+ updated_at?: number;+}++export interface SessionClient {+ get(sessionId: string, signal?: AbortSignal): Promise<SessionWireDetail>;+ rename(sessionId: string, title: string): Promise<SessionWireDetail>;+ remove(sessionId: string): Promise<void>;+ selectBranch(sessionId: string, selectedBranches: Record<string, number>): Promise<void>;+ removeMessage(sessionId: string, messageId: number): Promise<void>;+}++function id(value: string): string {+ return encodeURIComponent(value);+}++export const sessionClient: SessionClient = {+ get(sessionId, signal) {+ return requestJson<SessionWireDetail>(`/api/v1/sessions/${id(sessionId)}`, {+ cache: "no-store",+ signal,+ scope: "session",+ });+ },+ async rename(sessionId, title) {+ const result = await requestJson<SessionWireDetail | { session: SessionWireDetail }>(+ `/api/v1/sessions/${id(sessionId)}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ title }),+ scope: "session",+ },+ );+ return "session" in result ? result.session : result;+ },+ remove(sessionId) {+ return requestVoid(`/api/v1/sessions/${id(sessionId)}`, {+ method: "DELETE",+ scope: "session",+ });+ },+ selectBranch(sessionId, selectedBranches) {+ return requestVoid(`/api/v1/sessions/${id(sessionId)}/branch-selection`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ selected_branches: selectedBranches }),+ scope: "session",+ });+ },+ removeMessage(sessionId, messageId) {+ return requestVoid(`/api/v1/sessions/${id(sessionId)}/messages/${messageId}`, {+ method: "DELETE",+ scope: "session",+ });+ },+};diff --git a/web/features/chat/index.ts b/web/features/chat/index.tsnew file mode 100644index 000000000..8203509f6--- /dev/null+++ b/web/features/chat/index.ts@@ -0,0 +1,4 @@+export { ChatRuntimeProvider, useChatActions } from "./ChatRuntimeProvider";+export { useChatSelector, useChatStore } from "./store/ChatStoreProvider";+export * from "./store/selectors";+export type * from "./model/types";diff --git a/web/features/chat/model/types.ts b/web/features/chat/model/types.tsindex cb93d21e4..a5e8a9aaf 100644--- a/web/features/chat/model/types.ts+++ b/web/features/chat/model/types.ts@@ -68,6 +68,7 @@ export interface ChatStoreState {export type ChatStoreAction =| { type: "ensure_session"; key: string }| { type: "select_session"; key: string }+ | { type: "remove_session"; key: string }| { type: "load_session"; session: ChatSession }| {type: "add_optimistic_turn";diff --git a/web/features/chat/store/ChatActions.ts b/web/features/chat/store/ChatActions.tsnew file mode 100644index 000000000..bea6fc695--- /dev/null+++ b/web/features/chat/store/ChatActions.ts@@ -0,0 +1,152 @@+import type { StartTurnCommand, StreamEvent, TurnStatus } from "@/contracts/generated/turn-protocol";+import {+ buildCancelTurn,+ buildRegenerate,+ buildSubmitUserReply,+} from "@/contracts/parse/turn-command";++import type { ChatMessage, ChatSession } from "../model/types";+import type { TurnRuntimeClient } from "../transport/TurnRuntimeClient";+import type { ChatStore } from "./createChatStore";+import { sessionClient, type SessionClient, type SessionWireDetail } from "../api/session-client";++export type TurnRuntimeFactory = (sessionKey: string) => TurnRuntimeClient;++function status(value: unknown): TurnStatus | "idle" {+ return value === "queued" ||+ value === "running" ||+ value === "waiting_input" ||+ value === "completed" ||+ value === "failed" ||+ value === "cancelled"+ ? value+ : "idle";+}++function toSession(detail: SessionWireDetail, fallbackId: string): ChatSession {+ const id = detail.session_id ?? detail.id ?? fallbackId;+ const normalizedStatus = status(detail.status);+ return {+ key: id,+ id,+ title: detail.title,+ messages: detail.messages.map((message) => ({+ id: message.id,+ role: message.role,+ content: message.content,+ capability: message.capability,+ events: (message.events ?? []) as StreamEvent[],+ parentMessageId: message.parent_message_id ?? null,+ })),+ status: normalizedStatus,+ queryState: normalizedStatus,+ activeTurnId: detail.active_turn_id ?? null,+ lastSeq: 0,+ cancellationRequested: false,+ selectedBranches:+ detail.preferences?.selected_branches &&+ typeof detail.preferences.selected_branches === "object"+ ? (detail.preferences.selected_branches as Record<string, number>)+ : {},+ updatedAt: detail.updated_at ?? Date.now(),+ };+}++export class ChatActions {+ private readonly runtimes = new Map<string, TurnRuntimeClient>();++ constructor(+ private readonly store: ChatStore,+ private readonly runtimeFactory: TurnRuntimeFactory,+ private readonly sessions: SessionClient = sessionClient,+ ) {}++ async loadSession(sessionId: string, signal?: AbortSignal): Promise<ChatSession> {+ const session = toSession(await this.sessions.get(sessionId, signal), sessionId);+ this.store.dispatch({ type: "load_session", session });+ return session;+ }++ async renameSession(sessionId: string, title: string): Promise<void> {+ await this.sessions.rename(sessionId, title);+ this.store.dispatch({ type: "session_meta", key: sessionId, title });+ }++ async deleteSession(sessionId: string): Promise<void> {+ await this.sessions.remove(sessionId);+ this.runtime(sessionId).stop();+ this.runtimes.delete(sessionId);+ this.store.dispatch({ type: "remove_session", key: sessionId });+ }++ startTurn(input: {+ sessionKey: string;+ command: StartTurnCommand;+ user: ChatMessage;+ assistant: ChatMessage;+ }): void {+ this.store.dispatch({ type: "ensure_session", key: input.sessionKey });+ this.store.dispatch({+ type: "add_optimistic_turn",+ key: input.sessionKey,+ user: input.user,+ assistant: input.assistant,+ });+ const runtime = this.runtime(input.sessionKey);+ runtime.connect();+ runtime.send(input.command);+ }++ cancelTurn(sessionKey: string): void {+ const session = this.store.getState().sessions[sessionKey];+ if (!session?.activeTurnId) return;+ this.store.dispatch({ type: "cancel_requested", key: sessionKey });+ this.runtime(sessionKey).cancel(buildCancelTurn(session.activeTurnId));+ }++ submitReply(input: {+ sessionKey: string;+ text?: string;+ answers?: Array<{ questionId: string; text: string }>;+ }): void {+ const turnId = this.store.getState().sessions[input.sessionKey]?.activeTurnId;+ if (!turnId) return;+ this.runtime(input.sessionKey).send(buildSubmitUserReply({ turnId, ...input }));+ }++ regenerate(sessionId: string, overrides?: Record<string, unknown>): void {+ const runtime = this.runtime(sessionId);+ runtime.connect();+ runtime.send(buildRegenerate({ sessionId, overrides }));+ }++ async selectBranch(sessionId: string, parentKey: string, childId: number): Promise<void> {+ const current = this.store.getState().sessions[sessionId]?.selectedBranches ?? {};+ const next = { ...current, [parentKey]: childId };+ this.store.dispatch({ type: "set_branch", key: sessionId, parentKey, childId });+ await this.sessions.selectBranch(sessionId, next);+ }++ async deleteMessages(sessionId: string, messageId: number, pairedId?: number): Promise<void> {+ await this.sessions.removeMessage(sessionId, messageId);+ this.store.dispatch({+ type: "delete_messages",+ key: sessionId,+ ids: pairedId === undefined ? [messageId] : [messageId, pairedId],+ });+ }++ close(): void {+ for (const runtime of this.runtimes.values()) runtime.stop();+ this.runtimes.clear();+ }++ private runtime(key: string): TurnRuntimeClient {+ let runtime = this.runtimes.get(key);+ if (!runtime) {+ runtime = this.runtimeFactory(key);+ this.runtimes.set(key, runtime);+ }+ return runtime;+ }+}diff --git a/web/features/chat/store/reducer.ts b/web/features/chat/store/reducer.tsindex 947f5e7dd..4d77a374d 100644--- a/web/features/chat/store/reducer.ts+++ b/web/features/chat/store/reducer.ts@@ -115,6 +115,20 @@ export function chatReducer(state: ChatStoreState, action: ChatStoreAction): Chareturn state.sessions[action.key] && state.activeKey !== action.key? { ...state, activeKey: action.key }: state;+ case "remove_session": {+ if (!state.sessions[action.key]) return state;+ const sessions = { ...state.sessions };+ delete sessions[action.key];+ return {+ ...state,+ activeKey: state.activeKey === action.key ? null : state.activeKey,+ sessions,+ sidebar: {+ revision: state.sidebar.revision + 1,+ sessions: state.sidebar.sessions.filter((item) => item.key !== action.key),+ },+ };+ }case "load_session": {const next = {...state,diff --git a/web/tests/chat-provider-topology.test.ts b/web/tests/chat-provider-topology.test.tsnew file mode 100644index 000000000..213999819--- /dev/null+++ b/web/tests/chat-provider-topology.test.ts@@ -0,0 +1,30 @@+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import test from "node:test";++const source = (relative: string) => fs.readFileSync(path.resolve(process.cwd(), relative), "utf8");++test("workspace owns one runtime and Reading does not nest another", () => {+ assert.match(source("app/(workspace)/layout.tsx"), /ChatRuntimeProvider/);+ assert.doesNotMatch(+ source("app/(workspace)/reading/layout.tsx"),+ /ChatRuntimeProvider|UnifiedChatProvider/,+ );+});++test("Mastery study receives its own runtime outside the workspace group", () => {+ assert.match(+ source("app/(utility)/mastery/[pathId]/study/layout.tsx"),+ /ChatRuntimeProvider/,+ );+});++test("the runtime provider owns store, actions, transport, and cleanup", () => {+ const provider = source("features/chat/ChatRuntimeProvider.tsx");+ assert.match(provider, /createChatStore/);+ assert.match(provider, /new ChatActions/);+ assert.match(provider, /new TurnRuntimeClient/);+ assert.match(provider, /actions\.close/);+ assert.match(provider, /cannot be nested/);+});diff --git a/web/tests/reading-v2-surface.test.ts b/web/tests/reading-v2-surface.test.tsindex 2fddbe894..23702d5d6 100644--- a/web/tests/reading-v2-surface.test.ts+++ b/web/tests/reading-v2-surface.test.ts@@ -89,10 +89,10 @@ test("reading is reachable only through its own workspace", () => {assert.doesNotMatch(css, /dt-reader-shell|--reader-width/);});-test("reading owns an isolated chat runtime instead of inheriting Home's stream", () => {+test("reading reuses the workspace runtime without nesting another provider", () => {const layout = source("app/(workspace)/reading/layout.tsx");- assert.match(layout, /UnifiedChatProvider/);+ assert.doesNotMatch(layout, /UnifiedChatProvider|ChatRuntimeProvider/);assert.match(layout, /QuizFollowupProvider/);assert.match(layout, /GeogebraTabProvider/);});