Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | 2x 2x 26x 26x 26x 26x 1x 26x 6x 6x 6x 1x 5x 5x 6x 5x 5x 5x 6x 1x 4x 1x 3x 3x 4x 5x 26x 2x 2x 2x 2x 2x 2x 2x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 3x 3x 3x 26x 2x 2x 2x 1x 26x 2x 5x 5x 2x 26x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 26x 2x 2x 26x 2x 26x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 26x 21x 1x 1x 6x 6x 2x 2x 1x 1x 5x 5x 2x 2x 2x 2x 2x 2x 26x 20x 20x 20x 20x 18x 20x 26x 20x 20x 20x 20x 26x 24x 1x 1x 1x 1x 1x 26x | import { useEffect, useCallback } from "react";
import { useWebSocket } from "@/hooks/use-websocket";
import { getWebSocketManager } from "@/lib/websocket-manager";
import { Logger } from "@shared/logger";
import { buildGccCompilationErrorState } from "@/lib/compilation-error-state";
import type { ParserMessage, IOPinRecord, OutputLine, WSMessage } from "@shared/schema";
import { telemetryStore } from "@/hooks/use-telemetry-store";
import type { PinState, PinStateType } from "@/hooks/use-simulation-store";
import { emitPinStateChange, emitSimulationStateEvent } from "@/hooks/use-external-api";
import type {
IncomingArduinoMessage,
SerialPayload,
PinStatePayload,
PinStateBatchPayload,
IoRegistryPayload,
SimulationStatusPayload,
CompilationStatusPayload,
CompilationErrorPayload,
SimTelemetryPayload,
} from "@/types/websocket";
const logger = new Logger("useWebSocketHandler");
// NOTE: We intentionally keep OutputLine as a shared type from @shared/schema to
// avoid duplicating the definition across components.
// ─── Regex patterns (extracted to module level) ────────────────────────────
/** Match "Pin Xx is..." messages (e.g., "Pin 13 is...") – S5843 fix (use .exec()) */
const PIN_MESSAGE_RE = /Pin\s+(\S+)\s+is/;
/** Extract pin key from Arduino parser message (e.g., "Pin 13 is..." → "13") */
function extractPinKeyFromMessage(msg: string): string | null {
const match = PIN_MESSAGE_RE.exec(msg);
return match?.[1] ?? null;
}
/**
* Merge incoming parser warnings into existing messages.
* Replaces stale "pinMode() was never called" messages for the same pin,
* deduplicates, and returns the new array (or the original if nothing changed).
* Extracted to fix S2004 (nesting depth) in useWebSocketHandler.
*/
function mergeParserWarnings(
prev: ParserMessage[],
usageWarnings: ParserMessage[],
): ParserMessage[] {
const cleanedPrev = prev.filter((existing) => {
if (existing.category !== "pins") return true;
if (!existing.message.includes("pinMode() was never called")) return true;
const pinKey = extractPinKeyFromMessage(existing.message);
if (!pinKey) return true;
return !usageWarnings.some((m) => extractPinKeyFromMessage(m.message) === pinKey);
});
const existingKeys = new Set(cleanedPrev.map((m) => `${m.category}:${m.message}`));
const newMessages = usageWarnings.filter((m) => !existingKeys.has(`${m.category}:${m.message}`));
return newMessages.length > 0 ? [...cleanedPrev, ...newMessages] : cleanedPrev;
}
export type UseWebSocketHandlerParams = {
// read-only state used inside the handler
simulationStatus: "running" | "stopped" | "paused";
// callbacks / setters from parent scope
addDebugMessage: (source: "frontend" | "server", type: string, data: string, protocol?: "websocket" | "http") => void;
setRxActivity: React.Dispatch<React.SetStateAction<number>>;
appendSerialOutput: (text: string) => void;
appendRenderedText: (text: string) => void;
setSerialOutput: React.Dispatch<React.SetStateAction<OutputLine[]>>;
setArduinoCliStatus: React.Dispatch<React.SetStateAction<"idle" | "compiling" | "success" | "error">>;
setCliOutput: React.Dispatch<React.SetStateAction<string>>;
setHasCompilationErrors: React.Dispatch<React.SetStateAction<boolean>>;
setLastCompilationResult: React.Dispatch<React.SetStateAction<"success" | "error" | null>>;
setShowCompilationOutput: React.Dispatch<React.SetStateAction<boolean>>;
setParserPanelDismissed: React.Dispatch<React.SetStateAction<boolean>>;
setActiveOutputTab: React.Dispatch<React.SetStateAction<"compiler" | "messages" | "registry" | "debug">>;
setCompilationStatus: React.Dispatch<React.SetStateAction<"ready" | "compiling" | "success" | "error">>;
setSimulationStatus: React.Dispatch<React.SetStateAction<"running" | "stopped" | "paused">>;
stopRendering: () => void;
pauseRendering: () => void;
resumeRendering: () => void;
serialEventQueueRef: React.MutableRefObject<Array<{ payload: IncomingArduinoMessage; receivedAt: number }>>;
setPinStates: React.Dispatch<React.SetStateAction<PinState[]>>;
setAnalogPinsUsed: React.Dispatch<React.SetStateAction<number[]>>;
resetPinUI: (opts?: { keepDetected?: boolean }) => void;
enqueuePinEvent: (pin: number, stateType: PinStateType, value: number) => void;
setIoRegistry: React.Dispatch<React.SetStateAction<IOPinRecord[]>>;
setBaudRate: React.Dispatch<React.SetStateAction<number>>;
setSerialBaudrate: (baud: number) => void;
pinToNumber: (pin: string) => number | null;
setParserMessages: React.Dispatch<React.SetStateAction<ParserMessage[]>>;
setSandboxMode: React.Dispatch<React.SetStateAction<string>>;
setWorkerIndex: React.Dispatch<React.SetStateAction<number | undefined>>;
setWorkerTotal: React.Dispatch<React.SetStateAction<number | undefined>>;
};
export function useWebSocketHandler(params: UseWebSocketHandlerParams) {
const {
simulationStatus,
addDebugMessage,
setRxActivity,
appendSerialOutput,
appendRenderedText,
setSerialOutput,
setArduinoCliStatus,
setCliOutput,
setHasCompilationErrors,
setLastCompilationResult,
setShowCompilationOutput,
setParserPanelDismissed,
setActiveOutputTab,
setCompilationStatus,
setSimulationStatus,
setSandboxMode,
setWorkerIndex,
setWorkerTotal,
stopRendering,
pauseRendering,
resumeRendering,
serialEventQueueRef,
setPinStates,
setAnalogPinsUsed,
resetPinUI,
enqueuePinEvent,
setIoRegistry,
setBaudRate,
setSerialBaudrate,
pinToNumber,
setParserMessages,
} = params;
const {
isConnected,
messageQueue,
consumeMessages,
sendMessage: sendMessageRaw,
} = useWebSocket();
const sendMessage = useCallback((message: WSMessage) => {
sendMessageRaw(message);
}, [sendMessageRaw]);
// ─── Message handlers: extracted to reduce nesting depth and cognitive complexity ───
/** Handle sim_telemetry messages. */
const handleSimTelemetry = (message: SimTelemetryPayload) => {
// Push telemetry unconditionally: the server only sends sim_telemetry
// while the simulation is running, so the status guard is unnecessary.
// Dropping it avoids a timing issue where React batches the
// simulation_status: running message together with the first telemetry
// packet — causing the status to still read "stopped" when the handler
// runs and silently discarding the data.
telemetryStore.pushTelemetry(message.metrics);
};
/** Handle serial_output messages. */
const handleSerialOutput = (message: SerialPayload) => {
let text = (message.data ?? "").toString();
const isComplete = message.isComplete ?? true;
// Skip timing control messages
if (text.includes("[[TIME_RESUMED:") || text.includes("[[TIME_FROZEN:")) {
return;
}
setRxActivity((prev) => prev + 1);
const isNewlineOnly = text === "\n" || text === "\r\n";
if (isNewlineOnly) text = "";
const MAX_SERIAL_LINES = 5000;
const textTrimmed = text.trimEnd();
const isSystemMessage = textTrimmed.startsWith("--- ") && textTrimmed.endsWith(" ---");
if (isSystemMessage) {
appendRenderedText(text);
} else {
// The server now adds newlines after complete lines during batching.
// Only add a final newline if:
// 1. isComplete=true (this line had a newline originally)
// 2. text doesn't already end with newline (server already added it)
let textForRenderer: string;
if (isNewlineOnly) {
textForRenderer = "\n";
I} else if (isComplete && !isNewlineOnly && !text.endsWith('\n')) {
textForRenderer = text + "\n";
} else {
textForRenderer = text;
}
appendSerialOutput(textForRenderer);
}
setSerialOutput((prev) => {
const newLines = [...prev];
if (isComplete) {
if (newLines.length > 0 && !newLines.at(-1)!.complete) {
newLines[newLines.length - 1] = {
text: newLines.at(-1)!.text + text,
complete: true,
};
} else if (text.length > 0) {
newLines.push({ text, complete: true });
}
} else if (newLines.length === 0 || newLines.at(-1)!.complete) {
newLines.push({ text, complete: false });
} else {
newLines[newLines.length - 1] = {
text: newLines.at(-1)!.text + text,
complete: false,
};
}
if (newLines.length > MAX_SERIAL_LINES) {
return newLines.slice(newLines.length - MAX_SERIAL_LINES);
}
return newLines;
});
};
/** Handle compilation_status messages. */
const handleCompilationStatus = (message: CompilationStatusPayload) => {
Eif (message.arduinoCliStatus !== undefined) {
setArduinoCliStatus(message.arduinoCliStatus);
}
Iif (message.sandboxMode !== undefined) {
setSandboxMode(message.sandboxMode);
}
Iif (message.workerIndex !== undefined) {
setWorkerIndex(message.workerIndex);
}
Iif (message.workerTotal !== undefined) {
setWorkerTotal(message.workerTotal);
}
Eif (message.message) {
setCliOutput(message.message);
}
};
/** Handle compilation_error messages. */
const handleCompilationError = (message: CompilationErrorPayload) => {
logger.info(`[WS] GCC Compilation Error detected: ${JSON.stringify(message.data)}`);
const gccErrorState = buildGccCompilationErrorState(message.data);
setCliOutput(gccErrorState.cliOutput);
setHasCompilationErrors(gccErrorState.hasCompilationErrors);
setLastCompilationResult(gccErrorState.lastCompilationResult);
setShowCompilationOutput(gccErrorState.showCompilationOutput);
setParserPanelDismissed(gccErrorState.parserPanelDismissed);
setActiveOutputTab(gccErrorState.activeOutputTab);
setCompilationStatus("error");
setSimulationStatus("stopped");
};
/** Handle simulation_status messages. */
const handleSimulationStatus = (message: SimulationStatusPayload) => {
const { status } = message;
setSimulationStatus(status);
if (status === "stopped") {
stopRendering();
Eif (serialEventQueueRef?.current) {
serialEventQueueRef.current = [];
}
setPinStates([]);
setAnalogPinsUsed([]);
resetPinUI({ keepDetected: true });
setCompilationStatus("ready");
emitSimulationStateEvent("STOPPED");
} else if (status === "paused") {
pauseRendering();
emitSimulationStateEvent("PAUSED");
E} else if (status === "running") {
resumeRendering();
emitSimulationStateEvent("RUNNING");
}
};
/** Handle pin_state messages. */
const handlePinState = (message: PinStatePayload) => {
const { pin, stateType, value } = message;
enqueuePinEvent(pin, stateType, value);
if (stateType === "value" || stateType === "pwm") {
emitPinStateChange(pin, value);
}
};
/** Handle pin_state_batch messages. */
const handlePinStateBatch = (message: PinStateBatchPayload) => {
for (const { pin, stateType, value } of message.states) {
enqueuePinEvent(pin, stateType, value);
if (stateType === "value" || stateType === "pwm") {
emitPinStateChange(pin, value);
}
}
};
/** Extract analog pins from IO registry operations. */
const extractAnalogPinsFromRegistry = (registry: IOPinRecord[]) => {
const analogPins = new Set<number>();
for (const record of registry) {
const usedOps = record.usedAt || [];
const hasAnalogOp = usedOps.some((u: { line: number; operation: string }) =>
u.operation === "analogRead" || u.operation === "analogWrite" || u.operation.startsWith("analogWrite:")
);
if (hasAnalogOp) {
const pinNum = pinToNumber(record.pin);
Eif (pinNum !== null && pinNum >= 14 && pinNum <= 19) {
analogPins.add(pinNum);
}
}
}
return analogPins;
};
/** Update analog pins used in the simulation. */
const updateAnalogPinsUsed = (analogPinsFromRegistry: Set<number>) => {
if (simulationStatus === "running") {
setAnalogPinsUsed((prev) => {
const merged = new Set([...prev, ...Array.from(analogPinsFromRegistry)]);
return Array.from(merged).sort((a, b) => a - b);
});
E} else if (analogPinsFromRegistry.size > 0) {
const arr = Array.from(analogPinsFromRegistry).sort((a, b) => a - b);
setAnalogPinsUsed(arr);
}
};
/** Update pin states from IO registry. */
const updatePinStatesFromRegistry = (registry: IOPinRecord[]) => {
setPinStates((prev) => {
const newStates = [...prev];
for (const record of registry) {
if (!record.defined) continue;
const pinNum = pinToNumber(record.pin);
if (pinNum === null) continue;
const exists = newStates.find((p) => p.pin === pinNum);
if (!exists) {
newStates.push({
pin: pinNum,
mode: "INPUT",
value: 0,
type: "digital",
});
}
}
return newStates;
});
};
/** Handle io_registry messages. */
const handleIoRegistry = (message: IoRegistryPayload) => {
const { registry, baudrate } = message;
setIoRegistry(registry);
Eif (typeof baudrate === "number" && baudrate > 0) {
setBaudRate(baudrate);
setSerialBaudrate(baudrate);
}
const analogPinsFromRegistry = extractAnalogPinsFromRegistry(registry);
updateAnalogPinsUsed(analogPinsFromRegistry);
updatePinStatesFromRegistry(registry);
// Parser messages handling
const usageWarnings: ParserMessage[] = [];
Iif (usageWarnings.length > 0) {
setParserMessages((prev) => {
const updated = mergeParserWarnings(prev, usageWarnings);
if (updated !== prev) setParserPanelDismissed(false);
return updated;
});
}
};
// Helper: single message processor (used by both the mount-consumer and
// the reactive consumer). Extracted so initial queued messages are handled
// the same way as runtime messages and to avoid duplicated logic.
const processMessage = (message: IncomingArduinoMessage) => {
switch (message.type) {
case "sim_telemetry":
handleSimTelemetry(message);
break;
case "serial_output":
handleSerialOutput(message);
break;
case "compilation_status":
handleCompilationStatus(message);
break;
case "compilation_error":
handleCompilationError(message);
break;
case "simulation_status":
handleSimulationStatus(message);
break;
case "pin_state":
handlePinState(message);
break;
case "pin_state_batch":
handlePinStateBatch(message);
break;
case "io_registry":
handleIoRegistry(message);
break;
}
};
// Ensure we process any messages that might already be queued at mount time.
// This guards against test mocks that provide an initial messageQueue value
// and ensures deterministic processing on first render.
useEffect(() => {
try {
// Prefer consuming the hook's queue, but fall back to reading the
// `messageQueue` array directly if the mock/manager returns an empty
// value (tests sometimes provide a pre-seeded array reference).
let initial = consumeMessages();
Iif ((!initial || initial.length === 0) && messageQueue && messageQueue.length > 0) {
initial = Array.from(messageQueue);
// attempt to clear the source queue as well
try {
consumeMessages();
} catch {}
}
if (initial && initial.length > 0) {
for (const message of initial) {
processMessage(message);
}
}
} catch {
// swallow - defensive
}
}, []);
// Explicit manager subscription + cleanup (socket.off style cleanup via the unsubscribe)
useEffect(() => {
const manager = getWebSocketManager();
// We intentionally add a benign subscriber so the hook demonstrates
// explicit unsubscribe/cleanup (per refactor requirement). This is a
// NO-OP handler and does not change runtime behaviour because
// message processing remains driven by the shared messageQueue.
const unsub = manager.on("message", () => {});
return () => {
unsub();
};
}, []);
// Moved messageQueue consumer (preserves original behaviour, no logic change)
useEffect(() => {
if (messageQueue.length === 0) return;
// Log all messages to debug console BEFORE consuming them
messageQueue.forEach((msg) => {
addDebugMessage("server", msg.type || "unknown", JSON.stringify(msg, null, 2), "websocket");
});
const messages = consumeMessages();
for (const message of messages) {
processMessage(message);
}
}, [messageQueue, consumeMessages, addDebugMessage]);
return { sendMessage, isConnected };
}
|