From bfdf874a10a0d9a1f190105dfe4d4cc48effdb57 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Tue, 1 Sep 2026 20:16:46 +0800 Subject: [PATCH] refactor(web): remove v1 chat transport and legacy surfaces --- .../book/components/BookChatPanel.tsx | 20 +- web/app/(workspace)/partners/new/page.tsx | 2 +- web/app/(workspace)/whisper/page.tsx | 16 +- web/components/chat/home/AskUserOptions.tsx | 2 +- web/components/chat/home/ChatComposer.tsx | 2 +- web/components/chat/home/ChatMessages.tsx | 8 - web/components/chat/home/ModelSelector.tsx | 2 +- .../chat/home/SessionActivityPanel.tsx | 2 +- .../chat/home/SessionViewerPanel.tsx | 4 +- .../chat/home/StandaloneComposer.tsx | 2 +- .../chat/home/SubagentRunTranscript.tsx | 2 +- web/components/chat/home/SubagentTabBody.tsx | 2 +- web/components/chat/home/TracePanels.tsx | 15 - web/components/common/AssistantResponse.tsx | 2 +- web/components/common/InlineFileCard.tsx | Bin 12948 -> 12959 bytes web/components/memory/MemoryRunPanel.tsx | 2 +- web/components/memory/useMemoryRun.ts | 2 +- web/components/partners/PartnerChat.tsx | 2 +- web/components/partners/PartnerConfigure.tsx | 2 +- .../partners/PartnerModelPicker.tsx | 2 +- .../partners/PartnerModelSelect.tsx | 2 +- .../partners/group/useGroupSession.ts | 2 +- web/components/quiz/QuizFollowupTabBody.tsx | 2 +- .../reading/workspace/ReadingCompanion.tsx | 4 +- .../reading/workspace/ReadingComposer.tsx | 4 +- .../reading/workspace/ReadingWorkspace.tsx | 4 +- .../reading/workspace/useReadingWorkspace.ts | 4 +- web/components/sidebar/WorkspaceSidebar.tsx | 4 +- .../space/learning/MasteryComposer.tsx | 4 +- .../space/learning/MasteryStudy.tsx | 4 +- web/context/QuizFollowupContext.tsx | 10 +- web/context/ReadingContext.tsx | 2 +- web/features/chat/ChatRuntimeProvider.tsx | 4 +- ...iedChatFacade.tsx => ChatStateAdapter.tsx} | 20 +- .../chat/components/ChatWorkspace.tsx | 8 +- .../chat/messages/ChatMessageList.tsx | 4 +- web/features/chat/model/protocol.ts | 130 +++++++ web/features/chat/trace/TracePresentation.tsx | 2 +- web/features/chat/trace/model.ts | 2 +- web/features/chat/trace/selectors.ts | 2 +- .../chat/transport/UnifiedTurnClient.ts | 93 +++++ web/hooks/useMasteryStudySession.ts | 6 +- web/hooks/useResearchOutlineContinuation.ts | 6 +- web/hooks/useSetupSync.ts | 2 +- web/hooks/useWorkspaceChatActions.ts | 4 +- web/lib/ask-user-state.ts | 2 +- web/lib/book-api.ts | 16 - web/lib/capabilities-api.ts | 9 - web/lib/chat-capabilities.ts | 2 - web/lib/chat-outline.ts | 2 +- web/lib/course-handoff.ts | 2 +- web/lib/deep-research-report.ts | 2 +- web/lib/llm-options-state.ts | 2 +- web/lib/llm-options.ts | 2 +- web/lib/partner-chat-draft.ts | 2 +- web/lib/partner-draft.ts | 2 +- web/lib/partner-groups-api.ts | 2 +- web/lib/partners-api.ts | 2 +- web/lib/session-activity.ts | 4 +- web/lib/session-api.ts | 2 +- web/lib/settings-nav.ts | 2 - web/lib/setup-signals.ts | 2 +- web/lib/stream.ts | 2 +- web/lib/trace-timing.ts | 2 +- web/lib/unified-ws-recovery.ts | 20 - web/lib/unified-ws.ts | 358 ------------------ web/tests/ask-user-segments.test.ts | 2 +- web/tests/ask-user-state.test.ts | 2 +- web/tests/capability-catalog.test.ts | 9 +- web/tests/chat-provider-topology.test.ts | 2 +- web/tests/deep-research-report.test.ts | 2 +- web/tests/integration/chat-messages.spec.tsx | 13 - web/tests/no-v1-chat-surface.test.ts | 61 +++ web/tests/optimistic-id.test.ts | 2 +- web/tests/orphaned-tree.test.ts | 2 +- web/tests/partner-chat-draft.test.ts | 2 +- web/tests/partner-draft.test.ts | 2 +- web/tests/provider-trace-row.test.ts | 4 +- web/tests/session-activity.test.ts | 4 +- .../settings-continuous-navigation.test.ts | 5 +- web/tests/setup-signals.test.ts | 2 +- web/tests/stream.test.ts | 2 +- web/tests/trace-selectors.test.ts | 2 +- .../turn-lifecycle-characterization.test.ts | 2 +- web/tests/unified-ws-recovery.test.ts | 23 -- 85 files changed, 411 insertions(+), 591 deletions(-) delete mode 100644 web/components/chat/home/ChatMessages.tsx delete mode 100644 web/components/chat/home/TracePanels.tsx rename web/features/chat/{compat/UnifiedChatFacade.tsx => ChatStateAdapter.tsx} (99%) create mode 100644 web/features/chat/model/protocol.ts create mode 100644 web/features/chat/transport/UnifiedTurnClient.ts delete mode 100644 web/lib/capabilities-api.ts delete mode 100644 web/lib/chat-capabilities.ts delete mode 100644 web/lib/settings-nav.ts delete mode 100644 web/lib/unified-ws-recovery.ts delete mode 100644 web/lib/unified-ws.ts create mode 100644 web/tests/no-v1-chat-surface.test.ts delete mode 100644 web/tests/unified-ws-recovery.test.ts diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsx index e1893c299..1b7deaa49 100644 --- a/web/app/(workspace)/book/components/BookChatPanel.tsx +++ b/web/app/(workspace)/book/components/BookChatPanel.tsx @@ -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(null); const sessionIdRef = useRef(null); - const clientRef = useRef(null); + const clientRef = useRef(null); const retryTimersRef = useRef>>(new Set()); const scrollerRef = useRef(null); const fileInputRef = useRef(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, ) { diff --git a/web/app/(workspace)/partners/new/page.tsx b/web/app/(workspace)/partners/new/page.tsx index a73af4553..5dadc33a8 100644 --- a/web/app/(workspace)/partners/new/page.tsx +++ b/web/app/(workspace)/partners/new/page.tsx @@ -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, diff --git a/web/app/(workspace)/whisper/page.tsx b/web/app/(workspace)/whisper/page.tsx index 39115cdcc..566709244 100644 --- a/web/app/(workspace)/whisper/page.tsx +++ b/web/app/(workspace)/whisper/page.tsx @@ -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(null); + const clientRef = useRef(null); const seatRef = useRef(seat); const roomIdRef = useRef(roomId); const sessionBySeatRef = useRef>({ @@ -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); diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsx index 89e36cb52..1b048bdbb 100644 --- a/web/components/chat/home/AskUserOptions.tsx +++ b/web/components/chat/home/AskUserOptions.tsx @@ -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``. diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx index ee96329a1..3fa3069b8 100644 --- a/web/components/chat/home/ChatComposer.tsx +++ b/web/components/chat/home/ChatComposer.tsx @@ -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"; diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx deleted file mode 100644 index 15ce12fef..000000000 --- a/web/components/chat/home/ChatMessages.tsx +++ /dev/null @@ -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"; diff --git a/web/components/chat/home/ModelSelector.tsx b/web/components/chat/home/ModelSelector.tsx index 44e651846..c683ece32 100644 --- a/web/components/chat/home/ModelSelector.tsx +++ b/web/components/chat/home/ModelSelector.tsx @@ -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, diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsx index 69934eef1..e9b0cda7d 100644 --- a/web/components/chat/home/SessionActivityPanel.tsx +++ b/web/components/chat/home/SessionActivityPanel.tsx @@ -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"; diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsx index c06218dfa..a9e7e9955 100644 --- a/web/components/chat/home/SessionViewerPanel.tsx +++ b/web/components/chat/home/SessionViewerPanel.tsx @@ -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, diff --git a/web/components/chat/home/StandaloneComposer.tsx b/web/components/chat/home/StandaloneComposer.tsx index 3a8a30d65..8b530c629 100644 --- a/web/components/chat/home/StandaloneComposer.tsx +++ b/web/components/chat/home/StandaloneComposer.tsx @@ -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, diff --git a/web/components/chat/home/SubagentRunTranscript.tsx b/web/components/chat/home/SubagentRunTranscript.tsx index da7ec06d4..0a88f894f 100644 --- a/web/components/chat/home/SubagentRunTranscript.tsx +++ b/web/components/chat/home/SubagentRunTranscript.tsx @@ -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"; /** diff --git a/web/components/chat/home/SubagentTabBody.tsx b/web/components/chat/home/SubagentTabBody.tsx index 34cfa0018..11a77aba0 100644 --- a/web/components/chat/home/SubagentTabBody.tsx +++ b/web/components/chat/home/SubagentTabBody.tsx @@ -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 diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx deleted file mode 100644 index 563679b5d..000000000 --- a/web/components/chat/home/TracePanels.tsx +++ /dev/null @@ -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"; diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsx index 8e2e2e850..2d8b34ed9 100644 --- a/web/components/common/AssistantResponse.tsx +++ b/web/components/common/AssistantResponse.tsx @@ -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, diff --git a/web/components/common/InlineFileCard.tsx b/web/components/common/InlineFileCard.tsx index e4d4c021b4c49b561a86ca956b7339c9ce1de361..6368fa693195354857eb80aaf3bac05558ee561f 100644 GIT binary patch delta 61 zcmbP|IzM&76anXq#FF5W#FA9Ul*EFP)S`)Nq9?ZT@#W^Hq~_=s6y=xXC+FvE7G*ps Q#1>O(00f)w3vZPJ0Q=<^qyPW_ delta 61 zcmbQAIwf_&6p7^g+=9ds{m{J3w9M2L=ZwS>x5VVcl+=k!qWN+%lk`g=61wHZo23~~ N3NbQlekHtB4gmE@7m@$~ diff --git a/web/components/memory/MemoryRunPanel.tsx b/web/components/memory/MemoryRunPanel.tsx index c914bcebb..3ae87da6c 100644 --- a/web/components/memory/MemoryRunPanel.tsx +++ b/web/components/memory/MemoryRunPanel.tsx @@ -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, diff --git a/web/components/memory/useMemoryRun.ts b/web/components/memory/useMemoryRun.ts index 98767d283..9ed040915 100644 --- a/web/components/memory/useMemoryRun.ts +++ b/web/components/memory/useMemoryRun.ts @@ -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"; diff --git a/web/components/partners/PartnerChat.tsx b/web/components/partners/PartnerChat.tsx index 9000ef7f3..a2fc8fd40 100644 --- a/web/components/partners/PartnerChat.tsx +++ b/web/components/partners/PartnerChat.tsx @@ -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, diff --git a/web/components/partners/PartnerConfigure.tsx b/web/components/partners/PartnerConfigure.tsx index 78500d224..94c1663d3 100644 --- a/web/components/partners/PartnerConfigure.tsx +++ b/web/components/partners/PartnerConfigure.tsx @@ -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, diff --git a/web/components/partners/PartnerModelPicker.tsx b/web/components/partners/PartnerModelPicker.tsx index d68fd8254..8be412023 100644 --- a/web/components/partners/PartnerModelPicker.tsx +++ b/web/components/partners/PartnerModelPicker.tsx @@ -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 ""; diff --git a/web/components/partners/PartnerModelSelect.tsx b/web/components/partners/PartnerModelSelect.tsx index e3ec43dfd..f6f8b404b 100644 --- a/web/components/partners/PartnerModelSelect.tsx +++ b/web/components/partners/PartnerModelSelect.tsx @@ -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 ""; diff --git a/web/components/partners/group/useGroupSession.ts b/web/components/partners/group/useGroupSession.ts index 3cafa5196..f04ec298f 100644 --- a/web/components/partners/group/useGroupSession.ts +++ b/web/components/partners/group/useGroupSession.ts @@ -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"; diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsx index d745e40ef..e52c100b3 100644 --- a/web/components/quiz/QuizFollowupTabBody.tsx +++ b/web/components/quiz/QuizFollowupTabBody.tsx @@ -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: { diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsx index 10dbc0437..11044d938 100644 --- a/web/components/reading/workspace/ReadingCompanion.tsx +++ b/web/components/reading/workspace/ReadingCompanion.tsx @@ -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); diff --git a/web/components/reading/workspace/ReadingComposer.tsx b/web/components/reading/workspace/ReadingComposer.tsx index 0852af418..6be4473b3 100644 --- a/web/components/reading/workspace/ReadingComposer.tsx +++ b/web/components/reading/workspace/ReadingComposer.tsx @@ -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(); diff --git a/web/components/reading/workspace/ReadingWorkspace.tsx b/web/components/reading/workspace/ReadingWorkspace.tsx index 7eb5bc1d9..7debbaa94 100644 --- a/web/components/reading/workspace/ReadingWorkspace.tsx +++ b/web/components/reading/workspace/ReadingWorkspace.tsx @@ -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, diff --git a/web/components/reading/workspace/useReadingWorkspace.ts b/web/components/reading/workspace/useReadingWorkspace.ts index ca2559ba6..8d3471716 100644 --- a/web/components/reading/workspace/useReadingWorkspace.ts +++ b/web/components/reading/workspace/useReadingWorkspace.ts @@ -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(null); const [conversations, setConversations] = useState([]); diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx index e97f2e929..d5fc3d4f4 100644 --- a/web/components/sidebar/WorkspaceSidebar.tsx +++ b/web/components/sidebar/WorkspaceSidebar.tsx @@ -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([]); const [courses, setCourses] = useState([]); const [masteryTopics, setMasteryTopics] = useState([]); diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsx index 653220fb3..28cf4ac17 100644 --- a/web/components/space/learning/MasteryComposer.tsx +++ b/web/components/space/learning/MasteryComposer.tsx @@ -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(); diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsx index ed281d28e..e49d6baeb 100644 --- a/web/components/space/learning/MasteryStudy.tsx +++ b/web/components/space/learning/MasteryStudy.tsx @@ -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); diff --git a/web/context/QuizFollowupContext.tsx b/web/context/QuizFollowupContext.tsx index dcf64b741..fccec2dcd 100644 --- a/web/context/QuizFollowupContext.tsx +++ b/web/context/QuizFollowupContext.tsx @@ -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>({}); const runnersRef = useRef< - Map + Map >(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, }; diff --git a/web/context/ReadingContext.tsx b/web/context/ReadingContext.tsx index 91fb6df9b..f5debbe6c 100644 --- a/web/context/ReadingContext.tsx +++ b/web/context/ReadingContext.tsx @@ -33,7 +33,7 @@ import { * changes the URL from `/home` to `/home/`, 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 diff --git a/web/features/chat/ChatRuntimeProvider.tsx b/web/features/chat/ChatRuntimeProvider.tsx index 2d148d49a..b199646be 100644 --- a/web/features/chat/ChatRuntimeProvider.tsx +++ b/web/features/chat/ChatRuntimeProvider.tsx @@ -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 ( - {children} + {children} ); diff --git a/web/features/chat/compat/UnifiedChatFacade.tsx b/web/features/chat/ChatStateAdapter.tsx similarity index 99% rename from web/features/chat/compat/UnifiedChatFacade.tsx rename to web/features/chat/ChatStateAdapter.tsx index dde54ab9a..193430041 100644 --- a/web/features/chat/compat/UnifiedChatFacade.tsx +++ b/web/features/chat/ChatStateAdapter.tsx @@ -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 {children}; } -/** @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; } diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx index ccae58e67..6c95b6ca3 100644 --- a/web/features/chat/components/ChatWorkspace.tsx +++ b/web/features/chat/components/ChatWorkspace.tsx @@ -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([]); const [knowledgeBasesLoaded, setKnowledgeBasesLoaded] = useState(false); diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsx index 6b0fb9ba0..50fefb90e 100644 --- a/web/features/chat/messages/ChatMessageList.tsx +++ b/web/features/chat/messages/ChatMessageList.tsx @@ -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"; diff --git a/web/features/chat/model/protocol.ts b/web/features/chat/model/protocol.ts new file mode 100644 index 000000000..4c495e245 --- /dev/null +++ b/web/features/chat/model/protocol.ts @@ -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; + 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; + 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; +} + +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; diff --git a/web/features/chat/trace/TracePresentation.tsx b/web/features/chat/trace/TracePresentation.tsx index ef38c806b..cce3a06a0 100644 --- a/web/features/chat/trace/TracePresentation.tsx +++ b/web/features/chat/trace/TracePresentation.tsx @@ -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, diff --git a/web/features/chat/trace/model.ts b/web/features/chat/trace/model.ts index 084adcbda..b6869445b 100644 --- a/web/features/chat/trace/model.ts +++ b/web/features/chat/trace/model.ts @@ -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; diff --git a/web/features/chat/trace/selectors.ts b/web/features/chat/trace/selectors.ts index 6a6dc87cc..4eb5af8ea 100644 --- a/web/features/chat/trace/selectors.ts +++ b/web/features/chat/trace/selectors.ts @@ -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, diff --git a/web/features/chat/transport/UnifiedTurnClient.ts b/web/features/chat/transport/UnifiedTurnClient.ts new file mode 100644 index 000000000..039532172 --- /dev/null +++ b/web/features/chat/transport/UnifiedTurnClient.ts @@ -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([ + "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 { + return value && typeof value === "object" ? (value as Record) : {}; +} + +function toStreamEvent(event: ServerEvent): StreamEvent | null { + const raw = event as unknown as Record; + 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"; + } +} diff --git a/web/hooks/useMasteryStudySession.ts b/web/hooks/useMasteryStudySession.ts index 034bcb3a1..458c694d9 100644 --- a/web/hooks/useMasteryStudySession.ts +++ b/web/hooks/useMasteryStudySession.ts @@ -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(null); const [topicError, setTopicError] = useState(null); diff --git a/web/hooks/useResearchOutlineContinuation.ts b/web/hooks/useResearchOutlineContinuation.ts index 6e1c084a7..352bc1778 100644 --- a/web/hooks/useResearchOutlineContinuation.ts +++ b/web/hooks/useResearchOutlineContinuation.ts @@ -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[], diff --git a/web/hooks/useSetupSync.ts b/web/hooks/useSetupSync.ts index 143d5b6f9..4144a13b5 100644 --- a/web/hooks/useSetupSync.ts +++ b/web/hooks/useSetupSync.ts @@ -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"]; diff --git a/web/hooks/useWorkspaceChatActions.ts b/web/hooks/useWorkspaceChatActions.ts index efae2630b..853fb9283 100644 --- a/web/hooks/useWorkspaceChatActions.ts +++ b/web/hooks/useWorkspaceChatActions.ts @@ -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( () => diff --git a/web/lib/ask-user-state.ts b/web/lib/ask-user-state.ts index 178a23686..1d9965578 100644 --- a/web/lib/ask-user-state.ts +++ b/web/lib/ask-user-state.ts @@ -1,4 +1,4 @@ -import type { StreamEvent } from "./unified-ws"; +import type { StreamEvent } from "@/features/chat/model/protocol"; type MessageWithEvents = { events?: StreamEvent[]; diff --git a/web/lib/book-api.ts b/web/lib/book-api.ts index a7fdf0b1c..76c7a1f45 100644 --- a/web/lib/book-api.ts +++ b/web/lib/book-api.ts @@ -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 { - 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"; diff --git a/web/lib/capabilities-api.ts b/web/lib/capabilities-api.ts deleted file mode 100644 index 80f980957..000000000 --- a/web/lib/capabilities-api.ts +++ /dev/null @@ -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 { - return (await fetchCapabilityCatalog()).map((capability) => capability.id); -} diff --git a/web/lib/chat-capabilities.ts b/web/lib/chat-capabilities.ts deleted file mode 100644 index 71816c8b3..000000000 --- a/web/lib/chat-capabilities.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** @deprecated Import capability presentation from `@/features/capabilities/presentation`. */ -export * from "@/features/capabilities/presentation"; diff --git a/web/lib/chat-outline.ts b/web/lib/chat-outline.ts index b75f5e957..26ca433b4 100644 --- a/web/lib/chat-outline.ts +++ b/web/lib/chat-outline.ts @@ -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"; /** diff --git a/web/lib/course-handoff.ts b/web/lib/course-handoff.ts index b7ed05fb2..741381420 100644 --- a/web/lib/course-handoff.ts +++ b/web/lib/course-handoff.ts @@ -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. diff --git a/web/lib/deep-research-report.ts b/web/lib/deep-research-report.ts index 3be9f9d96..f779ccbdf 100644 --- a/web/lib/deep-research-report.ts +++ b/web/lib/deep-research-report.ts @@ -1,4 +1,4 @@ -import type { StreamEvent } from "./unified-ws"; +import type { StreamEvent } from "@/features/chat/model/protocol"; export type DeepResearchFollowupStatus = "researching" | "done" | "failed"; diff --git a/web/lib/llm-options-state.ts b/web/lib/llm-options-state.ts index 6bbcac728..94063ae2e 100644 --- a/web/lib/llm-options-state.ts +++ b/web/lib/llm-options-state.ts @@ -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"; diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.ts index 8f7b38b80..209ff1198 100644 --- a/web/lib/llm-options.ts +++ b/web/lib/llm-options.ts @@ -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; diff --git a/web/lib/partner-chat-draft.ts b/web/lib/partner-chat-draft.ts index a1ad05b42..279cbe3e2 100644 --- a/web/lib/partner-chat-draft.ts +++ b/web/lib/partner-chat-draft.ts @@ -1,4 +1,4 @@ -import type { StreamEvent } from "@/lib/unified-ws"; +import type { StreamEvent } from "@/features/chat/model/protocol"; export interface PartnerDraftSnapshot { events: StreamEvent[]; diff --git a/web/lib/partner-draft.ts b/web/lib/partner-draft.ts index a33ede063..a2a315fd1 100644 --- a/web/lib/partner-draft.ts +++ b/web/lib/partner-draft.ts @@ -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 { diff --git a/web/lib/partner-groups-api.ts b/web/lib/partner-groups-api.ts index 0dedc8697..428bc8d23 100644 --- a/web/lib/partner-groups-api.ts +++ b/web/lib/partner-groups-api.ts @@ -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, diff --git a/web/lib/partners-api.ts b/web/lib/partners-api.ts index edfce321d..77743a9ae 100644 --- a/web/lib/partners-api.ts +++ b/web/lib/partners-api.ts @@ -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; diff --git a/web/lib/session-activity.ts b/web/lib/session-activity.ts index e6a6bcb42..b9c352560 100644 --- a/web/lib/session-activity.ts +++ b/web/lib/session-activity.ts @@ -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/`. */ const OUTPUTS_URL_PREFIX = "/api/outputs/"; diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts index dfb803122..bf8d1b4b2 100644 --- a/web/lib/session-api.ts +++ b/web/lib/session-api.ts @@ -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; diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.ts deleted file mode 100644 index bb931891d..000000000 --- a/web/lib/settings-nav.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** @deprecated Import settings navigation from the settings feature. */ -export * from "@/features/settings/navigation/settings-nav"; diff --git a/web/lib/setup-signals.ts b/web/lib/setup-signals.ts index 12ab9e084..3c6640bfc 100644 --- a/web/lib/setup-signals.ts +++ b/web/lib/setup-signals.ts @@ -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. diff --git a/web/lib/stream.ts b/web/lib/stream.ts index 50545949e..2ee8ffb1a 100644 --- a/web/lib/stream.ts +++ b/web/lib/stream.ts @@ -1,4 +1,4 @@ -import type { StreamEvent } from "@/lib/unified-ws"; +import type { StreamEvent } from "@/features/chat/model/protocol"; type ContentMeta = { call_id?: string; diff --git a/web/lib/trace-timing.ts b/web/lib/trace-timing.ts index c33e14751..2f06fffaa 100644 --- a/web/lib/trace-timing.ts +++ b/web/lib/trace-timing.ts @@ -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. diff --git a/web/lib/unified-ws-recovery.ts b/web/lib/unified-ws-recovery.ts deleted file mode 100644 index 85f9021df..000000000 --- a/web/lib/unified-ws-recovery.ts +++ /dev/null @@ -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); -} diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts deleted file mode 100644 index 13bfb67f7..000000000 --- a/web/lib/unified-ws.ts +++ /dev/null @@ -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; - 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; - 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; -} - -/** - * 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 | null = null; - private lastReceivedAt = 0; - - private reconnectAttempt = 0; - private reconnectTimer: ReturnType | 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; - } -} diff --git a/web/tests/ask-user-segments.test.ts b/web/tests/ask-user-segments.test.ts index 1d608c1e2..28fac09d7 100644 --- a/web/tests/ask-user-segments.test.ts +++ b/web/tests/ask-user-segments.test.ts @@ -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( diff --git a/web/tests/ask-user-state.test.ts b/web/tests/ask-user-state.test.ts index ac33a0052..1710a77b9 100644 --- a/web/tests/ask-user-state.test.ts +++ b/web/tests/ask-user-state.test.ts @@ -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"], diff --git a/web/tests/capability-catalog.test.ts b/web/tests/capability-catalog.test.ts index bfdd64a3c..5bb62d505 100644 --- a/web/tests/capability-catalog.test.ts +++ b/web/tests/capability-catalog.test.ts @@ -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, + ); }); diff --git a/web/tests/chat-provider-topology.test.ts b/web/tests/chat-provider-topology.test.ts index 213999819..83a2a93db 100644 --- a/web/tests/chat-provider-topology.test.ts +++ b/web/tests/chat-provider-topology.test.ts @@ -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/, ); }); diff --git a/web/tests/deep-research-report.test.ts b/web/tests/deep-research-report.test.ts index 27b4d8563..72e329798 100644 --- a/web/tests/deep-research-report.test.ts +++ b/web/tests/deep-research-report.test.ts @@ -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, diff --git a/web/tests/integration/chat-messages.spec.tsx b/web/tests/integration/chat-messages.spec.tsx index 12b1051ab..af751ac6b 100644 --- a/web/tests/integration/chat-messages.spec.tsx +++ b/web/tests/integration/chat-messages.spec.tsx @@ -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| { + 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"/); +}); diff --git a/web/tests/optimistic-id.test.ts b/web/tests/optimistic-id.test.ts index d55aacdd2..60fb25bc9 100644 --- a/web/tests/optimistic-id.test.ts +++ b/web/tests/optimistic-id.test.ts @@ -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()); diff --git a/web/tests/orphaned-tree.test.ts b/web/tests/orphaned-tree.test.ts index 82c9f1a20..a57ad1c0e 100644 --- a/web/tests/orphaned-tree.test.ts +++ b/web/tests/orphaned-tree.test.ts @@ -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 diff --git a/web/tests/partner-chat-draft.test.ts b/web/tests/partner-chat-draft.test.ts index e9422c505..30e82c2f4 100644 --- a/web/tests/partner-chat-draft.test.ts +++ b/web/tests/partner-chat-draft.test.ts @@ -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() { diff --git a/web/tests/partner-draft.test.ts b/web/tests/partner-draft.test.ts index 32cc553f8..8d7afd2d5 100644 --- a/web/tests/partner-draft.test.ts +++ b/web/tests/partner-draft.test.ts @@ -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): StreamEvent { return { diff --git a/web/tests/provider-trace-row.test.ts b/web/tests/provider-trace-row.test.ts index 4e8dc0813..adc0d8e5b 100644 --- a/web/tests/provider-trace-row.test.ts +++ b/web/tests/provider-trace-row.test.ts @@ -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; diff --git a/web/tests/session-activity.test.ts b/web/tests/session-activity.test.ts index f1fca7a59..efab447c2 100644 --- a/web/tests/session-activity.test.ts +++ b/web/tests/session-activity.test.ts @@ -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( diff --git a/web/tests/settings-continuous-navigation.test.ts b/web/tests/settings-continuous-navigation.test.ts index f92c08f93..d34e0f5b0 100644 --- a/web/tests/settings-continuous-navigation.test.ts +++ b/web/tests/settings-continuous-navigation.test.ts @@ -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"); diff --git a/web/tests/setup-signals.test.ts b/web/tests/setup-signals.test.ts index 54414d748..c19b1ef64 100644 --- a/web/tests/setup-signals.test.ts +++ b/web/tests/setup-signals.test.ts @@ -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, diff --git a/web/tests/stream.test.ts b/web/tests/stream.test.ts index 0a65de64a..ed0897db8 100644 --- a/web/tests/stream.test.ts +++ b/web/tests/stream.test.ts @@ -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"], diff --git a/web/tests/trace-selectors.test.ts b/web/tests/trace-selectors.test.ts index 28472df7f..42ca1ff8e 100644 --- a/web/tests/trace-selectors.test.ts +++ b/web/tests/trace-selectors.test.ts @@ -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, diff --git a/web/tests/turn-lifecycle-characterization.test.ts b/web/tests/turn-lifecycle-characterization.test.ts index e5064151f..1ef0f60a1 100644 --- a/web/tests/turn-lifecycle-characterization.test.ts +++ b/web/tests/turn-lifecycle-characterization.test.ts @@ -5,7 +5,7 @@ import type { ChatMessage, StreamEvent, StreamEventType, -} from "../lib/unified-ws"; +} from "../features/chat/model/protocol"; const waitForInputKind: StreamEventType = "wait_for_input"; diff --git a/web/tests/unified-ws-recovery.test.ts b/web/tests/unified-ws-recovery.test.ts deleted file mode 100644 index ebb6809cb..000000000 --- a/web/tests/unified-ws-recovery.test.ts +++ /dev/null @@ -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); -});