refactor(web): remove v1 chat transport and legacy surfaces

This commit is contained in:
Bingxi Zhao (Frank)
2026-09-01 20:16:46 +08:00
parent 829be646a1
commit bfdf874a10
85 changed files with 411 additions and 591 deletions
@@ -34,12 +34,12 @@ import {
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
import { useImeComposing } from "@/lib/use-ime-composing";
import { shouldAppendEventContent } from "@/lib/stream";
import {
UnifiedWSClient,
type StartTurnMessage,
type StreamEvent,
} from "@/lib/unified-ws";
import type { MessageAttachment } from "@/features/chat/compat/UnifiedChatFacade";
import type {
StartTurnMessage,
StreamEvent,
} from "@/features/chat/model/protocol";
import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";
import type { MessageAttachment } from "@/features/chat/ChatStateAdapter";
import type { Page, Book } from "@/lib/book-types";
interface ChatMessage {
@@ -113,7 +113,7 @@ export default function BookChatPanel({
const attachmentLimits = useAttachmentLimits();
const [attachmentError, setAttachmentError] = useState<string | null>(null);
const sessionIdRef = useRef<string | null>(null);
const clientRef = useRef<UnifiedWSClient | null>(null);
const clientRef = useRef<UnifiedTurnClient | null>(null);
const retryTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
const scrollerRef = useRef<HTMLDivElement | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
@@ -262,16 +262,16 @@ export default function BookChatPanel({
});
}
function ensureClient(): UnifiedWSClient {
function ensureClient(): UnifiedTurnClient {
if (clientRef.current) return clientRef.current;
const client = new UnifiedWSClient(handleEvent, () => setBusy(false));
const client = new UnifiedTurnClient(handleEvent, () => setBusy(false));
clientRef.current = client;
client.connect();
return client;
}
function sendWithRetry(
client: UnifiedWSClient,
client: UnifiedTurnClient,
payload: StartTurnMessage,
attempt = 0,
) {
+1 -1
View File
@@ -17,7 +17,7 @@ import {
sameLLMSelection,
type LLMOption,
} from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import {
createPartner,
getToolOptions,
+8 -8
View File
@@ -7,11 +7,11 @@ import WhisperComposer from "@/components/whisper/WhisperComposer";
import WhisperMessageList from "@/components/whisper/WhisperMessageList";
import WhisperRoomChip from "@/components/whisper/WhisperRoomChip";
import { useCapabilityFilter } from "@/features/capabilities/useCapabilityCatalog";
import {
UnifiedWSClient,
type StartTurnMessage,
type StreamEvent,
} from "@/lib/unified-ws";
import type {
StartTurnMessage,
StreamEvent,
} from "@/features/chat/model/protocol";
import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";
import {
filterMessagesForSeat,
looksLikeCrisisRedirect,
@@ -50,7 +50,7 @@ export default function WhisperPage() {
const [connected, setConnected] = useState(false);
const [everConnected, setEverConnected] = useState(false);
const clientRef = useRef<UnifiedWSClient | null>(null);
const clientRef = useRef<UnifiedTurnClient | null>(null);
const seatRef = useRef<WhisperSeat>(seat);
const roomIdRef = useRef<string | null>(roomId);
const sessionBySeatRef = useRef<Record<WhisperSeat, string | null>>({
@@ -137,7 +137,7 @@ export default function WhisperPage() {
}, []);
useEffect(() => {
const client = new UnifiedWSClient(handleEvent, () => {
const client = new UnifiedTurnClient(handleEvent, () => {
setBusy(false);
setConnected(false);
});
@@ -147,7 +147,7 @@ export default function WhisperPage() {
// cascaded a render.
client.connect();
// Poll readyState until open (UnifiedWSClient has no onOpen hook).
// Poll the adapter state until the validated v2 runtime is connected.
const poll = window.setInterval(() => {
if (client.connected) {
setConnected(true);
+1 -1
View File
@@ -9,7 +9,7 @@ import {
collectNarrationCallIds,
shouldAppendEventContent,
} from "@/lib/stream";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/**
* v3 ``ask_user`` payload. Mirrors ``deeptutor.tools.ask_user.AskUserPayload``.
+1 -1
View File
@@ -43,7 +43,7 @@ import type { StudyCourse } from "@/lib/courses-api";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import type { LLMOption } from "@/lib/llm-options";
import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";
import type { SpaceMemoryFile } from "@/lib/space-items";
@@ -1,8 +0,0 @@
/**
* @deprecated Import message presentation from `features/chat/messages`.
* This compatibility export contains no rendering implementation.
*/
export {
ChatMessageList,
getModeBadgeLabel,
} from "@/features/chat/messages/ChatMessageList";
+1 -1
View File
@@ -5,7 +5,7 @@ import { AlertCircle, Bot, Check, ChevronDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useLingerExpand } from "@/hooks/use-linger-expand";
import ProviderIcon from "@/components/common/ProviderIcon";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import {
llmSelectionKey,
sameLLMSelection,
@@ -34,7 +34,7 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";
import type { MessageAttachment } from "@/features/chat/compat/UnifiedChatFacade";
import type { MessageAttachment } from "@/features/chat/ChatStateAdapter";
import { listSessions, type SessionSummary } from "@/lib/session-api";
import { listNotebooks, type NotebookSummary } from "@/lib/notebook-api";
import { bookApi } from "@/lib/book-api";
@@ -58,8 +58,8 @@ import SubagentTabBody from "@/components/chat/home/SubagentTabBody";
import type { QuizFollowupTabContext } from "@/context/QuizFollowupContext";
import type { GeogebraTabPayload } from "@/context/GeogebraTabContext";
import { apiUrl } from "@/lib/api";
import type { MessageAttachment } from "@/features/chat/compat/UnifiedChatFacade";
import type { StreamEvent } from "@/lib/unified-ws";
import type { MessageAttachment } from "@/features/chat/ChatStateAdapter";
import type { StreamEvent } from "@/features/chat/model/protocol";
import {
normalizeSelectedText,
selectionTutorKey,
@@ -45,7 +45,7 @@ import { listLLMOptions, type LLMOption } from "@/lib/llm-options";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { SpaceMemoryFile } from "@/lib/space-items";
import { getSubagentSettings } from "@/lib/subagents-api";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import {
DEFAULT_QUIZ_CONFIG,
buildQuizWSConfig,
@@ -2,7 +2,7 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import { getTraceMeta } from "@/features/chat/trace";
/**
+1 -1
View File
@@ -7,7 +7,7 @@ import { ArrowUp, Loader2 } from "lucide-react";
import SubagentRunTranscript from "@/components/chat/home/SubagentRunTranscript";
import { getTraceMeta } from "@/features/chat/trace";
import { streamSubagentMessage } from "@/lib/subagents-api";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/**
* A connected subagent's run tab: the streamed transcript plus an input box to
-15
View File
@@ -1,15 +0,0 @@
/**
* @deprecated Import trace presentation from `features/chat/trace`.
* This path remains temporarily for independent feature migrations.
*/
export {
AssistantActivity,
CallTracePanel,
NestedTraceFlow,
ResearchStagePanel,
StreamingStatus,
TraceFlow,
getLatestToolProgress,
getToolProvider,
getTraceMeta,
} from "@/features/chat/trace/TracePresentation";
+1 -1
View File
@@ -5,7 +5,7 @@ import { Fragment, memo, useMemo } from "react";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import ModelThinkingCard from "@/components/common/ModelThinkingCard";
import { useReading } from "@/context/ReadingContext";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import { useWatching } from "@/context/WatchingContext";
import {
hasVisibleMarkdownContent,
Binary file not shown.
+1 -1
View File
@@ -28,7 +28,7 @@ import {
sameLLMSelection,
type LLMOption,
} from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import { apiFetch, apiUrl } from "@/lib/api";
import {
useMemoryRun,
+1 -1
View File
@@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import i18n from "i18next";
import { apiFetch, apiUrl } from "@/lib/api";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
export type RunMode = "update" | "audit" | "dedup";
export type RunStatus = "queued" | "running" | "cancelled" | "done" | "error";
+1 -1
View File
@@ -29,7 +29,7 @@ import { displaySessionTitle } from "@/lib/session-title";
import { createPartnerDraftPublisher } from "@/lib/partner-chat-draft";
import { ReconnectingWebSocket } from "@/lib/reconnecting-websocket";
import type { ExportableMessage } from "@/lib/chat-export";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import { docIconFor, formatBytes, isSvgFilename } from "@/lib/doc-attachments";
import {
isNarrationMarker,
+1 -1
View File
@@ -11,7 +11,7 @@ import { Loader2, Plus, Save, Trash2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import PartnerModelSelect from "@/components/partners/PartnerModelSelect";
import { listLLMOptions, type LLMOption } from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
import {
addPartnerAssets,
getPartnerAssets,
@@ -12,7 +12,7 @@ import {
sameLLMSelection,
type LLMOption,
} from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
function formatContext(tokens?: number): string {
if (!tokens || tokens <= 0) return "";
@@ -15,7 +15,7 @@ import {
sameLLMSelection,
type LLMOption,
} from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
function formatContext(tokens?: number): string {
if (!tokens || tokens <= 0) return "";
@@ -28,7 +28,7 @@ import {
recomputeAnswerContent,
shouldAppendEventContent,
} from "@/lib/stream";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
export type SeatStatus = "waiting" | "working" | "done" | "error";
+1 -1
View File
@@ -326,7 +326,7 @@ function AssistantThreadMessage({
message: {
role: "user" | "assistant" | "system";
content: string;
events?: import("@/lib/unified-ws").StreamEvent[];
events?: import("@/features/chat/model/protocol").StreamEvent[];
};
isStreaming: boolean;
onSubmitUserReply: (reply: {
@@ -44,7 +44,7 @@ import SessionViewerPanel, {
} from "@/components/chat/home/SessionViewerPanel";
import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";
import Tooltip from "@/components/common/Tooltip";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { TurnStatusBar } from "@/features/chat/components/turn";
import { turnViewState } from "@/features/chat/model/turn-state";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
@@ -121,7 +121,7 @@ export function ReadingCompanion({
deleteTurn,
editMessage,
switchBranch,
} = useUnifiedChat();
} = useChatStateAdapter();
const confirmResearchOutline = useResearchOutlineContinuation();
const [showSessions, setShowSessions] = useState(false);
@@ -17,7 +17,7 @@ import { useCallback } from "react";
import StandaloneComposer, {
type StandaloneComposerSubmission,
} from "@/components/chat/home/StandaloneComposer";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";
import { hasPendingAskUser } from "@/lib/ask-user-state";
import { setReadingViewport } from "@/lib/reading-turn-state";
@@ -49,7 +49,7 @@ export function ReadingComposer({
setKBs,
setLLMSelection,
setPersonaSelection,
} = useUnifiedChat();
} = useChatStateAdapter();
const { capabilities, activeCapabilityValue, selectCapability } =
useWorkspaceChatActions();
@@ -28,7 +28,7 @@ import { useTranslation } from "react-i18next";
import type { JumpRequest } from "@/components/reading/PdfDocumentView";
import { READER_ASK_EVENT, ReaderPane } from "@/components/reading/ReaderPane";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import type { ReaderHeading } from "@/lib/reading-outline";
import { setReadingViewport } from "@/lib/reading-turn-state";
import { listNotebooks, type NotebookSummary } from "@/lib/notebook-api";
@@ -95,7 +95,7 @@ export function ReadingWorkspacePage() {
// The shell only needs to *send* (guided one-click prompts). Rendering the
// transcript, editing, branching and cancelling all belong to the companion,
// which reads them off the same context.
const { state, sendMessage } = useUnifiedChat();
const { state, sendMessage } = useChatStateAdapter();
const {
workspace,
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useReading } from "@/context/ReadingContext";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { courseSessionConfiguration } from "@/lib/course-session-scope";
import { getMaterial, getUnitText } from "@/lib/reading-api";
import {
@@ -54,7 +54,7 @@ export function useReadingWorkspace(
loadSession,
newSession,
cancelStreamingTurn,
} = useUnifiedChat();
} = useChatStateAdapter();
const [workspace, setWorkspace] = useState<ReadingWorkspace | null>(null);
const [conversations, setConversations] = useState<ReadingConversation[]>([]);
+2 -2
View File
@@ -7,7 +7,7 @@ import { SidebarShell } from "@/components/sidebar/SidebarShell";
import { LogoutButton } from "@/components/auth/LogoutButton";
import { AdminLink } from "@/components/auth/AdminLink";
import { ProfileLink } from "@/components/auth/ProfileLink";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import {
deleteSession,
listSessions,
@@ -36,7 +36,7 @@ export default function WorkspaceSidebar() {
selectedSessionId,
sessionStatuses,
sidebarRefreshToken,
} = useUnifiedChat();
} = useChatStateAdapter();
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [courses, setCourses] = useState<StudyCourse[]>([]);
const [masteryTopics, setMasteryTopics] = useState<MasteryTopicLabel[]>([]);
@@ -17,7 +17,7 @@ import { useCallback } from "react";
import StandaloneComposer, {
type StandaloneComposerSubmission,
} from "@/components/chat/home/StandaloneComposer";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";
import { hasPendingAskUser } from "@/lib/ask-user-state";
@@ -43,7 +43,7 @@ export function MasteryComposer({
setKBs,
setLLMSelection,
setPersonaSelection,
} = useUnifiedChat();
} = useChatStateAdapter();
const { capabilities, activeCapabilityValue, selectCapability } =
useWorkspaceChatActions();
@@ -22,7 +22,7 @@ import { buildSessionActivity } from "@/components/chat/home/SessionActivityPane
import SessionViewerPanel, {
type SessionViewerPanelHandle,
} from "@/components/chat/home/SessionViewerPanel";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { TurnStatusBar } from "@/features/chat/components/turn";
import { turnViewState } from "@/features/chat/model/turn-state";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
@@ -91,7 +91,7 @@ export function MasteryStudy({
deleteTurn,
editMessage,
switchBranch,
} = useUnifiedChat();
} = useChatStateAdapter();
const confirmResearchOutline = useResearchOutlineContinuation();
const { topic, topicError, knowledgeBases, sessionError, sessionLoading } =
useMasteryStudySession(pathId, routeSessionId, courseId);
+5 -5
View File
@@ -33,8 +33,8 @@ import {
type ChatMessage,
type LLMSelection,
type StreamEvent,
UnifiedWSClient,
} from "@/lib/unified-ws";
} from "@/features/chat/model/protocol";
import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";
import type { QuizQuestion } from "@/lib/quiz-types";
import type { SelectionTutorContext } from "@/lib/selection-tutor";
@@ -221,7 +221,7 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
);
const threadsRef = useRef<Record<string, FollowupThreadState>>({});
const runnersRef = useRef<
Map<string, { questionKey: string; client: UnifiedWSClient }>
Map<string, { questionKey: string; client: UnifiedTurnClient }>
>(new Map());
// Notebook entry ids per question — captured from sendMessage so the
// ``session`` event handler can persist ``followup_session_id`` on the
@@ -356,7 +356,7 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
}
const record = {
questionKey: key,
client: new UnifiedWSClient(
client: new UnifiedTurnClient(
(event) => handleThreadEvent(key, event),
() => {
const current = threadsRef.current[key];
@@ -466,7 +466,7 @@ export function QuizFollowupProvider({ children }: ProviderProps) {
);
if (!current.isStreaming && !pendingAskUser) return;
const message: import("@/lib/unified-ws").SubmitUserReplyMessage = {
const message: import("@/features/chat/model/protocol").SubmitUserReplyMessage = {
type: "submit_user_reply",
turn_id: turnId,
};
+1 -1
View File
@@ -33,7 +33,7 @@ import {
* changes the URL from `/home` to `/home/<id>`, which remounts the page
* component. State held inside the reader pane died with it, so the document
* vanished the moment the user asked their first question. The layout persists
* across that navigation — which is exactly why `UnifiedChatProvider` sits there
* across that navigation — which is exactly why the chat runtime sits there
* too.
*
* The viewport (scroll position, selection) is deliberately NOT state: it
+2 -2
View File
@@ -3,7 +3,7 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import type { StreamEvent } from "@/contracts/generated/turn-protocol";
import { UnifiedChatProvider } from "./compat/UnifiedChatFacade";
import { ChatStateAdapterProvider } from "./ChatStateAdapter";
import { ChatActions } from "./store/ChatActions";
import { ChatStoreProvider } from "./store/ChatStoreProvider";
@@ -59,7 +59,7 @@ export function ChatRuntimeProvider({ children }: { children: ReactNode }) {
return (
<ChatRuntimeContext.Provider value={value}>
<ChatStoreProvider store={value.store}>
<UnifiedChatProvider>{children}</UnifiedChatProvider>
<ChatStateAdapterProvider>{children}</ChatStateAdapterProvider>
</ChatStoreProvider>
</ChatRuntimeContext.Provider>
);
@@ -18,8 +18,8 @@ import {
readStoredResponseLanguage,
writeStoredActiveSessionId,
} from "@/context/app-shell-storage";
import type { StreamEvent, ChatMessage, LLMSelection } from "@/lib/unified-ws";
import { UnifiedWSClient } from "@/lib/unified-ws";
import type { StreamEvent, ChatMessage, LLMSelection } from "@/features/chat/model/protocol";
import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";
import {
getSession,
deleteMessage,
@@ -1198,7 +1198,7 @@ function hydrateRequestSnapshot(
return snapshot;
}
export function UnifiedChatProvider({
export function ChatStateAdapterProvider({
children,
}: {
children: React.ReactNode;
@@ -1210,7 +1210,7 @@ export function UnifiedChatProvider({
string,
{
key: string;
client: UnifiedWSClient;
client: UnifiedTurnClient;
}
>
>(new Map());
@@ -1464,7 +1464,7 @@ export function UnifiedChatProvider({
}
const record = {
key,
client: new UnifiedWSClient(
client: new UnifiedTurnClient(
(event) => handleRunnerEvent(record.key, event),
() => {
const session = stateRef.current.sessions[record.key];
@@ -2029,7 +2029,7 @@ export function UnifiedChatProvider({
if (!session || !turnId || (!session.isStreaming && !pendingAskUser)) {
return;
}
const message: import("@/lib/unified-ws").SubmitUserReplyMessage = {
const message: import("@/features/chat/model/protocol").SubmitUserReplyMessage = {
type: "submit_user_reply",
turn_id: turnId,
};
@@ -2293,7 +2293,7 @@ export function UnifiedChatProvider({
// Memoize the context value so consumers don't re-render on every render of
// this provider. Without this wrap, every stream-event-driven reducer
// dispatch produced a fresh object identity, cascading a re-render through
// every `useUnifiedChat()` consumer (chat page, composer, sidebar) on each
// every adapter consumer (chat page, composer, sidebar) on each
// token. The callbacks below are already stable via useCallback; the only
// things that should change identity are derivedState, sessionStatuses,
// and sidebarRefreshToken.
@@ -2354,10 +2354,10 @@ export function UnifiedChatProvider({
return <ChatCtx.Provider value={value}>{children}</ChatCtx.Provider>;
}
/** @deprecated Compatibility-only hook while leaf surfaces move to narrow selectors/actions. */
export function useUnifiedChat() {
/** Transitional state adapter for surfaces that have not moved to store selectors yet. */
export function useChatStateAdapter() {
const ctx = useContext(ChatCtx);
if (!ctx)
throw new Error("useUnifiedChat must be inside UnifiedChatProvider");
throw new Error("useChatStateAdapter must be inside ChatStateAdapterProvider");
return ctx;
}
@@ -52,10 +52,10 @@ import {
} from "@/context/GeogebraTabContext";
import { BookmarkPlus, Download, PanelRight } from "lucide-react";
import {
useUnifiedChat,
useChatStateAdapter,
type MessageAttachment,
type MessageRequestSnapshot,
} from "@/features/chat/compat/UnifiedChatFacade";
} from "@/features/chat/ChatStateAdapter";
import { useAppShell } from "@/context/AppShellContext";
import {
@@ -63,7 +63,7 @@ import {
WatchingPane,
} from "@/components/watching/WatchingPane";
import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";
import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";
import type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";
import {
extractBase64FromDataUrl,
readFileAsDataUrl,
@@ -291,7 +291,7 @@ export default function ChatWorkspace() {
showCachedSession,
renameSessionTitle,
setCourseId,
} = useUnifiedChat();
} = useChatStateAdapter();
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [knowledgeBasesLoaded, setKnowledgeBasesLoaded] = useState(false);
@@ -38,7 +38,7 @@ import Tooltip from "@/components/common/Tooltip";
import type {
MessageAttachment,
MessageRequestSnapshot,
} from "@/features/chat/compat/UnifiedChatFacade";
} from "@/features/chat/ChatStateAdapter";
import { apiFetch, apiUrl } from "@/lib/api";
import { docIconFor } from "@/lib/doc-attachments";
import { useVoiceAutoplay } from "@/hooks/useVoiceAutoplay";
@@ -49,7 +49,7 @@ import {
extractStreamingQuizQuestions,
} from "@/lib/quiz-types";
import { extractVisualizeResult } from "@/lib/visualize-types";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import type { SelectedBookReference } from "@/lib/book-references";
import { buildVisiblePath, type SiblingInfo } from "@/lib/message-branches";
+130
View File
@@ -0,0 +1,130 @@
/** UI-facing aliases for the validated v2 turn protocol. */
export type {
ClientCommand,
ServerEvent,
} from "@/contracts/generated/turn-protocol";
export type StreamEventType =
| "stage_start"
| "stage_end"
| "thinking"
| "observation"
| "content"
| "tool_call"
| "tool_result"
| "progress"
| "sources"
| "result"
| "error"
| "session"
| "session_meta"
| "wait_for_input"
| "done";
export interface StreamEvent {
type: StreamEventType;
source: string;
stage: string;
content: string;
metadata: Record<string, unknown>;
session_id?: string;
turn_id?: string;
seq?: number;
timestamp: number;
}
export interface LLMSelection {
profile_id: string;
model_id: string;
}
export interface StartTurnMessage {
type: "start_turn";
content: string;
tools?: string[];
capability?: string | null;
workspace_mode?: "immersive_reading" | "mastery_path" | "";
knowledge_bases?: string[];
session_id?: string | null;
attachments?: Array<{
type: string;
url?: string;
base64?: string;
filename?: string;
mime_type?: string;
}>;
language?: string;
config?: Record<string, unknown>;
notebook_references?: Array<{ notebook_id: string; record_ids: string[] }>;
history_references?: string[];
question_notebook_references?: number[];
book_references?: Array<{ book_id: string; page_ids: string[] }>;
reading_references?: Array<{
material_id: string;
revision: number;
locators: number[];
}>;
mastery_path_id?: string;
reading_workspace_id?: string;
reading_material_id?: string;
reading_material_revision?: number;
reading_viewport?: { locator?: number; selection?: string };
timed_media_id?: string;
timed_media_viewport?: { time_seconds: number };
persona?: string;
llm_selection?: LLMSelection | null;
parent_message_id?: number | null;
[key: string]: unknown;
}
export interface SubscribeTurnMessage {
type: "subscribe_turn";
turn_id: string;
after_seq?: number;
}
export interface SubscribeSessionMessage {
type: "subscribe_session";
session_id: string;
after_seq?: number;
}
export interface ResumeTurnMessage {
type: "resume_from";
turn_id: string;
seq?: number;
}
export interface UnsubscribeMessage {
type: "unsubscribe";
turn_id?: string;
session_id?: string;
}
export interface CancelTurnMessage {
type: "cancel_turn";
turn_id: string;
}
export interface RegenerateMessage {
type: "regenerate";
session_id: string;
overrides?: Record<string, unknown>;
}
export interface SubmitUserReplyMessage {
type: "submit_user_reply";
turn_id: string;
text?: string;
answers?: Array<{ questionId: string; text: string }>;
}
export type ChatMessage =
| StartTurnMessage
| SubscribeTurnMessage
| SubscribeSessionMessage
| ResumeTurnMessage
| UnsubscribeMessage
| CancelTurnMessage
| RegenerateMessage
| SubmitUserReplyMessage;
@@ -17,7 +17,7 @@ import {
describeProviderTool,
type ToolProvider,
} from "@/lib/trace-tools";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import {
getLatestToolProgress as selectLatestToolProgress,
getToolProvider as selectToolProvider,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
export interface TraceMetadata {
call_id?: string;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
import { formatProgressLabel, type ToolProvider } from "@/lib/trace-tools";
import type {
StreamingMode,
@@ -0,0 +1,93 @@
import type { ClientCommand, ServerEvent } from "@/contracts/generated/turn-protocol";
import type { ChatMessage, StreamEvent, StreamEventType } from "../model/protocol";
import { TurnRuntimeClient, type RuntimeConnectionState } from "./TurnRuntimeClient";
const STREAM_TYPES = new Set<StreamEventType>([
"stage_start",
"stage_end",
"thinking",
"observation",
"content",
"tool_call",
"tool_result",
"progress",
"sources",
"result",
"error",
"session",
"session_meta",
"wait_for_input",
"done",
]);
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
}
function toStreamEvent(event: ServerEvent): StreamEvent | null {
const raw = event as unknown as Record<string, unknown>;
const type = raw.type;
if (typeof type !== "string" || !STREAM_TYPES.has(type as StreamEventType)) return null;
return {
type: type as StreamEventType,
source: typeof raw.source === "string" ? raw.source : "",
stage: typeof raw.stage === "string" ? raw.stage : "",
content: typeof raw.content === "string" ? raw.content : "",
metadata: asRecord(raw.metadata),
session_id: typeof raw.session_id === "string" ? raw.session_id : undefined,
turn_id: typeof raw.turn_id === "string" ? raw.turn_id : undefined,
seq: typeof raw.seq === "number" ? raw.seq : undefined,
timestamp: typeof raw.timestamp === "number" ? raw.timestamp : Date.now() / 1000,
};
}
function command(message: ChatMessage): ClientCommand {
return { ...message, protocol_version: "2.0" } as ClientCommand;
}
/** Transitional surface API backed entirely by the validated v2 runtime. */
export class UnifiedTurnClient {
private readonly runtime: TurnRuntimeClient;
private connectionState: RuntimeConnectionState = "idle";
private closeNotified = false;
constructor(onEvent: (event: StreamEvent) => void, onClose?: () => void) {
this.runtime = new TurnRuntimeClient({
onEvent(event) {
const streamEvent = toStreamEvent(event);
if (streamEvent) onEvent(streamEvent);
},
onStateChange: (state) => {
this.connectionState = state;
if (state === "idle" && !this.closeNotified) {
this.closeNotified = true;
onClose?.();
}
if (state === "connected") this.closeNotified = false;
},
});
}
get connected(): boolean {
return this.connectionState === "connected";
}
setResumeState(turnId: string | null, seq: number): void {
this.runtime.setResumeCursor(turnId, seq);
}
connect(): void {
this.runtime.connect();
}
send(message: ChatMessage): void {
this.runtime.send(command(message));
}
disconnect(): void {
this.runtime.stop();
this.runtime.setResumeCursor(null, 0);
this.connectionState = "stopped";
}
}
+3 -3
View File
@@ -5,9 +5,9 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
useUnifiedChat,
useChatStateAdapter,
type SessionConfiguration,
} from "@/features/chat/compat/UnifiedChatFacade";
} from "@/features/chat/ChatStateAdapter";
import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";
import {
fetchMasteryTopic,
@@ -43,7 +43,7 @@ export function useMasteryStudySession(
configureSession,
loadSession,
showCachedSession,
} = useUnifiedChat();
} = useChatStateAdapter();
const [topic, setTopic] = useState<MasteryTopic | null>(null);
const [topicError, setTopicError] = useState<string | null>(null);
+3 -3
View File
@@ -4,13 +4,13 @@ import { useCallback } from "react";
import {
type MessageRequestSnapshot,
useUnifiedChat,
} from "@/features/chat/compat/UnifiedChatFacade";
useChatStateAdapter,
} from "@/features/chat/ChatStateAdapter";
import type { OutlineItem } from "@/lib/research-types";
/** Resume Deep Research after its editable outline, on any chat surface. */
export function useResearchOutlineContinuation() {
const { sendMessage } = useUnifiedChat();
const { sendMessage } = useChatStateAdapter();
return useCallback(
(
outline: OutlineItem[],
+1 -1
View File
@@ -11,7 +11,7 @@ import {
} from "@/context/app-shell-storage";
import { setTheme, type Theme } from "@/lib/theme";
import { collectAppliedSettingIds } from "@/lib/setup-signals";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
const THEMES: readonly Theme[] = ["light", "dark", "glass", "snow"];
+2 -2
View File
@@ -2,14 +2,14 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useUnifiedChat } from "@/features/chat/compat/UnifiedChatFacade";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import { getChatCapability } from "@/features/capabilities/presentation";
import { useCapabilityCatalog } from "@/features/capabilities/useCapabilityCatalog";
import { getEnabledOptionalTools } from "@/lib/tools-settings";
/** Keep Reading/Mastery action selection on the same tool policy as Home. */
export function useWorkspaceChatActions() {
const { state, setCapability, setTools } = useUnifiedChat();
const { state, setCapability, setTools } = useChatStateAdapter();
const { capabilities: catalogCapabilities } = useCapabilityCatalog();
const workspaceCapabilities = useMemo(
() =>
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "./unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
type MessageWithEvents = {
events?: StreamEvent[];
-16
View File
@@ -472,21 +472,5 @@ export const bookApi = {
),
};
export interface LegacyChatSession {
session_id: string;
messages?: Array<{ role: string; content: string }>;
}
export async function getLegacyChatSession(
session_id: string,
): Promise<LegacyChatSession | null> {
const res = await apiFetch(
apiUrl(`/api/v1/chat/sessions/${encodeURIComponent(session_id)}`),
);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`chat session ${session_id} → ${res.status}`);
return (await res.json()) as LegacyChatSession;
}
// Re-exported so callers can keep importing the event type from book-api.
export type { BookWsEvent } from "@/lib/book-ws-operation";
-9
View File
@@ -1,9 +0,0 @@
/** @deprecated Import the canonical capability feature directly. */
import { fetchCapabilityCatalog } from "@/features/capabilities/api";
export { useCapabilityFilter } from "@/features/capabilities/useCapabilityCatalog";
export type { CapabilityFilter } from "@/features/capabilities/useCapabilityCatalog";
export async function listRegisteredCapabilities(): Promise<string[]> {
return (await fetchCapabilityCatalog()).map((capability) => capability.id);
}
-2
View File
@@ -1,2 +0,0 @@
/** @deprecated Import capability presentation from `@/features/capabilities/presentation`. */
export * from "@/features/capabilities/presentation";
+1 -1
View File
@@ -12,7 +12,7 @@
* agree on a stable ``data-turn-key`` per bubble.
*/
import type { MessageItem } from "@/features/chat/compat/UnifiedChatFacade";
import type { MessageItem } from "@/features/chat/ChatStateAdapter";
import { buildVisiblePath } from "@/lib/message-branches";
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/**
* Reading the `course_study` capability's hand-off signals off a turn's stream.
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "./unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
export type DeepResearchFollowupStatus = "researching" | "done" | "failed";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { LLMOption, LLMOptionsResponse } from "@/lib/llm-options";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
export type LLMOptionsStatus = "loading" | "ready" | "error";
+1 -1
View File
@@ -1,6 +1,6 @@
import { apiFetch, apiUrl } from "@/lib/api";
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
const LLM_OPTIONS_CACHE_KEY = "llm-options:list";
const DEFAULT_LLM_OPTIONS_TIMEOUT_MS = 30_000;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
export interface PartnerDraftSnapshot {
events: StreamEvent[];
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/** Versioned payload emitted by the Chat engine's `propose_partner` tool. */
export interface PartnerDraftData {
+1 -1
View File
@@ -3,7 +3,7 @@
import { apiFetch, apiUrl } from "@/lib/api";
import { browserStorage } from "@/shared/storage";
import type { PartnerInfo } from "@/lib/partners-api";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
export interface PartnerGroupMember extends Pick<
PartnerInfo,
+1 -1
View File
@@ -1,7 +1,7 @@
/** Typed client for the /api/v1/partners backend. */
import { apiFetch, apiUrl } from "@/lib/api";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMSelection } from "@/features/chat/model/protocol";
export interface PartnerInfo {
partner_id: string;
+2 -2
View File
@@ -12,8 +12,8 @@ import type {
MessageAttachment,
MessageItem,
MessageRequestSnapshot,
} from "@/features/chat/compat/UnifiedChatFacade";
import type { StreamEvent } from "@/lib/unified-ws";
} from "@/features/chat/ChatStateAdapter";
import type { StreamEvent } from "@/features/chat/model/protocol";
/** Artifact URLs are `/api/outputs/<path under the data root>`. */
const OUTPUTS_URL_PREFIX = "/api/outputs/";
+1 -1
View File
@@ -1,6 +1,6 @@
import { apiFetch, apiUrl } from "@/lib/api";
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";
import type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";
export interface SessionMessage {
id: number;
-2
View File
@@ -1,2 +0,0 @@
/** @deprecated Import settings navigation from the settings feature. */
export * from "@/features/settings/navigation/settings-nav";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/**
* Reading the setup capability's signals off a turn's event stream.
+1 -1
View File
@@ -1,4 +1,4 @@
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
type ContentMeta = {
call_id?: string;
+1 -1
View File
@@ -14,7 +14,7 @@
* state that resets on remount.
*/
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
/**
* Elapsed seconds for the turn the ``events`` belong to.
-20
View File
@@ -1,20 +0,0 @@
const MAX_RECONNECT_ATTEMPTS = 5;
const BASE_RECONNECT_DELAY_MS = 200;
export function shouldStopReconnecting({
attempt,
activeTurnId,
}: {
attempt: number;
activeTurnId: string | null;
}): boolean {
return !activeTurnId && attempt >= MAX_RECONNECT_ATTEMPTS;
}
export function reconnectDelayMs(attempt: number): number {
const cappedAttempt = Math.min(
Math.max(0, attempt),
MAX_RECONNECT_ATTEMPTS - 1,
);
return BASE_RECONNECT_DELAY_MS * Math.pow(2, cappedAttempt);
}
-358
View File
@@ -1,358 +0,0 @@
/**
* Unified WebSocket Client
*
* Connects to the single `/api/v1/ws` endpoint and provides
* a typed streaming interface for the new ChatOrchestrator protocol.
*
* Features:
* - Client-side heartbeat (30s ping / 45s dead-connection detection)
* - Auto-reconnect with exponential backoff (active turns keep retrying)
* - resume_from after reconnection to continue a streaming turn
*/
import { wsUrl } from "./api";
import {
reconnectDelayMs,
shouldStopReconnecting,
} from "./unified-ws-recovery";
// ---- StreamEvent types (mirror Python StreamEventType) ----
export type StreamEventType =
| "stage_start"
| "stage_end"
| "thinking"
| "observation"
| "content"
| "tool_call"
| "tool_result"
| "progress"
| "sources"
| "result"
| "error"
| "session"
| "session_meta"
| "wait_for_input"
| "done";
export interface StreamEvent {
type: StreamEventType;
source: string;
stage: string;
content: string;
metadata: Record<string, unknown>;
session_id?: string;
turn_id?: string;
seq?: number;
timestamp: number;
}
export interface LLMSelection {
profile_id: string;
model_id: string;
}
// ---- Client message ----
export interface StartTurnMessage {
type: "message" | "start_turn";
content: string;
tools?: string[];
capability?: string | null;
/** Stable product surface; capability remains the action for this turn. */
workspace_mode?: "immersive_reading" | "mastery_path" | "";
knowledge_bases?: string[];
session_id?: string | null;
attachments?: {
type: string;
url?: string;
base64?: string;
filename?: string;
mime_type?: string;
}[];
language?: string;
config?: Record<string, unknown>;
notebook_references?: {
notebook_id: string;
record_ids: string[];
}[];
history_references?: string[];
question_notebook_references?: number[];
book_references?: {
book_id: string;
page_ids: string[];
}[];
/** Explicit units from imported Reading materials. The server resolves the
* exact stored revision; clients never send trusted content. */
reading_references?: {
material_id: string;
revision: number;
locators: number[];
}[];
/** Persistent mastery state to use independently of this chat session. */
mastery_path_id?: string;
/** Private Immersive Reading workspace that owns this turn/session. */
reading_workspace_id?: string;
/** Immersive reading: the document open in the reader pane, if any. Its
* presence is what activates the reading capability for the turn. */
reading_material_id?: string;
/** Immutable content revision displayed when this turn was submitted. */
reading_material_revision?: number;
/** What the reader is showing right now — the locator on screen and any text
* the user has selected. Advisory context, not a citation. */
reading_viewport?: {
locator?: number;
selection?: string;
};
/** Immersive Watching material and live player position. */
timed_media_id?: string;
timed_media_viewport?: { time_seconds: number };
persona?: string;
llm_selection?: LLMSelection | null;
/** Edit-branching: when present (even as ``null``) the new user message
* attaches at this exact parent — creating a sibling rather than
* appending to the session tail. */
parent_message_id?: number | null;
}
export interface SubscribeTurnMessage {
type: "subscribe_turn";
turn_id: string;
after_seq?: number;
}
export interface SubscribeSessionMessage {
type: "subscribe_session";
session_id: string;
after_seq?: number;
}
export interface ResumeTurnMessage {
type: "resume_from";
turn_id: string;
seq?: number;
}
export interface UnsubscribeMessage {
type: "unsubscribe";
turn_id?: string;
session_id?: string;
}
export interface CancelTurnMessage {
type: "cancel_turn";
turn_id: string;
}
export interface RegenerateMessage {
type: "regenerate";
session_id: string;
overrides?: Record<string, unknown>;
}
/**
* Deliver the user's answer for an ``ask_user`` paused turn so the
* agentic loop can resume on the same turn. The user's reply is
* substituted into the matching ``role=tool`` message body before the
* next LLM iteration runs.
*
* Either ``text`` (legacy single-question shape) or ``answers``
* (v2 multi-question shape) must be provided. When both are present
* the backend prefers ``answers``.
*/
export interface SubmitUserReplyMessage {
type: "submit_user_reply";
turn_id: string;
text?: string;
answers?: Array<{ questionId: string; text: string }>;
}
export type ChatMessage =
| StartTurnMessage
| SubscribeTurnMessage
| SubscribeSessionMessage
| ResumeTurnMessage
| UnsubscribeMessage
| CancelTurnMessage
| RegenerateMessage
| SubmitUserReplyMessage;
// ---- Connection manager ----
export type EventHandler = (event: StreamEvent) => void;
const HEARTBEAT_INTERVAL_MS = 30_000;
const HEARTBEAT_TIMEOUT_MS = 45_000;
export class UnifiedWSClient {
private ws: WebSocket | null = null;
private onEvent: EventHandler;
private onClose?: () => void;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private lastReceivedAt = 0;
private reconnectAttempt = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private intentionalClose = false;
private activeTurnId: string | null = null;
private lastSeq = 0;
constructor(onEvent: EventHandler, onClose?: () => void) {
this.onEvent = onEvent;
this.onClose = onClose;
}
/** Provide the current turn/seq so reconnection can resume the stream. */
setResumeState(turnId: string | null, seq: number): void {
this.activeTurnId = turnId;
this.lastSeq = seq;
}
connect(): void {
if (this.ws && this.ws.readyState <= WebSocket.OPEN) return;
this.intentionalClose = false;
const url = wsUrl("/api/v1/ws");
this.ws = new WebSocket(url);
this.ws.onopen = () => {
this.reconnectAttempt = 0;
this.lastReceivedAt = Date.now();
this.startHeartbeat();
if (this.activeTurnId) {
this.send({
type: "resume_from",
turn_id: this.activeTurnId,
seq: this.lastSeq,
});
}
};
this.ws.onmessage = (ev) => {
this.lastReceivedAt = Date.now();
try {
const event: StreamEvent = JSON.parse(ev.data);
// Heartbeat frames (client-sent ``ping`` echoed by some legacy
// backends, or ``pong`` from the modern handler) keep the socket
// alive but are not user-visible chat events. They MUST be dropped
// here — otherwise the message list renders them as "Unknown type"
// error rows, especially during long-running turns.
const type = (event as { type?: string }).type;
if (type === "ping" || type === "pong") return;
if (event.turn_id) this.activeTurnId = event.turn_id;
if (event.seq != null) this.lastSeq = Math.max(this.lastSeq, event.seq);
this.onEvent(event);
} catch {
console.warn("Unparseable WS message:", ev.data);
}
};
this.ws.onclose = () => {
this.ws = null;
this.stopHeartbeat();
if (!this.intentionalClose) {
this.attemptReconnect();
}
};
this.ws.onerror = () => {
// Browser Event objects serialize as `{}` and Next.js turns
// ``console.error`` into a blocking dev overlay, so this must not be an
// error-level log. ``onclose`` carries the actionable signal (reconnect
// vs. intentional disconnect); keep a debug breadcrumb so a socket that
// fails without ever closing is still visible.
if (this.intentionalClose) return;
console.debug("[unified-ws] socket error; awaiting close for the reason");
};
}
send(msg: ChatMessage): void {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
console.error("WebSocket not connected");
return;
}
this.ws.send(JSON.stringify(msg));
}
disconnect(): void {
this.intentionalClose = true;
this.stopHeartbeat();
this.clearReconnectTimer();
this.ws?.close();
this.ws = null;
this.resetResumeState();
}
get connected(): boolean {
return this.ws?.readyState === WebSocket.OPEN;
}
// ---- Heartbeat ----
private startHeartbeat(): void {
this.stopHeartbeat();
this.heartbeatTimer = setInterval(() => {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
if (Date.now() - this.lastReceivedAt > HEARTBEAT_TIMEOUT_MS) {
this.ws.close();
return;
}
try {
this.ws.send(JSON.stringify({ type: "ping" }));
} catch {
// send may fail if socket is closing
}
}, HEARTBEAT_INTERVAL_MS);
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
// ---- Reconnect ----
private attemptReconnect(): void {
if (
shouldStopReconnecting({
attempt: this.reconnectAttempt,
activeTurnId: this.activeTurnId,
})
) {
this.resetResumeState();
this.onClose?.();
return;
}
// A live turn continues on the backend even while the browser is offline.
// Keep retrying at a capped delay so ``onopen`` can issue ``resume_from``
// and replay everything after ``lastSeq`` when the network returns.
const delay = reconnectDelayMs(this.reconnectAttempt);
this.reconnectAttempt += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
}, delay);
}
private clearReconnectTimer(): void {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
private resetResumeState(): void {
this.activeTurnId = null;
this.lastSeq = 0;
this.reconnectAttempt = 0;
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import {
extractMessageSegments,
leadingTraceEvents,
} from "../components/chat/home/AskUserOptions";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
import { decodeEscapedUnicodeForDisplay } from "../lib/markdown-display";
function event(
+1 -1
View File
@@ -4,7 +4,7 @@ import {
hasPendingAskUser,
hasPendingAskUserInMessages,
} from "../lib/ask-user-state";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
function event(
type: StreamEvent["type"],
+4 -5
View File
@@ -98,10 +98,9 @@ test("component-owned capability types cannot return", () => {
path.resolve(process.cwd(), "components/chat/home/ChatComposer.tsx"),
"utf8",
);
const legacy = fs.readFileSync(
path.resolve(process.cwd(), "lib/chat-capabilities.ts"),
"utf8",
);
assert.doesNotMatch(composer, /export interface CapabilityDef/);
assert.doesNotMatch(legacy, /components\/chat\/home\/ChatComposer/);
assert.equal(
fs.existsSync(path.resolve(process.cwd(), "lib/chat-capabilities.ts")),
false,
);
});
+1 -1
View File
@@ -9,7 +9,7 @@ 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/,
/ChatRuntimeProvider|ChatStateAdapterProvider/,
);
});
+1 -1
View File
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
import {
authoritativeResearchReport,
isConfirmedResearchFollowup,
@@ -1,5 +1,3 @@
import fs from "node:fs";
import path from "node:path";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
@@ -31,15 +29,4 @@ describe("chat message feature", () => {
await user.click(screen.getByRole("button", { name: "Copy" }));
expect(copy).toHaveBeenCalledWith("Explain eigenvectors");
});
it("keeps legacy paths as implementation-free migration shells", () => {
for (const relative of [
"components/chat/home/ChatMessages.tsx",
"components/chat/home/TracePanels.tsx",
]) {
const source = fs.readFileSync(path.resolve(process.cwd(), relative), "utf8");
expect(source.split("\n").length).toBeLessThan(25);
expect(source).not.toMatch(/useState|useEffect|<div|<button/);
}
});
});
+61
View File
@@ -0,0 +1,61 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
const SOURCE_ROOTS = [
"app",
"components",
"context",
"features",
"hooks",
"lib",
"shared",
];
function sourceFiles(directory: string): string[] {
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) return sourceFiles(absolute);
return /\.(?:ts|tsx)$/.test(entry.name) ? [absolute] : [];
});
}
test("the frontend has no v1 chat transport or compatibility import surface", () => {
const cwd = process.cwd();
const files = SOURCE_ROOTS.flatMap((root) => sourceFiles(path.resolve(cwd, root)));
const forbidden = [
/\/api\/v1\/chat/,
/UnifiedWSClient/,
/lib\/unified-ws/,
/features\/chat\/compat\/UnifiedChatFacade/,
];
for (const file of files) {
const source = fs.readFileSync(file, "utf8");
for (const pattern of forbidden) {
assert.doesNotMatch(source, pattern, `${path.relative(cwd, file)} contains ${pattern}`);
}
}
for (const relative of [
"lib/unified-ws.ts",
"lib/unified-ws-recovery.ts",
"components/chat/home/ChatMessages.tsx",
"components/chat/home/TracePanels.tsx",
"lib/chat-capabilities.ts",
"lib/capabilities-api.ts",
"lib/settings-nav.ts",
]) {
assert.equal(fs.existsSync(path.resolve(cwd, relative)), false, `${relative} must stay deleted`);
}
});
test("all chat entry points share the validated v2 runtime", () => {
const adapter = fs.readFileSync(
path.resolve(process.cwd(), "features/chat/transport/UnifiedTurnClient.ts"),
"utf8",
);
assert.match(adapter, /TurnRuntimeClient/);
assert.match(adapter, /protocol_version: "2\.0"/);
});
+1 -1
View File
@@ -11,7 +11,7 @@ import {
selectChildBranch,
tipMessageId,
} from "../lib/message-branches";
import type { MessageItem } from "../features/chat/compat/UnifiedChatFacade";
import type { MessageItem } from "../features/chat/ChatStateAdapter";
test("optimistic ids are negative and strictly decreasing", () => {
const ids = Array.from({ length: 50 }, () => nextOptimisticId());
+1 -1
View File
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { buildVisiblePath } from "../lib/message-branches";
import type { MessageItem } from "../features/chat/compat/UnifiedChatFacade";
import type { MessageItem } from "../features/chat/ChatStateAdapter";
// Issue #912: deleting a turn left descendants pointing at deleted rows, so
// buildVisiblePath found no root message and rendered a blank chat while
+1 -1
View File
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
import { createPartnerDraftPublisher } from "../lib/partner-chat-draft";
function createFrameQueue() {
+1 -1
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { extractPartnerDraft } from "@/lib/partner-draft";
import type { StreamEvent } from "@/lib/unified-ws";
import type { StreamEvent } from "@/features/chat/model/protocol";
function toolResult(partnerDraft: Record<string, unknown>): StreamEvent {
return {
+2 -2
View File
@@ -16,9 +16,9 @@ import recordedEvents from "./fixtures/provider-trace-events.json";
import {
getLatestToolProgress,
getToolProvider,
} from "../components/chat/home/TracePanels";
} from "../features/chat/trace/TracePresentation";
import { describeProviderTool } from "../lib/trace-tools";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
const recorded = recordedEvents as unknown as Record<string, StreamEvent[]>;
+2 -2
View File
@@ -7,8 +7,8 @@ import {
import type {
MessageItem,
MessageRequestSnapshot,
} from "../features/chat/compat/UnifiedChatFacade";
import type { StreamEvent } from "../lib/unified-ws";
} from "../features/chat/ChatStateAdapter";
import type { StreamEvent } from "../features/chat/model/protocol";
/** A StreamEvent with only the fields the fold reads set explicitly. */
function event(
@@ -3,7 +3,10 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import { settingsAnchorHref, storagePathFor } from "../lib/settings-nav";
import {
settingsAnchorHref,
storagePathFor,
} from "../features/settings/navigation/settings-nav";
const readWebFile = (...parts: string[]) =>
readFileSync(path.join(process.cwd(), ...parts), "utf8");
+1 -1
View File
@@ -5,7 +5,7 @@ import {
collectAppliedSettingIds,
extractSetupCredential,
} from "../lib/setup-signals";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
function toolResult(
toolMetadata: Record<string, unknown>,
+1 -1
View File
@@ -5,7 +5,7 @@ import {
isNarrationMarker,
recomputeAnswerContent,
} from "../lib/stream";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
function event(
type: StreamEvent["type"],
+1 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { StreamEvent } from "../lib/unified-ws";
import type { StreamEvent } from "../features/chat/model/protocol";
import {
detectStreamingMode,
groupTraceEvents,
@@ -5,7 +5,7 @@ import type {
ChatMessage,
StreamEvent,
StreamEventType,
} from "../lib/unified-ws";
} from "../features/chat/model/protocol";
const waitForInputKind: StreamEventType = "wait_for_input";
-23
View File
@@ -1,23 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
reconnectDelayMs,
shouldStopReconnecting,
} from "../lib/unified-ws-recovery";
test("an active turn keeps reconnecting after the normal attempt budget", () => {
assert.equal(
shouldStopReconnecting({ attempt: 99, activeTurnId: "turn_research" }),
false,
);
assert.equal(
shouldStopReconnecting({ attempt: 5, activeTurnId: null }),
true,
);
});
test("active-turn reconnect backoff is capped", () => {
assert.equal(reconnectDelayMs(0), 200);
assert.equal(reconnectDelayMs(4), 3200);
assert.equal(reconnectDelayMs(99), 3200);
});