From a9de890cd863c83b1ac4f675b3445e0acda356ea Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:04:17 +0200 Subject: [PATCH 01/25] Add chat_session_state table migration --- .../73_add_chat_session_state_table.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 surfsense_backend/alembic/versions/73_add_chat_session_state_table.py diff --git a/surfsense_backend/alembic/versions/73_add_chat_session_state_table.py b/surfsense_backend/alembic/versions/73_add_chat_session_state_table.py new file mode 100644 index 000000000..12e99f306 --- /dev/null +++ b/surfsense_backend/alembic/versions/73_add_chat_session_state_table.py @@ -0,0 +1,75 @@ +"""Add chat_session_state table for live collaboration + +Revision ID: 73 +Revises: 72 + +Creates chat_session_state table to track AI responding state per thread. +Enables real-time sync via Electric SQL for shared chat collaboration. +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "73" +down_revision: str | None = "72" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Create chat_session_state table with Electric SQL replication.""" + op.execute( + """ + CREATE TABLE IF NOT EXISTS chat_session_state ( + id SERIAL PRIMARY KEY, + thread_id INTEGER NOT NULL REFERENCES new_chat_threads(id) ON DELETE CASCADE, + ai_responding_to_user_id UUID REFERENCES "user"(id) ON DELETE SET NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (thread_id) + ) + """ + ) + + op.execute( + "CREATE INDEX IF NOT EXISTS idx_chat_session_state_thread_id ON chat_session_state(thread_id)" + ) + + op.execute("ALTER TABLE chat_session_state REPLICA IDENTITY FULL;") + + op.execute( + """ + DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'chat_session_state' + ) THEN + ALTER PUBLICATION electric_publication_default ADD TABLE chat_session_state; + END IF; + END + $$; + """ + ) + + +def downgrade() -> None: + """Drop chat_session_state table and remove from Electric SQL replication.""" + op.execute( + """ + DO $$ + BEGIN + IF EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'chat_session_state' + ) THEN + ALTER PUBLICATION electric_publication_default DROP TABLE chat_session_state; + END IF; + END + $$; + """ + ) + + op.execute("DROP TABLE IF EXISTS chat_session_state;") From 7d35419b882da4c206af249637029ffea707b031 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:17:54 +0200 Subject: [PATCH 02/25] Add ChatSessionState model --- surfsense_backend/app/db.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/surfsense_backend/app/db.py b/surfsense_backend/app/db.py index 38e27ecf2..35b512c5e 100644 --- a/surfsense_backend/app/db.py +++ b/surfsense_backend/app/db.py @@ -472,6 +472,38 @@ class ChatCommentMention(BaseModel, TimestampMixin): mentioned_user = relationship("User") +class ChatSessionState(BaseModel): + """ + Tracks real-time session state for shared chat collaboration. + One record per thread, synced via Electric SQL. + """ + + __tablename__ = "chat_session_state" + + thread_id = Column( + Integer, + ForeignKey("new_chat_threads.id", ondelete="CASCADE"), + nullable=False, + unique=True, + index=True, + ) + ai_responding_to_user_id = Column( + UUID(as_uuid=True), + ForeignKey("user.id", ondelete="SET NULL"), + nullable=True, + index=True, + ) + updated_at = Column( + TIMESTAMP(timezone=True), + nullable=False, + default=lambda: datetime.now(UTC), + onupdate=lambda: datetime.now(UTC), + ) + + thread = relationship("NewChatThread") + ai_responding_to_user = relationship("User") + + class Document(BaseModel, TimestampMixin): __tablename__ = "documents" From 55a07c064e8e0d56f99cb0d9c2094d591235169f Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:24:37 +0200 Subject: [PATCH 03/25] Add chat session state schemas --- .../app/schemas/chat_session_state.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 surfsense_backend/app/schemas/chat_session_state.py diff --git a/surfsense_backend/app/schemas/chat_session_state.py b/surfsense_backend/app/schemas/chat_session_state.py new file mode 100644 index 000000000..6eca0e26f --- /dev/null +++ b/surfsense_backend/app/schemas/chat_session_state.py @@ -0,0 +1,29 @@ +""" +Pydantic schemas for chat session state (live collaboration). +""" + +from datetime import datetime +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + + +class RespondingUser(BaseModel): + """The user that the AI is currently responding to.""" + + id: UUID + display_name: str | None = None + email: str + + model_config = ConfigDict(from_attributes=True) + + +class ChatSessionStateResponse(BaseModel): + """Current session state for a chat thread.""" + + id: int + thread_id: int + responding_to: RespondingUser | None = None + updated_at: datetime + + model_config = ConfigDict(from_attributes=True) From d7b0b90a01c40d941440e84078c3944d95e61326 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:31:40 +0200 Subject: [PATCH 04/25] Add chat session state service --- .../services/chat_session_state_service.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 surfsense_backend/app/services/chat_session_state_service.py diff --git a/surfsense_backend/app/services/chat_session_state_service.py b/surfsense_backend/app/services/chat_session_state_service.py new file mode 100644 index 000000000..d82fff3a7 --- /dev/null +++ b/surfsense_backend/app/services/chat_session_state_service.py @@ -0,0 +1,65 @@ +""" +Service layer for chat session state (live collaboration). +""" + +from datetime import UTC, datetime +from uuid import UUID + +from sqlalchemy import select +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import selectinload + +from app.db import ChatSessionState + + +async def get_session_state( + session: AsyncSession, + thread_id: int, +) -> ChatSessionState | None: + """Get the current session state for a thread.""" + result = await session.execute( + select(ChatSessionState) + .options(selectinload(ChatSessionState.ai_responding_to_user)) + .filter(ChatSessionState.thread_id == thread_id) + ) + return result.scalar_one_or_none() + + +async def set_ai_responding( + session: AsyncSession, + thread_id: int, + user_id: UUID, +) -> ChatSessionState: + """Mark AI as responding to a specific user. Uses upsert for atomicity.""" + now = datetime.now(UTC) + upsert_query = insert(ChatSessionState).values( + thread_id=thread_id, + ai_responding_to_user_id=user_id, + updated_at=now, + ) + upsert_query = upsert_query.on_conflict_do_update( + index_elements=["thread_id"], + set_={ + "ai_responding_to_user_id": user_id, + "updated_at": now, + }, + ) + await session.execute(upsert_query) + await session.commit() + + return await get_session_state(session, thread_id) + + +async def clear_ai_responding( + session: AsyncSession, + thread_id: int, +) -> ChatSessionState | None: + """Clear AI responding state when response is complete.""" + state = await get_session_state(session, thread_id) + if state: + state.ai_responding_to_user_id = None + state.updated_at = datetime.now(UTC) + await session.commit() + await session.refresh(state) + return state From dc628198cec68f60b9878b5bd0eb26e6699d0848 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:40:38 +0200 Subject: [PATCH 05/25] Integrate session state into chat streaming --- surfsense_backend/app/routes/new_chat_routes.py | 1 + .../app/tasks/chat/stream_new_chat.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/surfsense_backend/app/routes/new_chat_routes.py b/surfsense_backend/app/routes/new_chat_routes.py index 8fddc55c4..1ef3d0822 100644 --- a/surfsense_backend/app/routes/new_chat_routes.py +++ b/surfsense_backend/app/routes/new_chat_routes.py @@ -990,6 +990,7 @@ async def handle_new_chat( search_space_id=request.search_space_id, chat_id=request.chat_id, session=session, + user_id=user.id, llm_config_id=llm_config_id, attachments=request.attachments, mentioned_document_ids=request.mentioned_document_ids, diff --git a/surfsense_backend/app/tasks/chat/stream_new_chat.py b/surfsense_backend/app/tasks/chat/stream_new_chat.py index 85a524108..984cecc6d 100644 --- a/surfsense_backend/app/tasks/chat/stream_new_chat.py +++ b/surfsense_backend/app/tasks/chat/stream_new_chat.py @@ -11,6 +11,7 @@ Supports loading LLM configurations from: import json from collections.abc import AsyncGenerator +from uuid import UUID from langchain_core.messages import HumanMessage from sqlalchemy.ext.asyncio import AsyncSession @@ -27,6 +28,10 @@ from app.agents.new_chat.llm_config import ( ) from app.db import Document, SurfsenseDocsDocument from app.schemas.new_chat import ChatAttachment +from app.services.chat_session_state_service import ( + clear_ai_responding, + set_ai_responding, +) from app.services.connector_service import ConnectorService from app.services.new_streaming_service import VercelStreamingService @@ -149,6 +154,7 @@ async def stream_new_chat( search_space_id: int, chat_id: int, session: AsyncSession, + user_id: UUID, llm_config_id: int = -1, attachments: list[ChatAttachment] | None = None, mentioned_document_ids: list[int] | None = None, @@ -166,8 +172,8 @@ async def stream_new_chat( search_space_id: The search space ID chat_id: The chat ID (used as LangGraph thread_id for memory) session: The database session + user_id: The ID of the user sending the message llm_config_id: The LLM configuration ID (default: -1 for first global config) - messages: Optional chat history from frontend (list of ChatMessage) attachments: Optional attachments with extracted content mentioned_document_ids: Optional list of document IDs mentioned with @ in the chat mentioned_surfsense_doc_ids: Optional list of SurfSense doc IDs mentioned with @ in the chat @@ -181,6 +187,8 @@ async def stream_new_chat( current_text_id: str | None = None try: + # Mark AI as responding to this user for live collaboration + await set_ai_responding(session, chat_id, user_id) # Load LLM config - supports both YAML (negative IDs) and database (positive IDs) agent_config: AgentConfig | None = None @@ -1144,3 +1152,7 @@ async def stream_new_chat( yield streaming_service.format_finish_step() yield streaming_service.format_finish() yield streaming_service.format_done() + + finally: + # Clear AI responding state for live collaboration + await clear_ai_responding(session, chat_id) From 6a31e79edeb2da2fa1770fe666b9c84e379158e1 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 16:52:18 +0200 Subject: [PATCH 06/25] Add chat session state types for live collaboration --- .../types/chat-session-state.types.ts | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 surfsense_web/contracts/types/chat-session-state.types.ts diff --git a/surfsense_web/contracts/types/chat-session-state.types.ts b/surfsense_web/contracts/types/chat-session-state.types.ts new file mode 100644 index 000000000..cf73859e6 --- /dev/null +++ b/surfsense_web/contracts/types/chat-session-state.types.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; + +/** + * Chat session state for live collaboration. + * Tracks which user the AI is currently responding to. + */ +export const chatSessionState = z.object({ + id: z.number(), + thread_id: z.number(), + ai_responding_to_user_id: z.string().uuid().nullable(), + updated_at: z.string(), +}); + +/** + * User currently being responded to by the AI. + */ +export const respondingUser = z.object({ + id: z.string().uuid(), + display_name: z.string().nullable(), + email: z.string(), +}); + +export type ChatSessionState = z.infer; +export type RespondingUser = z.infer; From 69f2460d18a748e569c880df5d1188fbf593a80c Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 18:26:58 +0200 Subject: [PATCH 07/25] Refactor chat session state hook to use useShape --- surfsense_web/hooks/use-chat-session-state.ts | 28 +++++++++++++++++++ surfsense_web/lib/electric/client.ts | 1 - 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 surfsense_web/hooks/use-chat-session-state.ts diff --git a/surfsense_web/hooks/use-chat-session-state.ts b/surfsense_web/hooks/use-chat-session-state.ts new file mode 100644 index 000000000..0272464df --- /dev/null +++ b/surfsense_web/hooks/use-chat-session-state.ts @@ -0,0 +1,28 @@ +"use client"; + +import { useShape } from "@electric-sql/react"; +import type { ChatSessionState } from "@/contracts/types/chat-session-state.types"; + +const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; + +export function useChatSessionState(threadId: number | null) { + const { data, isLoading, isError, error } = useShape({ + url: `${ELECTRIC_URL}/v1/shape`, + params: { + table: "chat_session_state", + where: `thread_id = ${threadId}`, + }, + // Skip fetching if no threadId + ...(threadId ? {} : { url: undefined as unknown as string }), + }); + + const sessionState = data?.[0] ?? null; + + return { + sessionState, + isAiResponding: !!sessionState?.ai_responding_to_user_id, + respondingToUserId: sessionState?.ai_responding_to_user_id ?? null, + loading: isLoading, + error: isError ? error : null, + }; +} diff --git a/surfsense_web/lib/electric/client.ts b/surfsense_web/lib/electric/client.ts index 514185d23..d900ddb0a 100644 --- a/surfsense_web/lib/electric/client.ts +++ b/surfsense_web/lib/electric/client.ts @@ -228,7 +228,6 @@ export async function initElectric(userId: string): Promise { CREATE INDEX IF NOT EXISTS idx_documents_search_space_type ON documents(search_space_id, document_type); `); - // Create the chat_comment_mentions table schema in PGlite await db.exec(` CREATE TABLE IF NOT EXISTS chat_comment_mentions ( id INTEGER PRIMARY KEY, From b56c70c401c4e395617384d2b3b4fc13c91c0cec Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 18:33:29 +0200 Subject: [PATCH 08/25] Add ChatSessionStatus component with animation --- .../assistant-ui/chat-session-status.tsx | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 surfsense_web/components/assistant-ui/chat-session-status.tsx diff --git a/surfsense_web/components/assistant-ui/chat-session-status.tsx b/surfsense_web/components/assistant-ui/chat-session-status.tsx new file mode 100644 index 000000000..aef4aaeb0 --- /dev/null +++ b/surfsense_web/components/assistant-ui/chat-session-status.tsx @@ -0,0 +1,49 @@ +"use client"; + +import type { FC } from "react"; +import { Loader2 } from "lucide-react"; +import { cn } from "@/lib/utils"; + +interface ChatSessionStatusProps { + isAiResponding: boolean; + respondingToUserId: string | null; + currentUserId: string | null; + members: Array<{ + user_id: string; + user_display_name: string | null; + user_email: string; + }>; + className?: string; +} + +export const ChatSessionStatus: FC = ({ + isAiResponding, + respondingToUserId, + currentUserId, + members, + className, +}) => { + if (!isAiResponding || !respondingToUserId) { + return null; + } + + if (respondingToUserId === currentUserId) { + return null; + } + + const respondingUser = members.find((m) => m.user_id === respondingToUserId); + const displayName = respondingUser?.user_display_name || respondingUser?.user_email || "another user"; + + return ( +
+ + Currently responding to {displayName} +
+ ); +}; From 22ead877fa80fbcf13883fa27379eb0e9e17a3f7 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 18:39:50 +0200 Subject: [PATCH 09/25] Integrate ChatSessionStatus and blocking logic into Composer --- .../assistant-ui/chat-session-status.tsx | 4 +-- .../components/assistant-ui/thread.tsx | 30 ++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/surfsense_web/components/assistant-ui/chat-session-status.tsx b/surfsense_web/components/assistant-ui/chat-session-status.tsx index aef4aaeb0..62f7c33ce 100644 --- a/surfsense_web/components/assistant-ui/chat-session-status.tsx +++ b/surfsense_web/components/assistant-ui/chat-session-status.tsx @@ -10,8 +10,8 @@ interface ChatSessionStatusProps { currentUserId: string | null; members: Array<{ user_id: string; - user_display_name: string | null; - user_email: string; + user_display_name?: string | null; + user_email?: string | null; }>; className?: string; } diff --git a/surfsense_web/components/assistant-ui/thread.tsx b/surfsense_web/components/assistant-ui/thread.tsx index eaf30fc96..1d83b5a60 100644 --- a/surfsense_web/components/assistant-ui/thread.tsx +++ b/surfsense_web/components/assistant-ui/thread.tsx @@ -31,6 +31,7 @@ import { mentionedDocumentIdsAtom, mentionedDocumentsAtom, } from "@/atoms/chat/mentioned-documents.atom"; +import { membersAtom } from "@/atoms/members/members-query.atoms"; import { globalNewLLMConfigsAtom, llmPreferencesAtom, @@ -39,6 +40,7 @@ import { import { currentUserAtom } from "@/atoms/user/user-query.atoms"; import { AssistantMessage } from "@/components/assistant-ui/assistant-message"; import { ComposerAddAttachment, ComposerAttachments } from "@/components/assistant-ui/attachment"; +import { ChatSessionStatus } from "@/components/assistant-ui/chat-session-status"; import { ConnectorIndicator } from "@/components/assistant-ui/connector-popup"; import { InlineMentionEditor, @@ -59,6 +61,7 @@ import { import type { ThinkingStep } from "@/components/tool-ui/deepagent-thinking"; import { Button } from "@/components/ui/button"; import type { Document } from "@/contracts/types/document.types"; +import { useChatSessionState } from "@/hooks/use-chat-session-state"; import { cn } from "@/lib/utils"; interface ThreadProps { @@ -215,7 +218,7 @@ const Composer: FC = () => { const editorRef = useRef(null); const editorContainerRef = useRef(null); const documentPickerRef = useRef(null); - const { search_space_id } = useParams(); + const { search_space_id, chat_id } = useParams(); const setMentionedDocumentIds = useSetAtom(mentionedDocumentIdsAtom); const composerRuntime = useComposerRuntime(); const hasAutoFocusedRef = useRef(false); @@ -223,6 +226,18 @@ const Composer: FC = () => { const isThreadEmpty = useAssistantState(({ thread }) => thread.isEmpty); const isThreadRunning = useAssistantState(({ thread }) => thread.isRunning); + // Live collaboration: track AI responding state + const { data: currentUser } = useAtomValue(currentUserAtom); + const { data: members } = useAtomValue(membersAtom); + const threadId = useMemo(() => { + if (Array.isArray(chat_id) && chat_id.length > 0) { + return Number.parseInt(chat_id[0], 10) || null; + } + return typeof chat_id === "string" ? Number.parseInt(chat_id, 10) || null : null; + }, [chat_id]); + const { isAiResponding, respondingToUserId } = useChatSessionState(threadId); + const isBlockedByOtherUser = isAiResponding && respondingToUserId !== currentUser?.id; + // Auto-focus editor on new chat page after mount useEffect(() => { if (isThreadEmpty && !hasAutoFocusedRef.current && editorRef.current) { @@ -298,9 +313,9 @@ const Composer: FC = () => { [showDocumentPopover] ); - // Submit message (blocked during streaming or when document picker is open) + // Submit message (blocked during streaming, document picker open, or AI responding to another user) const handleSubmit = useCallback(() => { - if (isThreadRunning) { + if (isThreadRunning || isBlockedByOtherUser) { return; } if (!showDocumentPopover) { @@ -315,6 +330,7 @@ const Composer: FC = () => { }, [ showDocumentPopover, isThreadRunning, + isBlockedByOtherUser, composerRuntime, setMentionedDocuments, setMentionedDocumentIds, @@ -374,7 +390,13 @@ const Composer: FC = () => { ); return ( - + + {/* Inline editor with @mention support */} From 17f8c993df801043f96c8d2116b559a7d9249dcc Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Tue, 20 Jan 2026 19:48:28 +0200 Subject: [PATCH 10/25] Simplify chat session state hook and disable send button when blocked --- .../components/assistant-ui/thread.tsx | 29 ++++++++++++------- surfsense_web/hooks/use-chat-session-state.ts | 6 ++-- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/surfsense_web/components/assistant-ui/thread.tsx b/surfsense_web/components/assistant-ui/thread.tsx index 1d83b5a60..d65372c24 100644 --- a/surfsense_web/components/assistant-ui/thread.tsx +++ b/surfsense_web/components/assistant-ui/thread.tsx @@ -226,7 +226,7 @@ const Composer: FC = () => { const isThreadEmpty = useAssistantState(({ thread }) => thread.isEmpty); const isThreadRunning = useAssistantState(({ thread }) => thread.isRunning); - // Live collaboration: track AI responding state + // Live collaboration state const { data: currentUser } = useAtomValue(currentUserAtom); const { data: members } = useAtomValue(membersAtom); const threadId = useMemo(() => { @@ -439,13 +439,17 @@ const Composer: FC = () => { />, document.body )} - + ); }; -const ComposerAction: FC = () => { +interface ComposerActionProps { + isBlockedByOtherUser?: boolean; +} + +const ComposerAction: FC = ({ isBlockedByOtherUser = false }) => { // Check if any attachments are still being processed (running AND progress < 100) // When progress is 100, processing is done but waiting for send() const hasProcessingAttachments = useAssistantState(({ composer }) => @@ -480,7 +484,8 @@ const ComposerAction: FC = () => { return userConfigs?.some((c) => c.id === agentLlmId) ?? false; }, [preferences, globalConfigs, userConfigs]); - const isSendDisabled = hasProcessingAttachments || isComposerEmpty || !hasModelConfigured; + const isSendDisabled = + hasProcessingAttachments || isComposerEmpty || !hasModelConfigured || isBlockedByOtherUser; return (
@@ -509,13 +514,15 @@ const ComposerAction: FC = () => { ({ url: `${ELECTRIC_URL}/v1/shape`, @@ -12,8 +16,6 @@ export function useChatSessionState(threadId: number | null) { table: "chat_session_state", where: `thread_id = ${threadId}`, }, - // Skip fetching if no threadId - ...(threadId ? {} : { url: undefined as unknown as string }), }); const sessionState = data?.[0] ?? null; From 0245e4bea96074501815f262d167f9ed0d66dbc1 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 15:17:23 +0200 Subject: [PATCH 11/25] Add Electric SQL replication for messages and comments --- ..._messages_comments_electric_replication.py | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py diff --git a/surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py b/surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py new file mode 100644 index 000000000..c06b4ed3d --- /dev/null +++ b/surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py @@ -0,0 +1,94 @@ +"""Add new_chat_messages and chat_comments to Electric SQL publication + +Revision ID: 74 +Revises: 73 + +Enables real-time sync for chat messages and comments via Electric SQL. +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "74" +down_revision: str | None = "73" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Add new_chat_messages and chat_comments to Electric SQL replication.""" + # Set REPLICA IDENTITY FULL for Electric SQL sync + op.execute("ALTER TABLE new_chat_messages REPLICA IDENTITY FULL;") + op.execute("ALTER TABLE chat_comments REPLICA IDENTITY FULL;") + + # Add new_chat_messages to Electric publication + op.execute( + """ + DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'new_chat_messages' + ) THEN + ALTER PUBLICATION electric_publication_default ADD TABLE new_chat_messages; + END IF; + END + $$; + """ + ) + + # Add chat_comments to Electric publication + op.execute( + """ + DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'chat_comments' + ) THEN + ALTER PUBLICATION electric_publication_default ADD TABLE chat_comments; + END IF; + END + $$; + """ + ) + + +def downgrade() -> None: + """Remove new_chat_messages and chat_comments from Electric SQL replication.""" + op.execute( + """ + DO $$ + BEGIN + IF EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'new_chat_messages' + ) THEN + ALTER PUBLICATION electric_publication_default DROP TABLE new_chat_messages; + END IF; + END + $$; + """ + ) + + op.execute( + """ + DO $$ + BEGIN + IF EXISTS ( + SELECT 1 FROM pg_publication_tables + WHERE pubname = 'electric_publication_default' + AND tablename = 'chat_comments' + ) THEN + ALTER PUBLICATION electric_publication_default DROP TABLE chat_comments; + END IF; + END + $$; + """ + ) + + # Note: Not reverting REPLICA IDENTITY as it doesn't harm normal operations From 3765d0a868cecd832a060ebe5c57ee1ca1da7666 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 17:57:11 +0200 Subject: [PATCH 12/25] Update migration 74 for live collaboration tables --- ...ve_collaboration_tables_electric_replication.py} | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) rename surfsense_backend/alembic/versions/{74_add_messages_comments_electric_replication.py => 74_add_live_collaboration_tables_electric_replication.py} (82%) diff --git a/surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py b/surfsense_backend/alembic/versions/74_add_live_collaboration_tables_electric_replication.py similarity index 82% rename from surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py rename to surfsense_backend/alembic/versions/74_add_live_collaboration_tables_electric_replication.py index c06b4ed3d..c98ddd332 100644 --- a/surfsense_backend/alembic/versions/74_add_messages_comments_electric_replication.py +++ b/surfsense_backend/alembic/versions/74_add_live_collaboration_tables_electric_replication.py @@ -1,9 +1,14 @@ -"""Add new_chat_messages and chat_comments to Electric SQL publication +"""Add live collaboration tables to Electric SQL publication Revision ID: 74 Revises: 73 -Enables real-time sync for chat messages and comments via Electric SQL. +Enables real-time sync for live collaboration features: +- new_chat_messages: Live message sync between users +- chat_comments: Live comment updates + +Note: User/member info is fetched via API (membersAtom) for client-side joins, +not via Electric SQL, to keep where clauses optimized and reduce complexity. """ from collections.abc import Sequence @@ -17,7 +22,7 @@ depends_on: str | Sequence[str] | None = None def upgrade() -> None: - """Add new_chat_messages and chat_comments to Electric SQL replication.""" + """Add live collaboration tables to Electric SQL replication.""" # Set REPLICA IDENTITY FULL for Electric SQL sync op.execute("ALTER TABLE new_chat_messages REPLICA IDENTITY FULL;") op.execute("ALTER TABLE chat_comments REPLICA IDENTITY FULL;") @@ -58,7 +63,7 @@ def upgrade() -> None: def downgrade() -> None: - """Remove new_chat_messages and chat_comments from Electric SQL replication.""" + """Remove live collaboration tables from Electric SQL replication.""" op.execute( """ DO $$ From 73ff26119434f045da174b9645a53ce1aa02ba2c Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 17:58:17 +0200 Subject: [PATCH 13/25] Add raw message/comment types and reduce members stale time --- .../atoms/members/members-query.atoms.ts | 2 +- .../contracts/types/chat-comments.types.ts | 14 ++++++++++++++ .../contracts/types/chat-messages.types.ts | 16 ++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 surfsense_web/contracts/types/chat-messages.types.ts diff --git a/surfsense_web/atoms/members/members-query.atoms.ts b/surfsense_web/atoms/members/members-query.atoms.ts index 8ed56ef0c..f486dc02b 100644 --- a/surfsense_web/atoms/members/members-query.atoms.ts +++ b/surfsense_web/atoms/members/members-query.atoms.ts @@ -9,7 +9,7 @@ export const membersAtom = atomWithQuery((get) => { return { queryKey: cacheKeys.members.all(searchSpaceId?.toString() ?? ""), enabled: !!searchSpaceId, - staleTime: 5 * 60 * 1000, // 5 minutes + staleTime: 3 * 1000, // 3 seconds - short staleness for live collaboration queryFn: async () => { if (!searchSpaceId) { return []; diff --git a/surfsense_web/contracts/types/chat-comments.types.ts b/surfsense_web/contracts/types/chat-comments.types.ts index 92b3ff060..c3b32be9d 100644 --- a/surfsense_web/contracts/types/chat-comments.types.ts +++ b/surfsense_web/contracts/types/chat-comments.types.ts @@ -1,5 +1,18 @@ import { z } from "zod"; +/** + * Raw comment + */ +export const rawComment = z.object({ + id: z.number(), + message_id: z.number(), + parent_id: z.number().nullable(), + author_id: z.string().nullable(), + content: z.string(), + created_at: z.string(), + updated_at: z.string(), +}); + export const author = z.object({ id: z.string().uuid(), display_name: z.string().nullable(), @@ -122,6 +135,7 @@ export const getMentionsResponse = z.object({ total_count: z.number(), }); +export type RawComment = z.infer; export type Author = z.infer; export type CommentReply = z.infer; export type Comment = z.infer; diff --git a/surfsense_web/contracts/types/chat-messages.types.ts b/surfsense_web/contracts/types/chat-messages.types.ts new file mode 100644 index 000000000..01edef3f2 --- /dev/null +++ b/surfsense_web/contracts/types/chat-messages.types.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +/** + * Raw message from database (Electric SQL sync) + */ +export const rawMessage = z.object({ + id: z.number(), + thread_id: z.number(), + role: z.enum(["user", "assistant", "system"]), + content: z.unknown(), + author_id: z.string().nullable(), + created_at: z.string(), + updated_at: z.string(), +}); + +export type RawMessage = z.infer; From dd781fa3d531a7cb19b2f63b4980a0ecc418ea11 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 17:58:35 +0200 Subject: [PATCH 14/25] Add live sync hooks for messages and comments --- surfsense_web/hooks/use-chat-messages-live.ts | 77 +++++++++ surfsense_web/hooks/use-comments-live.ts | 154 ++++++++++++++++++ 2 files changed, 231 insertions(+) create mode 100644 surfsense_web/hooks/use-chat-messages-live.ts create mode 100644 surfsense_web/hooks/use-comments-live.ts diff --git a/surfsense_web/hooks/use-chat-messages-live.ts b/surfsense_web/hooks/use-chat-messages-live.ts new file mode 100644 index 000000000..39341d479 --- /dev/null +++ b/surfsense_web/hooks/use-chat-messages-live.ts @@ -0,0 +1,77 @@ +"use client"; + +import { useShape } from "@electric-sql/react"; +import { useAtomValue } from "jotai"; +import { useMemo } from "react"; +import { membersAtom } from "@/atoms/members/members-query.atoms"; +import type { RawMessage } from "@/contracts/types/chat-messages.types"; +import type { Membership } from "@/contracts/types/members.types"; +import type { MessageRecord } from "@/lib/chat/thread-persistence"; + +const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; + +/** + * Member info for building author data - derived from Membership + */ +type MemberInfo = Pick; + +/** + * Hook to get live chat messages for real-time sync. + * Uses Electric SQL for messages + membersAtom (API) for author info. + */ +export function useChatMessagesLive(threadId: number | null) { + + const { + data: messagesData, + isLoading: messagesLoading, + isError: messagesError, + error: messagesErrorDetails, + } = useShape({ + url: `${ELECTRIC_URL}/v1/shape`, + params: { + table: "new_chat_messages", + where: `thread_id = ${threadId}`, + }, + }); + + + const { data: membersData, isLoading: membersLoading } = useAtomValue(membersAtom); + + + const messages = useMemo(() => { + if (!messagesData) return []; + + // Build member lookup map + const memberMap = new Map(); + if (membersData) { + for (const member of membersData) { + memberMap.set(member.user_id, { + user_display_name: member.user_display_name, + user_avatar_url: member.user_avatar_url, + }); + } + } + + // Transform raw messages to MessageRecord with author info + return [...messagesData].map((msg): MessageRecord => { + const author = msg.author_id ? memberMap.get(msg.author_id) : null; + return { + id: msg.id, + thread_id: msg.thread_id, + role: msg.role, + content: msg.content, + created_at: msg.created_at, + author_id: msg.author_id, + author_display_name: author?.user_display_name ?? null, + author_avatar_url: author?.user_avatar_url ?? null, + }; + }); + }, [messagesData, membersData]); + + return { + messages, + isLoading: messagesLoading || membersLoading, + isError: messagesError, + error: messagesError ? messagesErrorDetails : null, + }; +} diff --git a/surfsense_web/hooks/use-comments-live.ts b/surfsense_web/hooks/use-comments-live.ts new file mode 100644 index 000000000..f4d922888 --- /dev/null +++ b/surfsense_web/hooks/use-comments-live.ts @@ -0,0 +1,154 @@ +"use client"; + +import { useShape } from "@electric-sql/react"; +import { useAtomValue } from "jotai"; +import { useMemo } from "react"; +import { membersAtom, myAccessAtom } from "@/atoms/members/members-query.atoms"; +import { currentUserAtom } from "@/atoms/user/user-query.atoms"; +import type { Comment, CommentReply, Author } from "@/contracts/types/chat-comments.types"; +import type { Membership } from "@/contracts/types/members.types"; +import type { RawComment } from "@/contracts/types/chat-comments.types"; + +const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; + +// Regex pattern to match @[uuid] mentions (matches backend MENTION_PATTERN) +const MENTION_PATTERN = /@\[([0-9a-fA-F-]{36})\]/g; + +/** + * Member info for building author objects - derived from Membership + */ +type MemberInfo = Pick; + +/** + * Render mentions in content by replacing @[uuid] with @{DisplayName} + */ +function renderMentions(content: string, memberMap: Map): string { + return content.replace(MENTION_PATTERN, (match, uuid) => { + const member = memberMap.get(uuid); + if (member?.user_display_name) { + return `@{${member.user_display_name}}`; + } + return match; + }); +} + +/** + * Hook to get live comments for a specific message. + * Uses Electric SQL for comments + membersAtom (API) for author info. + * Returns data matching the existing Comment type. + */ +export function useCommentsLive(messageId: number | null) { + const { + data: commentsData, + isLoading: commentsLoading, + isError: commentsError, + error: commentsErrorDetails, + } = useShape({ + url: `${ELECTRIC_URL}/v1/shape`, + params: { + table: "chat_comments", + where: `message_id = ${messageId}`, + }, + }); + + const { data: membersData, isLoading: membersLoading } = useAtomValue(membersAtom); + const { data: currentUser } = useAtomValue(currentUserAtom); + const { data: myAccess } = useAtomValue(myAccessAtom); + + const comments = useMemo(() => { + if (!commentsData) return []; + + // Build member lookup map + const memberMap = new Map(); + if (membersData) { + for (const member of membersData) { + memberMap.set(member.user_id, { + user_display_name: member.user_display_name, + user_avatar_url: member.user_avatar_url, + user_email: member.user_email, + }); + } + } + + const currentUserId = currentUser?.id; + const isOwnerOrAdmin = myAccess?.is_owner ?? false; + + // Build author object from member data + const buildAuthor = (authorId: string | null): Author | null => { + if (!authorId) return null; + const member = memberMap.get(authorId); + if (!member) return null; + return { + id: authorId, + display_name: member.user_display_name ?? null, + avatar_url: member.user_avatar_url ?? null, + email: member.user_email ?? "", + }; + }; + + // Transform raw comment to CommentReply + const transformToReply = (raw: RawComment): CommentReply => { + const isEdited = raw.created_at !== raw.updated_at; + const isAuthor = currentUserId === raw.author_id; + + return { + id: raw.id, + content: raw.content, + content_rendered: renderMentions(raw.content, memberMap), + author: buildAuthor(raw.author_id), + created_at: raw.created_at, + updated_at: raw.updated_at, + is_edited: isEdited, + can_edit: isAuthor, + can_delete: isAuthor || isOwnerOrAdmin, + }; + }; + + // Separate top-level comments and replies + const topLevelRaw: RawComment[] = []; + const repliesMap = new Map(); + + for (const raw of commentsData) { + if (raw.parent_id === null) { + topLevelRaw.push(raw); + } else { + const replies = repliesMap.get(raw.parent_id) || []; + replies.push(raw); + repliesMap.set(raw.parent_id, replies); + } + } + + // Transform top-level comments to Comment type + const transformToComment = (raw: RawComment): Comment => { + const isEdited = raw.created_at !== raw.updated_at; + const isAuthor = currentUserId === raw.author_id; + const rawReplies = repliesMap.get(raw.id) || []; + const replies = rawReplies.map(transformToReply); + + return { + id: raw.id, + message_id: raw.message_id, + content: raw.content, + content_rendered: renderMentions(raw.content, memberMap), + author: buildAuthor(raw.author_id), + created_at: raw.created_at, + updated_at: raw.updated_at, + is_edited: isEdited, + can_edit: isAuthor, + can_delete: isAuthor || isOwnerOrAdmin, + reply_count: replies.length, + replies, + }; + }; + + return topLevelRaw.map(transformToComment); + }, [commentsData, membersData, currentUser?.id, myAccess?.is_owner]); + + return { + comments, + commentCount: commentsData?.length ?? 0, + isLoading: commentsLoading || membersLoading, + isError: commentsError, + error: commentsError ? commentsErrorDetails : null, + }; +} From f7ee03ddf370110dd42614d545d3b3cf05b797cb Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 18:10:03 +0200 Subject: [PATCH 15/25] Integrate live message sync on chat page --- .../new-chat/[[...chat_id]]/page.tsx | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx index 43c33ba5a..865dd6e68 100644 --- a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx +++ b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx @@ -33,6 +33,7 @@ import { GeneratePodcastToolUI } from "@/components/tool-ui/generate-podcast"; import { LinkPreviewToolUI } from "@/components/tool-ui/link-preview"; import { ScrapeWebpageToolUI } from "@/components/tool-ui/scrape-webpage"; // import { WriteTodosToolUI } from "@/components/tool-ui/write-todos"; +import { useChatMessagesLive } from "@/hooks/use-chat-messages-live"; import { getBearerToken } from "@/lib/auth-utils"; import { createAttachmentAdapter, extractAttachmentContent } from "@/lib/chat/attachment-adapter"; import { @@ -257,6 +258,9 @@ export default function NewChatPage() { // Get current user for author info in shared chats const { data: currentUser } = useAtomValue(currentUserAtom); + // Live sync for other users' messages (shared chats) + const { messages: liveMessages } = useChatMessagesLive(threadId); + // Create the attachment adapter for file processing const attachmentAdapter = useMemo(() => createAttachmentAdapter(), []); @@ -409,6 +413,45 @@ export default function NewChatPage() { }); }, [currentThread, setCurrentThreadState]); + // Live sync: Merge messages from other users (shared chats) + useEffect(() => { + if (!liveMessages.length || !currentUser?.id || isRunning) return; + + // Get IDs of messages we already have locally + const localMessageIds = new Set( + messages + .map((m) => { + // Extract numeric ID from "msg-{id}" format + const match = m.id?.match(/^msg-(\d+)$/); + return match ? Number.parseInt(match[1], 10) : null; + }) + .filter((id): id is number => id !== null) + ); + + // Find live messages from OTHER users that we don't have locally + const newOtherUserMessages = liveMessages.filter((liveMsg) => { + // Skip if we already have this message + if (localMessageIds.has(liveMsg.id)) return false; + // Skip if this is our own message (we added it optimistically) + if (liveMsg.author_id === currentUser.id) return false; + return true; + }); + + if (newOtherUserMessages.length > 0) { + // Convert and add new messages from other users + const converted = newOtherUserMessages.map(convertToThreadMessage); + setMessages((prev) => { + // Merge and sort by ID to maintain order + const merged = [...prev, ...converted]; + return merged.sort((a, b) => { + const aId = Number.parseInt((a.id ?? "").replace(/^msg-/, ""), 10) || 0; + const bId = Number.parseInt((b.id ?? "").replace(/^msg-/, ""), 10) || 0; + return aId - bId; + }); + }); + } + }, [liveMessages, currentUser?.id, messages, isRunning]); + // Cancel ongoing request const cancelRun = useCallback(async () => { if (abortControllerRef.current) { From f3467262940e956e9e443dc944901e763ff77a26 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Wed, 21 Jan 2026 18:13:02 +0200 Subject: [PATCH 16/25] Integrate live comment sync in comment components --- .../components/assistant-ui/assistant-message.tsx | 10 +++------- .../comment-panel-container.tsx | 15 +++++++-------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/surfsense_web/components/assistant-ui/assistant-message.tsx b/surfsense_web/components/assistant-ui/assistant-message.tsx index 681dc315a..513242d1b 100644 --- a/surfsense_web/components/assistant-ui/assistant-message.tsx +++ b/surfsense_web/components/assistant-ui/assistant-message.tsx @@ -25,7 +25,7 @@ import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button import { CommentPanelContainer } from "@/components/chat-comments/comment-panel-container/comment-panel-container"; import { CommentSheet } from "@/components/chat-comments/comment-sheet/comment-sheet"; import { CommentTrigger } from "@/components/chat-comments/comment-trigger/comment-trigger"; -import { useComments } from "@/hooks/use-comments"; +import { useCommentsLive } from "@/hooks/use-comments-live"; import { useMediaQuery } from "@/hooks/use-media-query"; import { cn } from "@/lib/utils"; @@ -115,12 +115,8 @@ export const AssistantMessage: FC = () => { const isLastMessage = useAssistantState(({ message }) => message?.isLast ?? false); const isMessageStreaming = isThreadRunning && isLastMessage; - const { data: commentsData } = useComments({ - messageId: dbMessageId ?? 0, - enabled: !!dbMessageId, - }); - - const commentCount = commentsData?.total_count ?? 0; + // Live sync for real-time comment count + const { commentCount } = useCommentsLive(dbMessageId); const hasComments = commentCount > 0; const isAddingComment = dbMessageId !== null && addingCommentToMessageId === dbMessageId; const showCommentPanel = hasComments || isAddingComment; diff --git a/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx b/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx index 197ac0798..8281ca8fd 100644 --- a/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx +++ b/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx @@ -10,7 +10,7 @@ import { } from "@/atoms/chat-comments/comments-mutation.atoms"; import { membersAtom } from "@/atoms/members/members-query.atoms"; import { currentUserAtom } from "@/atoms/user/user-query.atoms"; -import { useComments } from "@/hooks/use-comments"; +import { useCommentsLive } from "@/hooks/use-comments-live"; import { CommentPanel } from "../comment-panel/comment-panel"; import type { CommentPanelContainerProps } from "./types"; import { transformComment, transformMember } from "./utils"; @@ -21,10 +21,10 @@ export function CommentPanelContainer({ maxHeight, variant = "desktop", }: CommentPanelContainerProps) { - const { data: commentsData, isLoading: isCommentsLoading } = useComments({ - messageId, - enabled: isOpen, - }); + // Live sync for real-time comment updates + const { comments: liveComments, isLoading: isCommentsLoading } = useCommentsLive( + isOpen ? messageId : null + ); const [{ data: membersData, isLoading: isMembersLoading }] = useAtom(membersAtom); const [{ data: currentUser }] = useAtom(currentUserAtom); @@ -35,9 +35,8 @@ export function CommentPanelContainer({ const [{ mutate: deleteComment, isPending: isDeleting }] = useAtom(deleteCommentMutationAtom); const commentThreads = useMemo(() => { - if (!commentsData?.comments) return []; - return commentsData.comments.map(transformComment); - }, [commentsData]); + return liveComments.map(transformComment); + }, [liveComments]); const members = useMemo(() => { if (!membersData) return []; From 3ab9cc84854c8e050ad76b7c45228154777b6a74 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 15:05:00 +0200 Subject: [PATCH 17/25] Restore API-based comments and remove unstable live sync integration --- .../new-chat/[[...chat_id]]/page.tsx | 43 ------------------- .../assistant-ui/assistant-message.tsx | 10 +++-- .../comment-panel-container.tsx | 15 ++++--- .../contracts/types/chat-messages.types.ts | 2 +- surfsense_web/hooks/use-chat-messages-live.ts | 7 ++- 5 files changed, 22 insertions(+), 55 deletions(-) diff --git a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx index 865dd6e68..43c33ba5a 100644 --- a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx +++ b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx @@ -33,7 +33,6 @@ import { GeneratePodcastToolUI } from "@/components/tool-ui/generate-podcast"; import { LinkPreviewToolUI } from "@/components/tool-ui/link-preview"; import { ScrapeWebpageToolUI } from "@/components/tool-ui/scrape-webpage"; // import { WriteTodosToolUI } from "@/components/tool-ui/write-todos"; -import { useChatMessagesLive } from "@/hooks/use-chat-messages-live"; import { getBearerToken } from "@/lib/auth-utils"; import { createAttachmentAdapter, extractAttachmentContent } from "@/lib/chat/attachment-adapter"; import { @@ -258,9 +257,6 @@ export default function NewChatPage() { // Get current user for author info in shared chats const { data: currentUser } = useAtomValue(currentUserAtom); - // Live sync for other users' messages (shared chats) - const { messages: liveMessages } = useChatMessagesLive(threadId); - // Create the attachment adapter for file processing const attachmentAdapter = useMemo(() => createAttachmentAdapter(), []); @@ -413,45 +409,6 @@ export default function NewChatPage() { }); }, [currentThread, setCurrentThreadState]); - // Live sync: Merge messages from other users (shared chats) - useEffect(() => { - if (!liveMessages.length || !currentUser?.id || isRunning) return; - - // Get IDs of messages we already have locally - const localMessageIds = new Set( - messages - .map((m) => { - // Extract numeric ID from "msg-{id}" format - const match = m.id?.match(/^msg-(\d+)$/); - return match ? Number.parseInt(match[1], 10) : null; - }) - .filter((id): id is number => id !== null) - ); - - // Find live messages from OTHER users that we don't have locally - const newOtherUserMessages = liveMessages.filter((liveMsg) => { - // Skip if we already have this message - if (localMessageIds.has(liveMsg.id)) return false; - // Skip if this is our own message (we added it optimistically) - if (liveMsg.author_id === currentUser.id) return false; - return true; - }); - - if (newOtherUserMessages.length > 0) { - // Convert and add new messages from other users - const converted = newOtherUserMessages.map(convertToThreadMessage); - setMessages((prev) => { - // Merge and sort by ID to maintain order - const merged = [...prev, ...converted]; - return merged.sort((a, b) => { - const aId = Number.parseInt((a.id ?? "").replace(/^msg-/, ""), 10) || 0; - const bId = Number.parseInt((b.id ?? "").replace(/^msg-/, ""), 10) || 0; - return aId - bId; - }); - }); - } - }, [liveMessages, currentUser?.id, messages, isRunning]); - // Cancel ongoing request const cancelRun = useCallback(async () => { if (abortControllerRef.current) { diff --git a/surfsense_web/components/assistant-ui/assistant-message.tsx b/surfsense_web/components/assistant-ui/assistant-message.tsx index 513242d1b..681dc315a 100644 --- a/surfsense_web/components/assistant-ui/assistant-message.tsx +++ b/surfsense_web/components/assistant-ui/assistant-message.tsx @@ -25,7 +25,7 @@ import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button import { CommentPanelContainer } from "@/components/chat-comments/comment-panel-container/comment-panel-container"; import { CommentSheet } from "@/components/chat-comments/comment-sheet/comment-sheet"; import { CommentTrigger } from "@/components/chat-comments/comment-trigger/comment-trigger"; -import { useCommentsLive } from "@/hooks/use-comments-live"; +import { useComments } from "@/hooks/use-comments"; import { useMediaQuery } from "@/hooks/use-media-query"; import { cn } from "@/lib/utils"; @@ -115,8 +115,12 @@ export const AssistantMessage: FC = () => { const isLastMessage = useAssistantState(({ message }) => message?.isLast ?? false); const isMessageStreaming = isThreadRunning && isLastMessage; - // Live sync for real-time comment count - const { commentCount } = useCommentsLive(dbMessageId); + const { data: commentsData } = useComments({ + messageId: dbMessageId ?? 0, + enabled: !!dbMessageId, + }); + + const commentCount = commentsData?.total_count ?? 0; const hasComments = commentCount > 0; const isAddingComment = dbMessageId !== null && addingCommentToMessageId === dbMessageId; const showCommentPanel = hasComments || isAddingComment; diff --git a/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx b/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx index 8281ca8fd..197ac0798 100644 --- a/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx +++ b/surfsense_web/components/chat-comments/comment-panel-container/comment-panel-container.tsx @@ -10,7 +10,7 @@ import { } from "@/atoms/chat-comments/comments-mutation.atoms"; import { membersAtom } from "@/atoms/members/members-query.atoms"; import { currentUserAtom } from "@/atoms/user/user-query.atoms"; -import { useCommentsLive } from "@/hooks/use-comments-live"; +import { useComments } from "@/hooks/use-comments"; import { CommentPanel } from "../comment-panel/comment-panel"; import type { CommentPanelContainerProps } from "./types"; import { transformComment, transformMember } from "./utils"; @@ -21,10 +21,10 @@ export function CommentPanelContainer({ maxHeight, variant = "desktop", }: CommentPanelContainerProps) { - // Live sync for real-time comment updates - const { comments: liveComments, isLoading: isCommentsLoading } = useCommentsLive( - isOpen ? messageId : null - ); + const { data: commentsData, isLoading: isCommentsLoading } = useComments({ + messageId, + enabled: isOpen, + }); const [{ data: membersData, isLoading: isMembersLoading }] = useAtom(membersAtom); const [{ data: currentUser }] = useAtom(currentUserAtom); @@ -35,8 +35,9 @@ export function CommentPanelContainer({ const [{ mutate: deleteComment, isPending: isDeleting }] = useAtom(deleteCommentMutationAtom); const commentThreads = useMemo(() => { - return liveComments.map(transformComment); - }, [liveComments]); + if (!commentsData?.comments) return []; + return commentsData.comments.map(transformComment); + }, [commentsData]); const members = useMemo(() => { if (!membersData) return []; diff --git a/surfsense_web/contracts/types/chat-messages.types.ts b/surfsense_web/contracts/types/chat-messages.types.ts index 01edef3f2..faba71bff 100644 --- a/surfsense_web/contracts/types/chat-messages.types.ts +++ b/surfsense_web/contracts/types/chat-messages.types.ts @@ -6,7 +6,7 @@ import { z } from "zod"; export const rawMessage = z.object({ id: z.number(), thread_id: z.number(), - role: z.enum(["user", "assistant", "system"]), + role: z.string(), content: z.unknown(), author_id: z.string().nullable(), created_at: z.string(), diff --git a/surfsense_web/hooks/use-chat-messages-live.ts b/surfsense_web/hooks/use-chat-messages-live.ts index 39341d479..4a8ae97e6 100644 --- a/surfsense_web/hooks/use-chat-messages-live.ts +++ b/surfsense_web/hooks/use-chat-messages-live.ts @@ -55,10 +55,15 @@ export function useChatMessagesLive(threadId: number | null) { // Transform raw messages to MessageRecord with author info return [...messagesData].map((msg): MessageRecord => { const author = msg.author_id ? memberMap.get(msg.author_id) : null; + + const role = (typeof msg.role === "string" ? msg.role.toLowerCase() : msg.role) as + | "user" + | "assistant" + | "system"; return { id: msg.id, thread_id: msg.thread_id, - role: msg.role, + role, content: msg.content, created_at: msg.created_at, author_id: msg.author_id, From ac7d84571dbbe834d01ecf653d1c95df288946a5 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 17:27:42 +0200 Subject: [PATCH 18/25] Add thread_id to chat_comments for Electric sync --- .../75_add_thread_id_to_chat_comments.py | 68 +++++++++++++++++++ surfsense_backend/app/db.py | 8 +++ .../app/services/chat_comments_service.py | 6 +- 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 surfsense_backend/alembic/versions/75_add_thread_id_to_chat_comments.py diff --git a/surfsense_backend/alembic/versions/75_add_thread_id_to_chat_comments.py b/surfsense_backend/alembic/versions/75_add_thread_id_to_chat_comments.py new file mode 100644 index 000000000..ceeb589f4 --- /dev/null +++ b/surfsense_backend/alembic/versions/75_add_thread_id_to_chat_comments.py @@ -0,0 +1,68 @@ +"""Add thread_id to chat_comments for denormalized Electric subscriptions + +This denormalization allows a single Electric SQL subscription per thread +instead of one per message, significantly reducing connection overhead. + +Revision ID: 75 +Revises: 74 +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "75" +down_revision: str | None = "74" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Add thread_id column to chat_comments and backfill from messages.""" + # Add the column (nullable initially for backfill) + op.execute( + """ + ALTER TABLE chat_comments + ADD COLUMN IF NOT EXISTS thread_id INTEGER; + """ + ) + + # Backfill thread_id from the related message + op.execute( + """ + UPDATE chat_comments c + SET thread_id = m.thread_id + FROM new_chat_messages m + WHERE c.message_id = m.id + AND c.thread_id IS NULL; + """ + ) + + # Make it NOT NULL after backfill + op.execute( + """ + ALTER TABLE chat_comments + ALTER COLUMN thread_id SET NOT NULL; + """ + ) + + # Add FK constraint + op.execute( + """ + ALTER TABLE chat_comments + ADD CONSTRAINT fk_chat_comments_thread_id + FOREIGN KEY (thread_id) REFERENCES new_chat_threads(id) ON DELETE CASCADE; + """ + ) + + # Add index for efficient Electric subscriptions by thread + op.execute( + "CREATE INDEX IF NOT EXISTS idx_chat_comments_thread_id ON chat_comments(thread_id)" + ) + + +def downgrade() -> None: + """Remove thread_id column from chat_comments.""" + op.execute("DROP INDEX IF EXISTS idx_chat_comments_thread_id") + op.execute("ALTER TABLE chat_comments DROP CONSTRAINT IF EXISTS fk_chat_comments_thread_id") + op.execute("ALTER TABLE chat_comments DROP COLUMN IF EXISTS thread_id") diff --git a/surfsense_backend/app/db.py b/surfsense_backend/app/db.py index 35b512c5e..181f78101 100644 --- a/surfsense_backend/app/db.py +++ b/surfsense_backend/app/db.py @@ -413,6 +413,13 @@ class ChatComment(BaseModel, TimestampMixin): nullable=False, index=True, ) + # Denormalized thread_id for efficient Electric SQL subscriptions (one per thread) + thread_id = Column( + Integer, + ForeignKey("new_chat_threads.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) parent_id = Column( Integer, ForeignKey("chat_comments.id", ondelete="CASCADE"), @@ -436,6 +443,7 @@ class ChatComment(BaseModel, TimestampMixin): # Relationships message = relationship("NewChatMessage", back_populates="comments") + thread = relationship("NewChatThread") author = relationship("User") parent = relationship( "ChatComment", remote_side="ChatComment.id", backref="replies" diff --git a/surfsense_backend/app/services/chat_comments_service.py b/surfsense_backend/app/services/chat_comments_service.py index fa26bf6d5..7e07a56e6 100644 --- a/surfsense_backend/app/services/chat_comments_service.py +++ b/surfsense_backend/app/services/chat_comments_service.py @@ -281,8 +281,10 @@ async def create_comment( detail="You don't have permission to create comments in this search space", ) + thread = message.thread comment = ChatComment( message_id=message_id, + thread_id=thread.id, # Denormalized for efficient Electric subscriptions author_id=user.id, content=content, ) @@ -299,7 +301,6 @@ async def create_comment( user_names = await get_user_names_for_mentions(session, set(mentions_map.keys())) # Create notifications for mentioned users (excluding author) - thread = message.thread author_name = user.display_name or user.email content_preview = render_mentions(content, user_names) for mentioned_user_id, mention_id in mentions_map.items(): @@ -391,8 +392,10 @@ async def create_reply( detail="You don't have permission to create comments in this search space", ) + thread = parent_comment.message.thread reply = ChatComment( message_id=parent_comment.message_id, + thread_id=thread.id, # Denormalized for efficient Electric subscriptions parent_id=comment_id, author_id=user.id, content=content, @@ -410,7 +413,6 @@ async def create_reply( user_names = await get_user_names_for_mentions(session, set(mentions_map.keys())) # Create notifications for mentioned users (excluding author) - thread = parent_comment.message.thread author_name = user.display_name or user.email content_preview = render_mentions(content, user_names) for mentioned_user_id, mention_id in mentions_map.items(): From 4b57ba9d2bac1883d409bc337ea7a77f94f4f803 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 17:56:45 +0200 Subject: [PATCH 19/25] Add chat_comments table to PGlite schema and thread_id to types --- .../contracts/types/chat-comments.types.ts | 1 + surfsense_web/lib/electric/client.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/surfsense_web/contracts/types/chat-comments.types.ts b/surfsense_web/contracts/types/chat-comments.types.ts index c3b32be9d..46e064a4e 100644 --- a/surfsense_web/contracts/types/chat-comments.types.ts +++ b/surfsense_web/contracts/types/chat-comments.types.ts @@ -6,6 +6,7 @@ import { z } from "zod"; export const rawComment = z.object({ id: z.number(), message_id: z.number(), + thread_id: z.number(), // Denormalized for efficient Electric subscriptions parent_id: z.number().nullable(), author_id: z.string().nullable(), content: z.string(), diff --git a/surfsense_web/lib/electric/client.ts b/surfsense_web/lib/electric/client.ts index d900ddb0a..84df6c905 100644 --- a/surfsense_web/lib/electric/client.ts +++ b/surfsense_web/lib/electric/client.ts @@ -240,6 +240,24 @@ export async function initElectric(userId: string): Promise { CREATE INDEX IF NOT EXISTS idx_chat_comment_mentions_comment_id ON chat_comment_mentions(comment_id); `); + // Create chat_comments table for live comment sync + await db.exec(` + CREATE TABLE IF NOT EXISTS chat_comments ( + id INTEGER PRIMARY KEY, + message_id INTEGER NOT NULL, + thread_id INTEGER NOT NULL, + parent_id INTEGER, + author_id TEXT, + content TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE INDEX IF NOT EXISTS idx_chat_comments_thread_id ON chat_comments(thread_id); + CREATE INDEX IF NOT EXISTS idx_chat_comments_message_id ON chat_comments(message_id); + CREATE INDEX IF NOT EXISTS idx_chat_comments_parent_id ON chat_comments(parent_id); + `); + const electricUrl = getElectricUrl(); // STEP 4: Create the client wrapper From 0b8fed7304aee0275f8e249bcd81e80cbeca6087 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 17:57:20 +0200 Subject: [PATCH 20/25] Add thread-level Electric sync for comments, remove per-message hooks --- .../components/assistant-ui/thread.tsx | 4 + surfsense_web/hooks/use-comments-electric.ts | 361 ++++++++++++++++++ surfsense_web/hooks/use-comments-live.ts | 154 -------- 3 files changed, 365 insertions(+), 154 deletions(-) create mode 100644 surfsense_web/hooks/use-comments-electric.ts delete mode 100644 surfsense_web/hooks/use-comments-live.ts diff --git a/surfsense_web/components/assistant-ui/thread.tsx b/surfsense_web/components/assistant-ui/thread.tsx index d65372c24..e1169867c 100644 --- a/surfsense_web/components/assistant-ui/thread.tsx +++ b/surfsense_web/components/assistant-ui/thread.tsx @@ -62,6 +62,7 @@ import type { ThinkingStep } from "@/components/tool-ui/deepagent-thinking"; import { Button } from "@/components/ui/button"; import type { Document } from "@/contracts/types/document.types"; import { useChatSessionState } from "@/hooks/use-chat-session-state"; +import { useCommentsElectric } from "@/hooks/use-comments-electric"; import { cn } from "@/lib/utils"; interface ThreadProps { @@ -238,6 +239,9 @@ const Composer: FC = () => { const { isAiResponding, respondingToUserId } = useChatSessionState(threadId); const isBlockedByOtherUser = isAiResponding && respondingToUserId !== currentUser?.id; + // Sync comments for the entire thread via Electric SQL (one subscription per thread) + useCommentsElectric(threadId); + // Auto-focus editor on new chat page after mount useEffect(() => { if (isThreadEmpty && !hasAutoFocusedRef.current && editorRef.current) { diff --git a/surfsense_web/hooks/use-comments-electric.ts b/surfsense_web/hooks/use-comments-electric.ts new file mode 100644 index 000000000..83a019ef3 --- /dev/null +++ b/surfsense_web/hooks/use-comments-electric.ts @@ -0,0 +1,361 @@ +"use client"; + +import { useQueryClient } from "@tanstack/react-query"; +import { useAtomValue } from "jotai"; +import { useCallback, useEffect, useMemo, useRef } from "react"; +import { membersAtom, myAccessAtom } from "@/atoms/members/members-query.atoms"; +import { currentUserAtom } from "@/atoms/user/user-query.atoms"; +import type { + Comment, + CommentReply, + Author, +} from "@/contracts/types/chat-comments.types"; +import type { Membership } from "@/contracts/types/members.types"; +import type { SyncHandle } from "@/lib/electric/client"; +import { useElectricClient } from "@/lib/electric/context"; +import { cacheKeys } from "@/lib/query-client/cache-keys"; + +// Raw comment from PGlite local database +interface RawCommentRow { + id: number; + message_id: number; + thread_id: number; + parent_id: number | null; + author_id: string | null; + content: string; + created_at: string; + updated_at: string; +} + +// Regex pattern to match @[uuid] mentions (matches backend MENTION_PATTERN) +const MENTION_PATTERN = /@\[([0-9a-fA-F-]{36})\]/g; + +type MemberInfo = Pick; + +/** + * Render mentions in content by replacing @[uuid] with @{DisplayName} + */ +function renderMentions(content: string, memberMap: Map): string { + return content.replace(MENTION_PATTERN, (match, uuid) => { + const member = memberMap.get(uuid); + if (member?.user_display_name) { + return `@{${member.user_display_name}}`; + } + return match; + }); +} + +/** + * Build member lookup map from membersData + */ +function buildMemberMap(membersData: Membership[] | undefined): Map { + const map = new Map(); + if (membersData) { + for (const m of membersData) { + map.set(m.user_id, { + user_display_name: m.user_display_name, + user_avatar_url: m.user_avatar_url, + user_email: m.user_email, + }); + } + } + return map; +} + +/** + * Build author object from member data + */ +function buildAuthor(authorId: string | null, memberMap: Map): Author | null { + if (!authorId) return null; + const m = memberMap.get(authorId); + if (!m) return null; + return { + id: authorId, + display_name: m.user_display_name ?? null, + avatar_url: m.user_avatar_url ?? null, + email: m.user_email ?? "", + }; +} + +/** + * Check if a comment has been edited by comparing timestamps. + * Uses a small threshold to handle precision differences. + */ +function isEdited(createdAt: string, updatedAt: string): boolean { + const created = new Date(createdAt).getTime(); + const updated = new Date(updatedAt).getTime(); + // Consider edited if updated_at is more than 1 second after created_at + return updated - created > 1000; +} + +/** + * Transform raw comment to CommentReply + */ +function transformReply( + raw: RawCommentRow, + memberMap: Map, + currentUserId: string | undefined, + isOwner: boolean +): CommentReply { + return { + id: raw.id, + content: raw.content, + content_rendered: renderMentions(raw.content, memberMap), + author: buildAuthor(raw.author_id, memberMap), + created_at: raw.created_at, + updated_at: raw.updated_at, + is_edited: isEdited(raw.created_at, raw.updated_at), + can_edit: currentUserId === raw.author_id, + can_delete: currentUserId === raw.author_id || isOwner, + }; +} + +/** + * Transform raw comments to Comment with replies + */ +function transformComments( + rawComments: RawCommentRow[], + memberMap: Map, + currentUserId: string | undefined, + isOwner: boolean +): Map { + // Group comments by message_id + const byMessage = new Map }>(); + + for (const raw of rawComments) { + if (!byMessage.has(raw.message_id)) { + byMessage.set(raw.message_id, { topLevel: [], replies: new Map() }); + } + const group = byMessage.get(raw.message_id)!; + + if (raw.parent_id === null) { + group.topLevel.push(raw); + } else { + if (!group.replies.has(raw.parent_id)) { + group.replies.set(raw.parent_id, []); + } + group.replies.get(raw.parent_id)!.push(raw); + } + } + + // Transform to Comment objects grouped by message_id + const result = new Map(); + + for (const [messageId, group] of byMessage) { + const comments: Comment[] = group.topLevel.map((raw) => { + const replies = (group.replies.get(raw.id) || []) + .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()) + .map((r) => transformReply(r, memberMap, currentUserId, isOwner)); + + return { + id: raw.id, + message_id: raw.message_id, + content: raw.content, + content_rendered: renderMentions(raw.content, memberMap), + author: buildAuthor(raw.author_id, memberMap), + created_at: raw.created_at, + updated_at: raw.updated_at, + is_edited: isEdited(raw.created_at, raw.updated_at), + can_edit: currentUserId === raw.author_id, + can_delete: currentUserId === raw.author_id || isOwner, + reply_count: replies.length, + replies, + }; + }); + + // Sort by created_at + comments.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()); + result.set(messageId, comments); + } + + return result; +} + +/** + * Hook for syncing comments with Electric SQL real-time sync. + * + * Syncs ALL comments for a thread in ONE subscription, then updates + * React Query cache for each message. This avoids N subscriptions for N messages. + * + * @param threadId - The thread ID to sync comments for + */ +export function useCommentsElectric(threadId: number | null) { + const electricClient = useElectricClient(); + const queryClient = useQueryClient(); + + const { data: membersData } = useAtomValue(membersAtom); + const { data: currentUser } = useAtomValue(currentUserAtom); + const { data: myAccess } = useAtomValue(myAccessAtom); + + const memberMap = useMemo(() => buildMemberMap(membersData), [membersData]); + const currentUserId = currentUser?.id; + const isOwner = myAccess?.is_owner ?? false; + + // Use refs for values needed in live query callback to avoid stale closures + const memberMapRef = useRef(memberMap); + const currentUserIdRef = useRef(currentUserId); + const isOwnerRef = useRef(isOwner); + const queryClientRef = useRef(queryClient); + + // Keep refs updated + useEffect(() => { + memberMapRef.current = memberMap; + currentUserIdRef.current = currentUserId; + isOwnerRef.current = isOwner; + queryClientRef.current = queryClient; + }, [memberMap, currentUserId, isOwner, queryClient]); + + const syncHandleRef = useRef(null); + const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null); + const syncKeyRef = useRef(null); + + // Stable callback that uses refs for fresh values + const updateReactQueryCache = useCallback((rows: RawCommentRow[]) => { + const commentsByMessage = transformComments( + rows, + memberMapRef.current, + currentUserIdRef.current, + isOwnerRef.current + ); + + for (const [messageId, comments] of commentsByMessage) { + const cacheKey = cacheKeys.comments.byMessage(messageId); + queryClientRef.current.setQueryData(cacheKey, { + comments, + total_count: comments.length, + }); + } + }, []); + + useEffect(() => { + if (!threadId || !electricClient) { + return; + } + + const syncKey = `comments_${threadId}`; + if (syncKeyRef.current === syncKey) { + return; + } + + // Capture in local variable for use in async functions + const client = electricClient; + + let mounted = true; + syncKeyRef.current = syncKey; + + async function startSync() { + try { + const handle = await client.syncShape({ + table: "chat_comments", + where: `thread_id = ${threadId}`, + columns: ["id", "message_id", "thread_id", "parent_id", "author_id", "content", "created_at", "updated_at"], + primaryKey: ["id"], + }); + + if (!handle.isUpToDate && handle.initialSyncPromise) { + try { + await Promise.race([ + handle.initialSyncPromise, + new Promise((resolve) => setTimeout(resolve, 3000)), + ]); + } catch { + // Initial sync timeout - continue anyway + } + } + + if (!mounted) { + handle.unsubscribe(); + return; + } + + syncHandleRef.current = handle; + + // Fetch initial comments and update cache + await fetchAndUpdateCache(); + + // Set up live query for real-time updates + await setupLiveQuery(); + } catch { + // Sync failed - will retry on next mount + } + } + + async function fetchAndUpdateCache() { + try { + const result = await client.db.query( + `SELECT id, message_id, thread_id, parent_id, author_id, content, created_at, updated_at + FROM chat_comments + WHERE thread_id = $1 + ORDER BY created_at ASC`, + [threadId] + ); + + if (mounted && result.rows) { + updateReactQueryCache(result.rows); + } + } catch { + // Query failed - data will be fetched from API + } + } + + async function setupLiveQuery() { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const db = client.db as any; + + if (db.live?.query && typeof db.live.query === "function") { + const liveQuery = await db.live.query( + `SELECT id, message_id, thread_id, parent_id, author_id, content, created_at, updated_at + FROM chat_comments + WHERE thread_id = $1 + ORDER BY created_at ASC`, + [threadId] + ); + + if (!mounted) { + liveQuery.unsubscribe?.(); + return; + } + + // Set initial results + if (liveQuery.initialResults?.rows) { + updateReactQueryCache(liveQuery.initialResults.rows); + } else if (liveQuery.rows) { + updateReactQueryCache(liveQuery.rows); + } + + // Subscribe to changes + if (typeof liveQuery.subscribe === "function") { + liveQuery.subscribe((result: { rows: RawCommentRow[] }) => { + if (mounted && result.rows) { + updateReactQueryCache(result.rows); + } + }); + } + + if (typeof liveQuery.unsubscribe === "function") { + liveQueryRef.current = liveQuery; + } + } + } catch { + // Live query setup failed - will use initial fetch only + } + } + + startSync(); + + return () => { + mounted = false; + syncKeyRef.current = null; + + if (syncHandleRef.current) { + syncHandleRef.current.unsubscribe(); + syncHandleRef.current = null; + } + if (liveQueryRef.current) { + liveQueryRef.current.unsubscribe(); + liveQueryRef.current = null; + } + }; + }, [threadId, electricClient, updateReactQueryCache]); +} diff --git a/surfsense_web/hooks/use-comments-live.ts b/surfsense_web/hooks/use-comments-live.ts deleted file mode 100644 index f4d922888..000000000 --- a/surfsense_web/hooks/use-comments-live.ts +++ /dev/null @@ -1,154 +0,0 @@ -"use client"; - -import { useShape } from "@electric-sql/react"; -import { useAtomValue } from "jotai"; -import { useMemo } from "react"; -import { membersAtom, myAccessAtom } from "@/atoms/members/members-query.atoms"; -import { currentUserAtom } from "@/atoms/user/user-query.atoms"; -import type { Comment, CommentReply, Author } from "@/contracts/types/chat-comments.types"; -import type { Membership } from "@/contracts/types/members.types"; -import type { RawComment } from "@/contracts/types/chat-comments.types"; - -const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; - -// Regex pattern to match @[uuid] mentions (matches backend MENTION_PATTERN) -const MENTION_PATTERN = /@\[([0-9a-fA-F-]{36})\]/g; - -/** - * Member info for building author objects - derived from Membership - */ -type MemberInfo = Pick; - -/** - * Render mentions in content by replacing @[uuid] with @{DisplayName} - */ -function renderMentions(content: string, memberMap: Map): string { - return content.replace(MENTION_PATTERN, (match, uuid) => { - const member = memberMap.get(uuid); - if (member?.user_display_name) { - return `@{${member.user_display_name}}`; - } - return match; - }); -} - -/** - * Hook to get live comments for a specific message. - * Uses Electric SQL for comments + membersAtom (API) for author info. - * Returns data matching the existing Comment type. - */ -export function useCommentsLive(messageId: number | null) { - const { - data: commentsData, - isLoading: commentsLoading, - isError: commentsError, - error: commentsErrorDetails, - } = useShape({ - url: `${ELECTRIC_URL}/v1/shape`, - params: { - table: "chat_comments", - where: `message_id = ${messageId}`, - }, - }); - - const { data: membersData, isLoading: membersLoading } = useAtomValue(membersAtom); - const { data: currentUser } = useAtomValue(currentUserAtom); - const { data: myAccess } = useAtomValue(myAccessAtom); - - const comments = useMemo(() => { - if (!commentsData) return []; - - // Build member lookup map - const memberMap = new Map(); - if (membersData) { - for (const member of membersData) { - memberMap.set(member.user_id, { - user_display_name: member.user_display_name, - user_avatar_url: member.user_avatar_url, - user_email: member.user_email, - }); - } - } - - const currentUserId = currentUser?.id; - const isOwnerOrAdmin = myAccess?.is_owner ?? false; - - // Build author object from member data - const buildAuthor = (authorId: string | null): Author | null => { - if (!authorId) return null; - const member = memberMap.get(authorId); - if (!member) return null; - return { - id: authorId, - display_name: member.user_display_name ?? null, - avatar_url: member.user_avatar_url ?? null, - email: member.user_email ?? "", - }; - }; - - // Transform raw comment to CommentReply - const transformToReply = (raw: RawComment): CommentReply => { - const isEdited = raw.created_at !== raw.updated_at; - const isAuthor = currentUserId === raw.author_id; - - return { - id: raw.id, - content: raw.content, - content_rendered: renderMentions(raw.content, memberMap), - author: buildAuthor(raw.author_id), - created_at: raw.created_at, - updated_at: raw.updated_at, - is_edited: isEdited, - can_edit: isAuthor, - can_delete: isAuthor || isOwnerOrAdmin, - }; - }; - - // Separate top-level comments and replies - const topLevelRaw: RawComment[] = []; - const repliesMap = new Map(); - - for (const raw of commentsData) { - if (raw.parent_id === null) { - topLevelRaw.push(raw); - } else { - const replies = repliesMap.get(raw.parent_id) || []; - replies.push(raw); - repliesMap.set(raw.parent_id, replies); - } - } - - // Transform top-level comments to Comment type - const transformToComment = (raw: RawComment): Comment => { - const isEdited = raw.created_at !== raw.updated_at; - const isAuthor = currentUserId === raw.author_id; - const rawReplies = repliesMap.get(raw.id) || []; - const replies = rawReplies.map(transformToReply); - - return { - id: raw.id, - message_id: raw.message_id, - content: raw.content, - content_rendered: renderMentions(raw.content, memberMap), - author: buildAuthor(raw.author_id), - created_at: raw.created_at, - updated_at: raw.updated_at, - is_edited: isEdited, - can_edit: isAuthor, - can_delete: isAuthor || isOwnerOrAdmin, - reply_count: replies.length, - replies, - }; - }; - - return topLevelRaw.map(transformToComment); - }, [commentsData, membersData, currentUser?.id, myAccess?.is_owner]); - - return { - comments, - commentCount: commentsData?.length ?? 0, - isLoading: commentsLoading || membersLoading, - isError: commentsError, - error: commentsError ? commentsErrorDetails : null, - }; -} From 12437f840a656a65a358bce7c1f6be270aebd99d Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 18:43:20 +0200 Subject: [PATCH 21/25] Add new_chat_messages table to PGlite and create useMessagesElectric hook --- .../contracts/types/chat-messages.types.ts | 1 - surfsense_web/hooks/use-chat-messages-live.ts | 82 ---------- surfsense_web/hooks/use-messages-electric.ts | 154 ++++++++++++++++++ surfsense_web/lib/electric/client.ts | 15 ++ 4 files changed, 169 insertions(+), 83 deletions(-) delete mode 100644 surfsense_web/hooks/use-chat-messages-live.ts create mode 100644 surfsense_web/hooks/use-messages-electric.ts diff --git a/surfsense_web/contracts/types/chat-messages.types.ts b/surfsense_web/contracts/types/chat-messages.types.ts index faba71bff..78bf7b043 100644 --- a/surfsense_web/contracts/types/chat-messages.types.ts +++ b/surfsense_web/contracts/types/chat-messages.types.ts @@ -10,7 +10,6 @@ export const rawMessage = z.object({ content: z.unknown(), author_id: z.string().nullable(), created_at: z.string(), - updated_at: z.string(), }); export type RawMessage = z.infer; diff --git a/surfsense_web/hooks/use-chat-messages-live.ts b/surfsense_web/hooks/use-chat-messages-live.ts deleted file mode 100644 index 4a8ae97e6..000000000 --- a/surfsense_web/hooks/use-chat-messages-live.ts +++ /dev/null @@ -1,82 +0,0 @@ -"use client"; - -import { useShape } from "@electric-sql/react"; -import { useAtomValue } from "jotai"; -import { useMemo } from "react"; -import { membersAtom } from "@/atoms/members/members-query.atoms"; -import type { RawMessage } from "@/contracts/types/chat-messages.types"; -import type { Membership } from "@/contracts/types/members.types"; -import type { MessageRecord } from "@/lib/chat/thread-persistence"; - -const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; - -/** - * Member info for building author data - derived from Membership - */ -type MemberInfo = Pick; - -/** - * Hook to get live chat messages for real-time sync. - * Uses Electric SQL for messages + membersAtom (API) for author info. - */ -export function useChatMessagesLive(threadId: number | null) { - - const { - data: messagesData, - isLoading: messagesLoading, - isError: messagesError, - error: messagesErrorDetails, - } = useShape({ - url: `${ELECTRIC_URL}/v1/shape`, - params: { - table: "new_chat_messages", - where: `thread_id = ${threadId}`, - }, - }); - - - const { data: membersData, isLoading: membersLoading } = useAtomValue(membersAtom); - - - const messages = useMemo(() => { - if (!messagesData) return []; - - // Build member lookup map - const memberMap = new Map(); - if (membersData) { - for (const member of membersData) { - memberMap.set(member.user_id, { - user_display_name: member.user_display_name, - user_avatar_url: member.user_avatar_url, - }); - } - } - - // Transform raw messages to MessageRecord with author info - return [...messagesData].map((msg): MessageRecord => { - const author = msg.author_id ? memberMap.get(msg.author_id) : null; - - const role = (typeof msg.role === "string" ? msg.role.toLowerCase() : msg.role) as - | "user" - | "assistant" - | "system"; - return { - id: msg.id, - thread_id: msg.thread_id, - role, - content: msg.content, - created_at: msg.created_at, - author_id: msg.author_id, - author_display_name: author?.user_display_name ?? null, - author_avatar_url: author?.user_avatar_url ?? null, - }; - }); - }, [messagesData, membersData]); - - return { - messages, - isLoading: messagesLoading || membersLoading, - isError: messagesError, - error: messagesError ? messagesErrorDetails : null, - }; -} diff --git a/surfsense_web/hooks/use-messages-electric.ts b/surfsense_web/hooks/use-messages-electric.ts new file mode 100644 index 000000000..e8c82e92b --- /dev/null +++ b/surfsense_web/hooks/use-messages-electric.ts @@ -0,0 +1,154 @@ +"use client"; + +import { useCallback, useEffect, useRef } from "react"; +import type { RawMessage } from "@/contracts/types/chat-messages.types"; +import type { SyncHandle } from "@/lib/electric/client"; +import { useElectricClient } from "@/lib/electric/context"; + +/** + * Syncs chat messages for a thread via Electric SQL. + * Calls onMessagesUpdate when messages change. + */ +export function useMessagesElectric( + threadId: number | null, + onMessagesUpdate: (messages: RawMessage[]) => void +) { + const electricClient = useElectricClient(); + + const syncHandleRef = useRef(null); + const liveQueryRef = useRef<{ unsubscribe: () => void } | null>(null); + const syncKeyRef = useRef(null); + const onMessagesUpdateRef = useRef(onMessagesUpdate); + + useEffect(() => { + onMessagesUpdateRef.current = onMessagesUpdate; + }, [onMessagesUpdate]); + + const handleMessagesUpdate = useCallback((rows: RawMessage[]) => { + onMessagesUpdateRef.current(rows); + }, []); + + useEffect(() => { + if (!threadId || !electricClient) { + return; + } + + const syncKey = `messages_${threadId}`; + if (syncKeyRef.current === syncKey) { + return; + } + + const client = electricClient; + let mounted = true; + syncKeyRef.current = syncKey; + + async function startSync() { + try { + const handle = await client.syncShape({ + table: "new_chat_messages", + where: `thread_id = ${threadId}`, + columns: ["id", "thread_id", "role", "content", "author_id", "created_at"], + primaryKey: ["id"], + }); + + if (!handle.isUpToDate && handle.initialSyncPromise) { + try { + await Promise.race([ + handle.initialSyncPromise, + new Promise((resolve) => setTimeout(resolve, 3000)), + ]); + } catch { + // Timeout + } + } + + if (!mounted) { + handle.unsubscribe(); + return; + } + + syncHandleRef.current = handle; + await fetchMessages(); + await setupLiveQuery(); + } catch { + // Sync failed + } + } + + async function fetchMessages() { + try { + const result = await client.db.query( + `SELECT id, thread_id, role, content, author_id, created_at + FROM new_chat_messages + WHERE thread_id = $1 + ORDER BY created_at ASC`, + [threadId] + ); + + if (mounted && result.rows) { + handleMessagesUpdate(result.rows); + } + } catch { + // Query failed + } + } + + async function setupLiveQuery() { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const db = client.db as any; + + if (db.live?.query && typeof db.live.query === "function") { + const liveQuery = await db.live.query( + `SELECT id, thread_id, role, content, author_id, created_at + FROM new_chat_messages + WHERE thread_id = $1 + ORDER BY created_at ASC`, + [threadId] + ); + + if (!mounted) { + liveQuery.unsubscribe?.(); + return; + } + + if (liveQuery.initialResults?.rows) { + handleMessagesUpdate(liveQuery.initialResults.rows); + } else if (liveQuery.rows) { + handleMessagesUpdate(liveQuery.rows); + } + + if (typeof liveQuery.subscribe === "function") { + liveQuery.subscribe((result: { rows: RawMessage[] }) => { + if (mounted && result.rows) { + handleMessagesUpdate(result.rows); + } + }); + } + + if (typeof liveQuery.unsubscribe === "function") { + liveQueryRef.current = liveQuery; + } + } + } catch { + // Live query failed + } + } + + startSync(); + + return () => { + mounted = false; + syncKeyRef.current = null; + + if (syncHandleRef.current) { + syncHandleRef.current.unsubscribe(); + syncHandleRef.current = null; + } + if (liveQueryRef.current) { + liveQueryRef.current.unsubscribe(); + liveQueryRef.current = null; + } + }; + }, [threadId, electricClient, handleMessagesUpdate]); +} diff --git a/surfsense_web/lib/electric/client.ts b/surfsense_web/lib/electric/client.ts index 84df6c905..479026120 100644 --- a/surfsense_web/lib/electric/client.ts +++ b/surfsense_web/lib/electric/client.ts @@ -258,6 +258,21 @@ export async function initElectric(userId: string): Promise { CREATE INDEX IF NOT EXISTS idx_chat_comments_parent_id ON chat_comments(parent_id); `); + // Create new_chat_messages table for live message sync + await db.exec(` + CREATE TABLE IF NOT EXISTS new_chat_messages ( + id INTEGER PRIMARY KEY, + thread_id INTEGER NOT NULL, + role TEXT NOT NULL, + content JSONB NOT NULL, + author_id TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + + CREATE INDEX IF NOT EXISTS idx_new_chat_messages_thread_id ON new_chat_messages(thread_id); + CREATE INDEX IF NOT EXISTS idx_new_chat_messages_created_at ON new_chat_messages(created_at); + `); + const electricUrl = getElectricUrl(); // STEP 4: Create the client wrapper From 4cb835f19fd4708f7a0ab8687de394d3809df6a6 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 18:43:32 +0200 Subject: [PATCH 22/25] Integrate live message sync for shared chat collaboration --- .../new-chat/[[...chat_id]]/page.tsx | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx index 43c33ba5a..cb6e797bd 100644 --- a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx +++ b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx @@ -24,6 +24,7 @@ import { // extractWriteTodosFromContent, hydratePlanStateAtom, } from "@/atoms/chat/plan-state.atom"; +import { membersAtom } from "@/atoms/members/members-query.atoms"; import { currentUserAtom } from "@/atoms/user/user-query.atoms"; import { Thread } from "@/components/assistant-ui/thread"; import { ChatHeader } from "@/components/new-chat/chat-header"; @@ -49,6 +50,8 @@ import { type MessageRecord, type ThreadRecord, } from "@/lib/chat/thread-persistence"; +import { useChatSessionState } from "@/hooks/use-chat-session-state"; +import { useMessagesElectric } from "@/hooks/use-messages-electric"; import { trackChatCreated, trackChatError, @@ -257,6 +260,59 @@ export default function NewChatPage() { // Get current user for author info in shared chats const { data: currentUser } = useAtomValue(currentUserAtom); + // Live collaboration: sync messages from other users via Electric SQL + const { isAiResponding, respondingToUserId } = useChatSessionState(threadId); + const { data: membersData } = useAtomValue(membersAtom); + + const handleElectricMessagesUpdate = useCallback( + (electricMessages: { id: number; thread_id: number; role: string; content: unknown; author_id: string | null; created_at: string }[]) => { + // Skip sync while AI is responding to us or during local streaming + if ((isAiResponding && respondingToUserId === currentUser?.id) || isRunning) { + return; + } + + setMessages((prev) => { + const existingIds = new Set( + prev.map((m) => { + const match = String(m.id).match(/^msg-(\d+)$/); + return match ? Number.parseInt(match[1], 10) : null; + }).filter((id): id is number => id !== null) + ); + + const newConverted: ReturnType[] = []; + for (const msg of electricMessages) { + if (existingIds.has(msg.id)) continue; + + const member = msg.author_id + ? membersData?.find((m) => m.user_id === msg.author_id) + : null; + + newConverted.push( + convertToThreadMessage({ + id: msg.id, + thread_id: msg.thread_id, + role: msg.role.toLowerCase() as "user" | "assistant" | "system", + content: msg.content, + author_id: msg.author_id, + created_at: msg.created_at, + author_display_name: member?.user_display_name ?? null, + author_avatar_url: member?.user_avatar_url ?? null, + }) + ); + } + + if (newConverted.length === 0) { + return prev; + } + + return [...prev, ...newConverted]; + }); + }, + [isAiResponding, respondingToUserId, currentUser?.id, isRunning, membersData] + ); + + useMessagesElectric(threadId, handleElectricMessagesUpdate); + // Create the attachment adapter for file processing const attachmentAdapter = useMemo(() => createAttachmentAdapter(), []); From 39d434b00c32ef366a693926e40063cc503697ac Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 19:04:23 +0200 Subject: [PATCH 23/25] Centralize chat session state sync with single subscription via atom --- .../new-chat/[[...chat_id]]/page.tsx | 10 ++++-- .../atoms/chat/chat-session-state.atom.ts | 15 ++++++++ .../components/assistant-ui/thread.tsx | 6 ++-- surfsense_web/hooks/use-chat-session-state.ts | 35 ++++++++++++------- 4 files changed, 48 insertions(+), 18 deletions(-) create mode 100644 surfsense_web/atoms/chat/chat-session-state.atom.ts diff --git a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx index cb6e797bd..e76b83a97 100644 --- a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx +++ b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx @@ -50,7 +50,8 @@ import { type MessageRecord, type ThreadRecord, } from "@/lib/chat/thread-persistence"; -import { useChatSessionState } from "@/hooks/use-chat-session-state"; +import { chatSessionStateAtom } from "@/atoms/chat/chat-session-state.atom"; +import { useChatSessionStateSync } from "@/hooks/use-chat-session-state"; import { useMessagesElectric } from "@/hooks/use-messages-electric"; import { trackChatCreated, @@ -260,8 +261,11 @@ export default function NewChatPage() { // Get current user for author info in shared chats const { data: currentUser } = useAtomValue(currentUserAtom); - // Live collaboration: sync messages from other users via Electric SQL - const { isAiResponding, respondingToUserId } = useChatSessionState(threadId); + // Live collaboration: sync session state and messages via Electric SQL + useChatSessionStateSync(threadId); + const sessionState = useAtomValue(chatSessionStateAtom); + const isAiResponding = sessionState?.isAiResponding ?? false; + const respondingToUserId = sessionState?.respondingToUserId ?? null; const { data: membersData } = useAtomValue(membersAtom); const handleElectricMessagesUpdate = useCallback( diff --git a/surfsense_web/atoms/chat/chat-session-state.atom.ts b/surfsense_web/atoms/chat/chat-session-state.atom.ts new file mode 100644 index 000000000..4d83a45d4 --- /dev/null +++ b/surfsense_web/atoms/chat/chat-session-state.atom.ts @@ -0,0 +1,15 @@ +"use client"; + +import { atom } from "jotai"; + +export interface ChatSessionStateData { + threadId: number; + isAiResponding: boolean; + respondingToUserId: string | null; +} + +/** + * Global chat session state atom. + * Updated by useChatSessionStateSync hook, read anywhere. + */ +export const chatSessionStateAtom = atom(null); diff --git a/surfsense_web/components/assistant-ui/thread.tsx b/surfsense_web/components/assistant-ui/thread.tsx index e1169867c..e419258f2 100644 --- a/surfsense_web/components/assistant-ui/thread.tsx +++ b/surfsense_web/components/assistant-ui/thread.tsx @@ -61,7 +61,7 @@ import { import type { ThinkingStep } from "@/components/tool-ui/deepagent-thinking"; import { Button } from "@/components/ui/button"; import type { Document } from "@/contracts/types/document.types"; -import { useChatSessionState } from "@/hooks/use-chat-session-state"; +import { chatSessionStateAtom } from "@/atoms/chat/chat-session-state.atom"; import { useCommentsElectric } from "@/hooks/use-comments-electric"; import { cn } from "@/lib/utils"; @@ -236,7 +236,9 @@ const Composer: FC = () => { } return typeof chat_id === "string" ? Number.parseInt(chat_id, 10) || null : null; }, [chat_id]); - const { isAiResponding, respondingToUserId } = useChatSessionState(threadId); + const sessionState = useAtomValue(chatSessionStateAtom); + const isAiResponding = sessionState?.isAiResponding ?? false; + const respondingToUserId = sessionState?.respondingToUserId ?? null; const isBlockedByOtherUser = isAiResponding && respondingToUserId !== currentUser?.id; // Sync comments for the entire thread via Electric SQL (one subscription per thread) diff --git a/surfsense_web/hooks/use-chat-session-state.ts b/surfsense_web/hooks/use-chat-session-state.ts index fb263826f..f3bdd7722 100644 --- a/surfsense_web/hooks/use-chat-session-state.ts +++ b/surfsense_web/hooks/use-chat-session-state.ts @@ -1,30 +1,39 @@ "use client"; import { useShape } from "@electric-sql/react"; +import { useSetAtom } from "jotai"; +import { useEffect } from "react"; +import { chatSessionStateAtom } from "@/atoms/chat/chat-session-state.atom"; import type { ChatSessionState } from "@/contracts/types/chat-session-state.types"; const ELECTRIC_URL = process.env.NEXT_PUBLIC_ELECTRIC_URL || "http://localhost:5133"; /** - * Hook to get live chat session state for collaboration. - * Tracks which user the AI is currently responding to. + * Syncs chat session state for a thread via Electric SQL. + * Call once per thread (in page.tsx). Updates global atom. */ -export function useChatSessionState(threadId: number | null) { - const { data, isLoading, isError, error } = useShape({ +export function useChatSessionStateSync(threadId: number | null) { + const setSessionState = useSetAtom(chatSessionStateAtom); + + const { data } = useShape({ url: `${ELECTRIC_URL}/v1/shape`, params: { table: "chat_session_state", - where: `thread_id = ${threadId}`, + where: `thread_id = ${threadId ?? -1}`, }, }); - const sessionState = data?.[0] ?? null; + useEffect(() => { + if (!threadId) { + setSessionState(null); + return; + } - return { - sessionState, - isAiResponding: !!sessionState?.ai_responding_to_user_id, - respondingToUserId: sessionState?.ai_responding_to_user_id ?? null, - loading: isLoading, - error: isError ? error : null, - }; + const row = data?.[0]; + setSessionState({ + threadId, + isAiResponding: !!row?.ai_responding_to_user_id, + respondingToUserId: row?.ai_responding_to_user_id ?? null, + }); + }, [threadId, data, setSessionState]); } From b1b63c674045b1b8cc15bdeed0fcfc3925b56413 Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 20:40:49 +0200 Subject: [PATCH 24/25] Simplify live message sync using Electric as source of truth --- .../new-chat/[[...chat_id]]/page.tsx | 55 ++++++------------- 1 file changed, 17 insertions(+), 38 deletions(-) diff --git a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx index e76b83a97..2d1c0900c 100644 --- a/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx +++ b/surfsense_web/app/dashboard/[search_space_id]/new-chat/[[...chat_id]]/page.tsx @@ -50,7 +50,6 @@ import { type MessageRecord, type ThreadRecord, } from "@/lib/chat/thread-persistence"; -import { chatSessionStateAtom } from "@/atoms/chat/chat-session-state.atom"; import { useChatSessionStateSync } from "@/hooks/use-chat-session-state"; import { useMessagesElectric } from "@/hooks/use-messages-electric"; import { @@ -263,56 +262,38 @@ export default function NewChatPage() { // Live collaboration: sync session state and messages via Electric SQL useChatSessionStateSync(threadId); - const sessionState = useAtomValue(chatSessionStateAtom); - const isAiResponding = sessionState?.isAiResponding ?? false; - const respondingToUserId = sessionState?.respondingToUserId ?? null; const { data: membersData } = useAtomValue(membersAtom); const handleElectricMessagesUpdate = useCallback( (electricMessages: { id: number; thread_id: number; role: string; content: unknown; author_id: string | null; created_at: string }[]) => { - // Skip sync while AI is responding to us or during local streaming - if ((isAiResponding && respondingToUserId === currentUser?.id) || isRunning) { + if (isRunning) { return; } setMessages((prev) => { - const existingIds = new Set( - prev.map((m) => { - const match = String(m.id).match(/^msg-(\d+)$/); - return match ? Number.parseInt(match[1], 10) : null; - }).filter((id): id is number => id !== null) - ); - - const newConverted: ReturnType[] = []; - for (const msg of electricMessages) { - if (existingIds.has(msg.id)) continue; + if (electricMessages.length < prev.length) { + return prev; + } + return electricMessages.map((msg) => { const member = msg.author_id ? membersData?.find((m) => m.user_id === msg.author_id) : null; - newConverted.push( - convertToThreadMessage({ - id: msg.id, - thread_id: msg.thread_id, - role: msg.role.toLowerCase() as "user" | "assistant" | "system", - content: msg.content, - author_id: msg.author_id, - created_at: msg.created_at, - author_display_name: member?.user_display_name ?? null, - author_avatar_url: member?.user_avatar_url ?? null, - }) - ); - } - - if (newConverted.length === 0) { - return prev; - } - - return [...prev, ...newConverted]; + return convertToThreadMessage({ + id: msg.id, + thread_id: msg.thread_id, + role: msg.role.toLowerCase() as "user" | "assistant" | "system", + content: msg.content, + author_id: msg.author_id, + created_at: msg.created_at, + author_display_name: member?.user_display_name ?? null, + author_avatar_url: member?.user_avatar_url ?? null, + }); + }); }); }, - [isAiResponding, respondingToUserId, currentUser?.id, isRunning, membersData] + [isRunning, membersData] ); useMessagesElectric(threadId, handleElectricMessagesUpdate); @@ -646,8 +627,6 @@ export default function NewChatPage() { content: persistContent, }) .then(() => { - // For new threads, the backend updates the title from the first user message - // Invalidate threads query so sidebar shows the updated title in real-time if (isNewThread) { queryClient.invalidateQueries({ queryKey: ["threads", String(searchSpaceId)] }); } From 03445a5e07a78216dd128631f0af7ab88950a2ee Mon Sep 17 00:00:00 2001 From: CREDO23 Date: Thu, 22 Jan 2026 20:54:09 +0200 Subject: [PATCH 25/25] Fix auto-scroll by explicitly enabling it on ThreadViewport The turnAnchor="top" setting caused autoScroll to default to false. --- surfsense_web/components/assistant-ui/thread.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/surfsense_web/components/assistant-ui/thread.tsx b/surfsense_web/components/assistant-ui/thread.tsx index e419258f2..2127d4d1d 100644 --- a/surfsense_web/components/assistant-ui/thread.tsx +++ b/surfsense_web/components/assistant-ui/thread.tsx @@ -90,6 +90,7 @@ const ThreadContent: FC<{ header?: React.ReactNode }> = ({ header }) => { >