import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks"; import { getApiBaseUrl, getAuthToken, type Message } from "@/lib/api"; import { AGENT_ADMISSION_STORAGE_KEY, AgentRoomClient, agentAuthFrame, agentDisplayMessages, agentUnreadCount, applyAgentEvent, applyAgentReadState, applyAgentHistoryPage, agentUnreadCountIsPartial, createAgentReadSession, createAgentRoomState, parseAgentRoomEvent, syncAgentHistory, type AgentActivity, type AgentRoomState, } from "@/lib/agent-room"; import { AGENT_OUTBOX_STORAGE_KEY, createAgentOptimisticOutbox } from "@/lib/agent-optimistic-outbox"; import { createAgentRoomPresenter } from "@/lib/agent-room-presentation"; import { getAgentPresenceSessionId, syncAgentNotificationRead } from "@/lib/agent-push-browser"; import { AGENT_ATTACHMENT_DRAFT_KEY, createAgentUploadQueue, type AgentAttachment, type AgentAttachmentCapability } from "@/lib/agent-attachments"; export type AgentRoomConnection = "connecting" | "connected" | "reconnecting" | "offline"; export type AgentRoomHookResult = { messages: Message[]; activity: AgentActivity | null; unreadCount: number; connection: AgentRoomConnection; error: string | null; isLoading: boolean; isTyping: boolean; hasOlder: boolean; historyBeforeCursor: string | null; isLoadingOlder: boolean; olderError: string | null; loadOlder(): void; unreadCountIsPartial: boolean; attachmentCapability?: AgentAttachmentCapability; uploadAttachment(file: File, uploadId: string, signal: AbortSignal): Promise; downloadAttachment(file: AgentAttachment, signal?: AbortSignal): Promise; uploadQueue: ReturnType; sendMessage(content: string, attachments?: AgentAttachment[], onPersisted?: () => void): Promise; retryMessage(messageId: string): Promise; markRead(): void; retry(): void; }; const errorText = (error: unknown) => error instanceof Error ? error.message : String(error); /** Mount once in App; selection controls reading, never the lifetime of this subscription. */ export function useAgentRoom(enabled: boolean): AgentRoomHookResult { const [view, setView] = useState(() => ({ room: createAgentRoomState(), isTyping: false })); const room = view.room; const current = useRef(room); const [connection, setConnection] = useState("offline"); const [attachmentCapability, setAttachmentCapability] = useState(); const [error, setError] = useState(null); const [isLoading, setLoading] = useState(enabled); const [isLoadingOlder, setLoadingOlder] = useState(false); const [olderError, setOlderError] = useState(null); const older = useRef<(() => Promise) | null>(null); const [revision, setRevision] = useState(0); const client = useRef(null); const [, renderUploads] = useState(0); const capabilityRef = useRef(attachmentCapability); capabilityRef.current = enabled ? attachmentCapability : undefined; const uploadQueue = useRef | null>(null); if (!uploadQueue.current) uploadQueue.current = createAgentUploadQueue({ capability: () => capabilityRef.current, upload: (file, id, signal) => { if (!client.current) throw new Error("Agent connection is unavailable."); return client.current.upload(file, id, signal); }, changed: () => renderUploads(n => n + 1), storage: { read: () => { try { return JSON.parse(sessionStorage.getItem(AGENT_ATTACHMENT_DRAFT_KEY) || "null"); } catch { return null; } }, write: rows => { try { sessionStorage.setItem(AGENT_ATTACHMENT_DRAFT_KEY, JSON.stringify(rows)); } catch { throw new Error("Could not save attachment retry details. Allow session storage before uploading."); } }, }, }); useEffect(() => () => uploadQueue.current?.dispose(), []); const mark = useRef<((cursor: string, sourceId: string | null | undefined) => void) | null>(null); const sourceMismatch = useRef(false); const [outboxRevision, setOutboxRevision] = useState(0); const update = useCallback((change: (state: AgentRoomState) => AgentRoomState) => { const next = change(current.current); current.current = next; setView(previous => ({ ...previous, room: next })); }, []); const outbox = useRef | null>(null); if (!outbox.current) { const stored = (key: string) => { try { return JSON.parse(sessionStorage.getItem(key) || "null"); } catch { return null; } }; outbox.current = createAgentOptimisticOutbox({ submit: (content, requestId, attachments) => { if (!client.current) throw new Error("Agent connection is unavailable."); return client.current.submit(content, requestId, attachments); }, changed: () => setOutboxRevision(value => value + 1), storage: { read: () => stored(AGENT_OUTBOX_STORAGE_KEY), legacyRows: () => stored("sybil.pi-root.outbox"), legacyIds: () => stored(AGENT_ADMISSION_STORAGE_KEY), write: rows => { try { // Keep [] as a migration marker; legacy keys are retired only once // their replacement has been saved successfully. sessionStorage.setItem(AGENT_OUTBOX_STORAGE_KEY, JSON.stringify(rows)); sessionStorage.removeItem("sybil.pi-root.outbox"); sessionStorage.removeItem(AGENT_ADMISSION_STORAGE_KEY); } catch { throw new Error("Could not save this message for retry. Allow session storage or free browser storage, then retry."); } }, }, }); } useEffect(() => { setLoadingOlder(false); setOlderError(null); if (!enabled) { sourceMismatch.current = false; client.current = null; mark.current = null; older.current = null; setAttachmentCapability(undefined); update(() => createAgentRoomState()); setLoading(false); setConnection("offline"); setError(null); return; } let active = true; let sourceChanged = false; let socket: WebSocket | undefined; let reconnectTimer: ReturnType | undefined; let startupTimer: ReturnType | undefined; let socketTimeout: ReturnType | undefined; let reconnectAttempt = 0; let started = false; let maintaining = false; let loadingOlder = false; let lastPacket = Date.now(); let socketAuthenticated = false; let authFailed = false; const controller = new AbortController(); const api = new AgentRoomClient({ baseUrl: getApiBaseUrl(), token: getAuthToken }); client.current = api; const presenter = createAgentRoomPresenter({ initial: current.current, reduceEvent: applyAgentEvent, publish: (next, isTyping) => { if (!active || sourceChanged) return; outbox.current?.reconcile(next); current.current = next; setView({ room: next, isTyping }); }, }); setLoading(!current.current.historyLoaded); setConnection("connecting"); setError(null); const reportError = (failure: unknown) => { if (active && !controller.signal.aborted) setError(errorText(failure)); }; const readSession = createAgentReadSession({ initial: current.current, save: (cursor, sourceId) => api.markRead(cursor, controller.signal, sourceId), invalidated: failure => { sourceChanged = true; sourceMismatch.current = true; mark.current = null; clearTimeout(reconnectTimer); clearTimeout(startupTimer); clearTimeout(socketTimeout); presenter.dispose(); controller.abort(); socket?.close(); older.current = null; setLoadingOlder(false); setError(failure.message); setConnection("offline"); setLoading(false); }, apply: read => { void syncAgentNotificationRead(read); if (active && !sourceChanged) presenter.update(state => applyAgentReadState(state, read)); }, }); mark.current = (cursor, sourceId) => { void readSession.request(cursor, sourceId).catch(reportError); }; const refreshRead = async () => { const read = await api.readState(controller.signal); if (active && !sourceChanged) readSession.receive(read); }; const catchUp = async (replay = false) => syncAgentHistory(api, current.current.cursor, page => { if (active && !sourceChanged) presenter.push({ type: "messages", ...page }, { replay }); }, controller.signal); const refreshActivity = async () => { const descriptor = await api.descriptor(controller.signal); if (active && !sourceChanged) { setAttachmentCapability(descriptor.capabilities?.attachments?.version === 1 ? descriptor.capabilities.attachments : undefined); presenter.push({ type: "activity", conversationId: descriptor.id, activity: descriptor.activity }); } }; older.current = async () => { const before = current.current.beforeCursor; if (!active || sourceChanged || !started || loadingOlder || !current.current.hasOlder || before === null) return; loadingOlder = true; setLoadingOlder(true); setOlderError(null); try { const page = await api.history(before, controller.signal); if (!active || sourceChanged || controller.signal.aborted) return; presenter.update(state => applyAgentHistoryPage(state, page, before)); presenter.flush(); } catch (failure) { if (active && !sourceChanged && !controller.signal.aborted) setOlderError(errorText(failure)); } finally { loadingOlder = false; if (active && !sourceChanged) setLoadingOlder(false); } }; const connect = () => { if (!active || authFailed || sourceChanged) return; clearTimeout(reconnectTimer); clearTimeout(socketTimeout); setConnection(reconnectAttempt ? "reconnecting" : "connecting"); socketAuthenticated = false; const next = new WebSocket(api.websocketUrl(window.location.href)); socket = next; socketTimeout = setTimeout(() => { if (!socketAuthenticated) next.close(); }, 12_000); next.onopen = () => { if (!active || sourceChanged || socket !== next) { next.close(); return; } lastPacket = Date.now(); next.send(agentAuthFrame(getAuthToken(), current.current.cursor, getAgentPresenceSessionId())); }; next.onmessage = ({ data }) => { if (!active || sourceChanged || socket !== next) return; lastPacket = Date.now(); try { const event = parseAgentRoomEvent(String(data)); if (!event) return; if (event.type === "error") { reportError(new Error(event.error || event.message || "Agent connection error.")); return; } if (event.type === "ready") { clearTimeout(socketTimeout); socketAuthenticated = true; reconnectAttempt = 0; setConnection("connected"); setError(null); return; } if (event.type === "read_state") { readSession.receive(event); return; } presenter.push(event); } catch (failure) { reportError(failure); // A malformed message must not advance the replay cursor. Reconnect // from the last applied page, rather than silently skipping that input. next.close(); } }; next.onerror = () => { if (active && !sourceChanged) setConnection("reconnecting"); }; next.onclose = event => { if (!active || sourceChanged || socket !== next) return; clearTimeout(socketTimeout); socketAuthenticated = false; if (event.code === 4401) { authFailed = true; setConnection("offline"); setError("Agent authentication failed. Sign in again or retry."); return; } setConnection("reconnecting"); const wait = Math.min(30_000, 1000 * 2 ** Math.min(reconnectAttempt++, 5)); reconnectTimer = setTimeout(connect, wait); }; }; const start = async () => { try { await Promise.all([refreshRead(), refreshActivity()]); if (!current.current.historyLoaded) { const page = await api.history(undefined, controller.signal); if (!active || sourceChanged || controller.signal.aborted) return; presenter.update(state => applyAgentHistoryPage(state, page)); } else await catchUp(!started); if (!active || sourceChanged) return; presenter.flush(); started = true; setLoading(false); connect(); } catch (failure) { if (!active || sourceChanged) return; reportError(failure); setLoading(false); setConnection("offline"); startupTimer = setTimeout(() => { void start(); }, 10_000); } }; const maintain = async (foreground = false) => { if (!active || sourceChanged || !started || maintaining || authFailed) return; maintaining = true; try { await refreshRead(); await readSession.flush(); if (!socketAuthenticated) { await Promise.all([catchUp(), refreshActivity()]); } else if (foreground) await catchUp(); if (socket?.readyState === WebSocket.OPEN) { if (Date.now() - lastPacket > 60_000) socket.close(); else socket.send(JSON.stringify({ type: "ping" })); } } catch (failure) { reportError(failure); } finally { maintaining = false; } }; const focus = () => { if (document.visibilityState === "visible") void maintain(true); }; const interval = setInterval(() => { void maintain(); }, 15_000); window.addEventListener("focus", focus); document.addEventListener("visibilitychange", focus); void start(); return () => { active = false; readSession.cancel(); controller.abort(); presenter.dispose(); clearInterval(interval); clearTimeout(reconnectTimer); clearTimeout(startupTimer); clearTimeout(socketTimeout); window.removeEventListener("focus", focus); document.removeEventListener("visibilitychange", focus); socket?.close(); if (client.current === api) client.current = null; mark.current = null; older.current = null; }; }, [enabled, revision, update]); const renderedCursor = room.cursor; const renderedSourceId = room.sourceId; const hasRenderedHistory = room.messages.some(message => message.role === "user" || message.role === "assistant"); const markRead = useCallback(() => { if (!enabled || isLoading || !hasRenderedHistory) return; // This callback belongs to this rendered snapshot. Reading current.current // here would incorrectly mark a socket message that has not rendered yet. mark.current?.(renderedCursor, renderedSourceId); }, [enabled, isLoading, hasRenderedHistory, renderedCursor, renderedSourceId]); const sendMessage = useCallback(async (content: string, attachments?: AgentAttachment[], onPersisted?: () => void) => { if (!enabled || !outbox.current) throw new Error("Agent connection is unavailable."); await outbox.current.send(content, attachments, () => { uploadQueue.current!.clear(); onPersisted?.(); }); }, [enabled]); const uploadAttachment = useCallback((file: File, uploadId: string, signal: AbortSignal) => { if (!enabled || !client.current) return Promise.reject(new Error("Agent connection is unavailable.")); return client.current.upload(file, uploadId, signal); }, [enabled]); const downloadAttachment = useCallback((file: AgentAttachment, signal?: AbortSignal) => { if (!enabled || !client.current) return Promise.reject(new Error("Agent connection is unavailable.")); return client.current.download(file, signal); }, [enabled]); const retryMessage = useCallback(async (messageId: string) => { if (!enabled || !outbox.current) throw new Error("Agent connection is unavailable."); await outbox.current.retry(messageId); }, [enabled]); const retry = useCallback(() => { if (sourceMismatch.current) { window.location.reload(); return; } setRevision(value => value + 1); }, []); const loadOlder = useCallback(() => { void older.current?.(); }, []); const messages = useMemo(() => outbox.current?.display(agentDisplayMessages(room)) || agentDisplayMessages(room), [room.messages, room.activity, outboxRevision]); return { messages: enabled ? messages : [], activity: room.activity, unreadCount: agentUnreadCount(room), connection, error, isLoading, hasOlder: room.hasOlder, historyBeforeCursor: room.beforeCursor, isLoadingOlder, olderError, loadOlder, unreadCountIsPartial: agentUnreadCountIsPartial(room), attachmentCapability, uploadQueue: uploadQueue.current!, uploadAttachment, downloadAttachment, isTyping: enabled && view.isTyping, sendMessage, retryMessage, markRead, retry }; }