import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { AppConfigView, DashboardState, EventsConfig, FeedMessage, FireEventRequest, FireEventResponse, } from '../../shared/api-types'; import { clearActivityApi, dropPushStream, fetchConfig, fetchState, fireEventApi, makeTabPrimary, patchEventsConfig, postTabStatus, revokePoller, revokePushStream, type TabStatusPayload, } from './api'; import { applyMockFireEvent, applyMockPatchConfig, createMockConfig, createMockDashboardState, } from './mockState'; export interface PulseEvent { channel: 'push' | 'poll' | 'call' | 'event' | 'heartbeat'; ref?: string; at: string; seq: number; } export interface CaptureCommand { requestId: string; kind: 'webcam' | 'screen'; reason: string; } const DEFAULT_CONFIG: AppConfigView = { version: '0.3.0', mode: 'http', mcpPath: '/mcp', mcpHost: '', mcpHostConfigured: false, modernProtocol: '2026-07-28', legacyFallback: true, }; function getOrCreateTabId(): string { if (typeof window === 'undefined') return 'tab_ssr'; const key = 'mcp-webcam-tab-id'; try { const existing = window.sessionStorage.getItem(key); if (existing) return existing; const created = `tab_${Math.random().toString(36).slice(2, 10)}`; window.sessionStorage.setItem(key, created); return created; } catch { return `tab_${Math.random().toString(36).slice(2, 10)}`; } } export function isMockModeEnabled(): boolean { if (typeof window === 'undefined') return false; return new URLSearchParams(window.location.search).get('mock') === '1'; } export function useAppConfig(mockMode: boolean): AppConfigView { const [config, setConfig] = useState(() => mockMode ? createMockConfig() : DEFAULT_CONFIG, ); useEffect(() => { if (mockMode) return; let cancelled = false; fetchConfig() .then((cfg) => { if (!cancelled) setConfig(cfg); }) .catch(() => { // fallback to defaults }); return () => { cancelled = true; }; }, [mockMode]); return config; } export function useFeed( user: string, mockMode: boolean, onCapture: (cmd: CaptureCommand) => void, ) { const [tabId, setTabId] = useState(() => (mockMode ? 'tab_studio_01' : getOrCreateTabId())); const [state, setState] = useState(() => mockMode ? createMockDashboardState(user, 'tab_studio_01') : null, ); const [connected, setConnected] = useState(mockMode); const [lastPulse, setLastPulse] = useState(null); const pulseSeqRef = useRef(0); const onCaptureRef = useRef(onCapture); useEffect(() => { onCaptureRef.current = onCapture; }, [onCapture]); // Mock mode: periodic heartbeat pulse useEffect(() => { if (!mockMode) return; const timer = window.setInterval(() => { setState((prev) => { const base = prev ?? createMockDashboardState(user, tabId); if (base.push.length === 0) return base; const first = base.push[0]; const nowIso = new Date().toISOString(); setLastPulse({ channel: 'heartbeat', ref: first.streamId, at: nowIso, seq: ++pulseSeqRef.current, }); return { ...base, user, serverTime: nowIso, push: base.push.map((p) => ({ ...p, lastHeartbeatAt: nowIso })), }; }); }, 6000); return () => window.clearInterval(timer); }, [mockMode, user, tabId]); // Live SSE /api/feed connection useEffect(() => { if (mockMode) return; let closed = false; let es: EventSource | null = null; let retryTimer: number | null = null; let attempt = 0; const connect = () => { if (closed) return; const url = `/api/feed?user=${encodeURIComponent(user)}&tab=${encodeURIComponent(tabId)}`; es = new EventSource(url); es.onopen = () => { attempt = 0; setConnected(true); }; es.onmessage = (evt) => { try { const msg = JSON.parse(evt.data) as FeedMessage; if (msg.type === 'hello') { setTabId(msg.tabId); setConnected(true); } else if (msg.type === 'state') { setState(msg.state); } else if (msg.type === 'capture') { onCaptureRef.current({ requestId: msg.requestId, kind: msg.kind, reason: msg.reason, }); } else if (msg.type === 'pulse') { setLastPulse({ channel: msg.channel, ref: msg.ref, at: msg.at, seq: ++pulseSeqRef.current, }); } } catch { // ignore malformed frames } }; es.onerror = () => { setConnected(false); es?.close(); es = null; if (closed) return; const delay = Math.min(10000, 1000 * Math.pow(1.6, attempt)); attempt += 1; retryTimer = window.setTimeout(connect, delay); }; }; fetchState(user) .then((s) => { if (!closed) setState((prev) => prev ?? s); }) .catch(() => {}); connect(); return () => { closed = true; if (retryTimer !== null) window.clearTimeout(retryTimer); es?.close(); }; }, [mockMode, user, tabId]); const effectiveState = useMemo(() => { if (!mockMode || !state) return state; return state.user === user ? state : { ...state, user }; }, [mockMode, state, user]); // Actions (works in both live and mock modes) const fireEvent = useCallback( async (req: FireEventRequest): Promise => { if (mockMode) { let res!: FireEventResponse; setState((prev) => { const base = prev ?? createMockDashboardState(user, tabId); const applied = applyMockFireEvent({ ...base, user }, req); res = applied.response; return applied.next; }); return res; } return fireEventApi(user, req); }, [mockMode, user, tabId], ); const updateEventsConfig = useCallback( async (patch: Partial) => { if (mockMode) { setState((prev) => (prev ? applyMockPatchConfig(prev, patch) : prev)); return; } await patchEventsConfig(user, patch); }, [mockMode, user], ); const dropPush = useCallback( async (streamId: string) => { if (mockMode) { setState((prev) => { if (!prev) return prev; const target = prev.push.find((p) => p.streamId === streamId); return { ...prev, push: prev.push.filter((p) => p.streamId !== streamId), activity: [ { id: Date.now(), at: new Date().toISOString(), kind: 'stream.dropped' as const, summary: `Dropped push stream ${streamId} (client will reconnect)`, client: target?.client.name, }, ...prev.activity, ].slice(0, 100), }; }); return; } await dropPushStream(streamId, user); }, [mockMode, user], ); const revokePush = useCallback( async (streamId: string) => { if (mockMode) { setState((prev) => { if (!prev) return prev; const target = prev.push.find((p) => p.streamId === streamId); return { ...prev, push: prev.push.filter((p) => p.streamId !== streamId), activity: [ { id: Date.now(), at: new Date().toISOString(), kind: 'stream.revoked' as const, summary: `Revoked push stream ${streamId} (-32024 Forbidden)`, client: target?.client.name, }, ...prev.activity, ].slice(0, 100), }; }); return; } await revokePushStream(streamId, user); }, [mockMode, user], ); const revokePoll = useCallback( async (pollerId: string) => { if (mockMode) { setState((prev) => { if (!prev) return prev; return { ...prev, pollers: prev.pollers.map((p) => p.pollerId === pollerId ? { ...p, revokePending: true } : p, ), activity: [ { id: Date.now(), at: new Date().toISOString(), kind: 'poll.error' as const, summary: `Queued revoke (-32024) for next poll from ${pollerId}`, }, ...prev.activity, ].slice(0, 100), }; }); return; } await revokePoller(pollerId, user); }, [mockMode, user], ); const setPrimaryTab = useCallback( async (targetTabId: string) => { if (mockMode) { setState((prev) => { if (!prev) return prev; return { ...prev, tabs: prev.tabs.map((t) => ({ ...t, primary: t.tabId === targetTabId })), }; }); return; } await makeTabPrimary(targetTabId, user); }, [mockMode, user], ); const reportTabStatus = useCallback( async (status: TabStatusPayload) => { if (mockMode) { setState((prev) => { if (!prev) return prev; return { ...prev, tabs: prev.tabs.map((t) => (t.tabId === tabId ? { ...t, ...status } : t)), }; }); return; } await postTabStatus(tabId, user, status).catch(() => {}); }, [mockMode, tabId, user], ); const clearActivity = useCallback(async () => { if (mockMode) { setState((prev) => (prev ? { ...prev, activity: [] } : prev)); return; } await clearActivityApi(user); }, [mockMode, user]); return { mockMode, state: effectiveState, connected, tabId, lastPulse, actions: { fireEvent, updateEventsConfig, dropPush, revokePush, revokePoll, setPrimaryTab, reportTabStatus, clearActivity, }, }; }