Spaces:
Running
Running
File size: 10,285 Bytes
6f5f15e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | 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<AppConfigView>(() =>
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<string>(() => (mockMode ? 'tab_studio_01' : getOrCreateTabId()));
const [state, setState] = useState<DashboardState | null>(() =>
mockMode ? createMockDashboardState(user, 'tab_studio_01') : null,
);
const [connected, setConnected] = useState<boolean>(mockMode);
const [lastPulse, setLastPulse] = useState<PulseEvent | null>(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<FireEventResponse> => {
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<EventsConfig>) => {
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,
},
};
}
|