All files / client/src/hooks use-compile-and-run.ts

81.48% Statements 220/270
61.53% Branches 80/130
86.95% Functions 40/46
81.32% Lines 209/257

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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792                                                4x       8x 2x                 8x 2x 1x                                                                                                                                                                                                     153x 153x   153x 153x 153x 153x   153x 153x 153x     153x 153x     153x 153x   153x 23x 23x 23x 23x       153x                                                                                                                                     153x   20x 20x 20x           20x 17x   20x 17x 17x 17x                         17x 13x   4x       3x 3x 3x 3x                             153x   13x 13x 13x 13x 13x 13x           13x 13x     13x           13x                         13x               153x   6x 6x 6x 6x 6x   6x                   6x 6x 6x     6x 6x 6x 6x           6x           6x 6x 1x   6x         6x             153x   2x           2x 2x 2x 2x     2x 2x 2x       153x   2x           2x 2x     1x     1x               153x   2x           2x 2x     1x     1x               153x   13x 13x 13x               13x                   13x 13x   11x     11x 11x       11x 11x 1x 3x   1x         1x         2x 2x         2x 1x                 153x 6x     153x             153x 10x 7x 7x   1x         4x 2x     2x           153x   8x       8x               153x 17x 17x 238x   17x 102x   17x         153x 12x 12x 12x     12x 11x   1x     12x       12x 12x 12x                       153x 11x 10x     10x 10x 2x         2x       8x 8x 8x     8x 8x 8x   12x         8x 8x 8x     8x   7x   7x 5x 5x 5x 5x 5x 5x   2x 2x 2x         2x       1x 1x 1x         1x                             153x 1x 1x 1x     153x 8x 7x     153x 3x 2x     153x 3x 2x     153x 3x 2x     153x 3x 3x 3x 3x   3x 3x   3x         3x 1x                         153x                         153x                                                                                
import { useCallback, useRef, useState } from "react";
import type { RefObject, MutableRefObject } from "react";
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { Logger } from "@shared/logger";
import type { IOPinRecord, OutputLine, ParserMessage } from "@shared/schema";
import { useSimulationLifecycle } from "./use-simulation-lifecycle";
import type { DebugMessage } from "@/hooks/use-debug-console";
import {
  isCompileResult,
  isHexResult,
} from "@/types/websocket";
import type {
  CompileConfig,
  CompileResult,
  CompilerError,
  HexResult,
  IncomingArduinoMessage,
} from "@/types/websocket";
 
// status types
type CompilationStatus = "ready" | "compiling" | "success" | "error";
type CompilationResultType = "success" | "error" | null;
 
const logger = new Logger("useCompileAndRun");
 
/** Resets Arduino CLI status to idle after the standard 2-second delay. */
function scheduleCliIdle(setArduinoCliStatus: (s: "idle" | "compiling" | "success" | "error") => void) {
  setTimeout(() => {
    setArduinoCliStatus("idle");
  }, 2000);
}
 
/** Determines where the current code came from (fixes S3776 — extracted from handleCompileAndStart). */
function determineCodeSource(
  editorRef: { current: { getValue: () => string } | null },
  tabs: Array<{ content: string }>,
): "editor" | "tabs" | "state" {
  if (editorRef.current) return "editor";
  if (tabs[0]?.content) return "tabs";
  return "state";
}
 
// reused helpers from previous hooks
type SimulationStatus = "running" | "stopped" | "paused";
type CliStatus = "idle" | "compiling" | "success" | "error";
 
export type SetState<T> = (value: T | ((prev: T) => T)) => void;
 
export type DebugMessageParams = {
  source: "frontend" | "server";
  type: string;
  data: string;
  protocol?: "websocket" | "http";
};
 
// parameters for compile portion (same as old UseCompilationParams)
export type CompileAndRunParams = {
  editorRef: RefObject<{ getValue: () => string } | null>;
  tabs: Array<{ id: string; name: string; content: string }>;
  activeTabId: string | null;
  code: string;
  setSerialOutput: SetState<OutputLine[]>;
  clearSerialOutput: () => void;
  setParserMessages: SetState<ParserMessage[]>;
  setParserPanelDismissed: SetState<boolean>;
  resetPinUI: (opts?: { keepDetected?: boolean }) => void;
  setIoRegistry: SetState<IOPinRecord[]>;
  setIsModified: SetState<boolean>;
  setDebugMessages: SetState<DebugMessage[]>;
  addDebugMessage: (params: DebugMessageParams) => void;
  ensureBackendConnected: (reason: string) => boolean;
  isBackendUnreachableError: (error: unknown) => boolean;
  triggerErrorGlitch: () => void;
  toast: (args: {
    title: string;
    description?: string;
    variant?: "destructive";
  }) => void;
 
  // simulation-specific inputs (some overlap allowed)
  sendMessage: (message: IncomingArduinoMessage) => void;
  // changed to boolean return so callers know if the frame was actually sent
  sendMessageImmediate?: (message: IncomingArduinoMessage) => boolean;
  serialEventQueueRef: MutableRefObject<Array<{ payload: IncomingArduinoMessage; receivedAt: number }>>;
  pendingPinConflicts: number[];
  setPendingPinConflicts: SetState<number[]>;
  isModified?: boolean; // duplicated with compile side
  handleCompileAndStart?: () => void; // used by reset
  startSimulationRef?: MutableRefObject<(() => void) | null>;
};
 
interface UseCompileAndRunResult {
  /* compilation state & helpers */
  compilationStatus: CompilationStatus;
  setCompilationStatus: SetState<CompilationStatus>;
  arduinoCliStatus: CliStatus;
  setArduinoCliStatus: SetState<CliStatus>;
  hasCompilationErrors: boolean;
  setHasCompilationErrors: SetState<boolean>;
  compilerErrors: CompilerError[];
  setCompilerErrors: SetState<CompilerError[]>;
  lastCompilationResult: CompilationResultType;
  setLastCompilationResult: SetState<CompilationResultType>;
  cliOutput: string;
  setCliOutput: SetState<string>;
  compileMutation: UseMutationResult<CompileResult, unknown, CompileConfig, unknown>;
  handleCompile: () => void;
  handleCompileAndStart: () => void;
  handleClearCompilationOutput: () => void;
  clearOutputs: () => void;
 
  /* simulation state & helpers */
  simulationStatus: SimulationStatus;
  setSimulationStatus: SetState<SimulationStatus>;
  hasCompiledOnce: boolean;
  setHasCompiledOnce: SetState<boolean>;
  simulationTimeout: number;
  setSimulationTimeout: SetState<number>;
  startMutation: UseMutationResult<{ success: boolean }, unknown, void, unknown>;
  stopMutation: UseMutationResult<{ success: boolean }, unknown, void, unknown>;
  pauseMutation: UseMutationResult<{ success: boolean }, unknown, void, unknown>;
  resumeMutation: UseMutationResult<{ success: boolean }, unknown, void, unknown>;
  handleStart: () => void;
  handleStop: () => void;
  handlePause: () => void;
  handleResume: () => void;
  handleReset: () => void;
 
  /* compatibility helpers */
  startSimulation: () => void;
  startSimulationRef: MutableRefObject<(() => void) | null>;
  suppressAutoStopOnce: () => void;
}
 
export function useCompileAndRun(params: CompileAndRunParams): UseCompileAndRunResult {
  // ------------------------------------------------------------
  // shared state (compile + simulation)
  // ------------------------------------------------------------
  const [compilationStatus, setCompilationStatus] = useState<CompilationStatus>("ready");
  const [arduinoCliStatus, setArduinoCliStatus] = useState<CliStatus>("idle");
  // gccStatus removed - compiler results are tracked via errors array & flags
  const [hasCompilationErrors, setHasCompilationErrors] = useState(false);
  const [lastCompilationResult, setLastCompilationResult] = useState<CompilationResultType>(null);
  const [cliOutput, setCliOutput] = useState("");
  const [compilerErrors, setCompilerErrors] = useState<CompilerError[]>([]);
 
  const [simulationStatus, setSimulationStatus] = useState<SimulationStatus>("stopped");
  const [hasCompiledOnce, setHasCompiledOnce] = useState(false);
  const [simulationTimeout, setSimulationTimeout] = useState<number>(60);
 
  // refs used internally
  const doUploadOnCompileSuccessRef = useRef(false);
  const lastCompilePayloadRef = useRef<{ code: string; headers?: Array<{ name: string; content: string }> } | null>(null);
 
  // ensure we offer a ref to caller
  const internalStartRef = useRef<(() => void) | null>(null);
  const startSimulationRef = params.startSimulationRef ?? internalStartRef;
 
  const clearOutputs = useCallback(() => {
    setCliOutput("");
    params.setSerialOutput([]);
    params.clearSerialOutput();
    params.setParserMessages([]);
  }, [params]);
 
  // upload mutation used by compile success
  const uploadMutation = useMutation<HexResult, unknown, CompileConfig, unknown>({
    mutationFn: async (payload: CompileConfig): Promise<HexResult> => {
      params.addDebugMessage({
        source: "frontend",
        type: "upload_request",
        data: JSON.stringify({ endpoint: "POST /api/upload", codeLength: payload.code.length }, null, 2),
        protocol: "http",
      });
      const response = await apiRequest("POST", "/api/upload", payload);
      const ct = (response.headers.get("content-type") || "").toLowerCase();
 
      if (ct.includes("application/json")) {
        try {
          const parsed = await response.json();
          return isHexResult(parsed) ? parsed : { success: response.ok, raw: JSON.stringify(parsed) };
        } catch {
          const txt = await response.text();
          return { success: response.ok, raw: txt };
        }
      }
 
      const txt = await response.text();
      return { success: response.ok, raw: txt };
    },
    onSuccess: (data) => {
      if (data.success) {
        params.toast({
          title: "Upload started",
          description: "Upload initiated to connected device.",
        });
        return;
      }
 
      const txt = (data.raw ?? "").trim();
      if (txt.length === 0) {
        params.toast({
          title: "Upload started",
          description: "Upload initiated to connected device.",
        });
        return;
      }
 
      params.toast({
        title: "Upload response",
        description: txt.slice(0, 200),
      });
    },
    onError: (err: unknown) => {
      const backendDown = params.isBackendUnreachableError(err);
      const message = err instanceof Error ? err.message : JSON.stringify(err, null, 2);
      params.toast({
        title: backendDown ? "Backend unreachable" : "Upload failed",
        description: backendDown
          ? "API server unreachable. Please check the backend or reload."
          : message || "Upload failed",
        variant: "destructive",
      });
    },
    onSettled: () => {
      try {
        doUploadOnCompileSuccessRef.current = false;
        lastCompilePayloadRef.current = null;
      } catch { }
    },
  });
 
  // simple compile mutation (callbacks moved to handlers above)
  const compileMutation = useMutation<CompileResult, unknown, CompileConfig, unknown>({
    mutationFn: async (payload: CompileConfig): Promise<CompileResult> => {
      setArduinoCliStatus("compiling");
      setLastCompilationResult(null);
      params.addDebugMessage({
        source: "frontend",
        type: "compile_request",
        data: JSON.stringify({ endpoint: "POST /api/compile", codeLength: payload.code.length }, null, 2),
        protocol: "http",
      });
      const response = await apiRequest("POST", "/api/compile", payload);
      const ct = (response.headers.get("content-type") || "").toLowerCase();
 
      if (ct.includes("application/json")) {
        try {
          const parsed = await response.json();
          return isCompileResult(parsed)
            ? parsed
            : { success: false, errors: JSON.stringify(parsed), raw: JSON.stringify(parsed) };
        } catch {
          const txt = await response.text();
          return { success: false, errors: txt, raw: txt };
        }
      }
 
      const txt = await response.text();
      return { success: false, errors: txt, raw: txt };
    },
    onSuccess: (data) => {
      if (data.success) {
        handleCompileSuccess(data);
      } else {
        handleCompileError(data);
      }
    },
    onError: (error: unknown) => {
      setArduinoCliStatus("error");
      params.triggerErrorGlitch();
      const backendDown = params.isBackendUnreachableError(error);
      params.toast({
        title: backendDown ? "Backend unreachable" : "Compilation with Arduino-CLI Failed",
        description: backendDown
          ? "API server unreachable. Please check the backend or reload."
          : "There were errors in your sketch",
        variant: "destructive",
      });
    },
  });
 
  // ─── Compilation response handlers ───────────────────────────────────────
 
  /**
   * Handle successful compilation: update state, show toast, handle upload queue
   */
  const handleCompileSuccess = useCallback(
    (data: CompileResult) => {
      setArduinoCliStatus("success");
      setHasCompilationErrors(false);
      setLastCompilationResult("success");
      setCompilerErrors([]);
      setCliOutput(data.output || "✓ Arduino-CLI Compilation succeeded.");
      params.addDebugMessage({
        source: "server",
        type: "compilation_status",
        data: JSON.stringify({ success: true }, null, 2),
        protocol: "http",
      });
      params.setParserMessages(data.parserMessages ?? []);
      Iif (data.parserMessages && data.parserMessages.length > 0) {
        params.setParserPanelDismissed(false);
      }
      params.toast({
        title: "Arduino-CLI Compilation succeeded",
        description: "Your sketch has been compiled successfully",
      });
 
      // Handle queued upload
      Iif (doUploadOnCompileSuccessRef.current && data.success) {
        const payload = lastCompilePayloadRef.current;
        if (payload) {
          logger.info(`[CLIENT] Uploading compiled artifact... ${JSON.stringify(payload)}`);
          uploadMutation.mutate(payload);
        } else {
          params.toast({
            title: "Upload failed",
            description: "No compiled artifact available to upload.",
            variant: "destructive",
          });
        }
      }
      doUploadOnCompileSuccessRef.current = false;
    },
    [params, uploadMutation],
  );
 
  /**
   * Handle compilation errors: extract error details, show toast
   */
  const handleCompileError = useCallback(
    (data: CompileResult) => {
      setArduinoCliStatus("error");
      setHasCompilationErrors(true);
      setLastCompilationResult("error");
      let errs: CompilerError[] = [];
      let errText = "";
 
      Iif (Array.isArray(data.errors)) {
        errs = data.errors;
        errText = errs
          .map((e) => {
            const lineStr = e.line ? `:${e.line}` : "";
            const columnStr = e.column ? `:${e.column}` : "";
            const location = `${e.file}${lineStr}${columnStr}`;
            return `${location} ${e.type}: ${e.message}`;
          })
          .join("\n");
      E} else if (typeof data.errors === "string") {
        errs = [{ file: "", line: 0, column: 0, type: "error", message: data.errors }];
        errText = data.errors;
      }
 
      setCompilerErrors(errs);
      params.triggerErrorGlitch();
      setCliOutput(errText || "✗ Arduino-CLI Compilation failed.");
      params.addDebugMessage({
        source: "server",
        type: "compilation_error",
        data: JSON.stringify({ type: "compilation_error", data: data.errors }, null, 2),
        protocol: "http",
      });
      params.addDebugMessage({
        source: "server",
        type: "compilation_status",
        data: JSON.stringify({ success: false }, null, 2),
        protocol: "http",
      });
      params.setParserMessages(data.parserMessages ?? []);
      if (data.parserMessages && data.parserMessages.length > 0) {
        params.setParserPanelDismissed(false);
      }
      params.toast({
        title: "Arduino-CLI Compilation failed",
        description: "There were errors in your sketch",
        variant: "destructive",
      });
      doUploadOnCompileSuccessRef.current = false;
    },
    [params],
  );
 
  // ─── Simulation control mutations ─────────────────────────────────────────
 
  const stopMutation = useMutation({
    mutationFn: async () => {
      params.addDebugMessage({
        source: "frontend",
        type: "stop_simulation",
        data: JSON.stringify({ type: "stop_simulation" }, null, 2),
        protocol: "websocket",
      });
      const immediate = params.sendMessageImmediate ?? undefined;
      Iif (immediate) immediate({ type: "stop_simulation" });
      else params.sendMessage({ type: "stop_simulation" });
      return { success: true };
    },
    onSuccess: () => {
      setSimulationStatus("stopped");
      params.serialEventQueueRef.current = [];
      params.resetPinUI({ keepDetected: true });
    },
  });
 
  const pauseMutation = useMutation({
    mutationFn: async () => {
      params.addDebugMessage({
        source: "frontend",
        type: "pause_simulation",
        data: JSON.stringify({ type: "pause_simulation" }, null, 2),
        protocol: "websocket",
      });
      params.sendMessage({ type: "pause_simulation" });
      return { success: true };
    },
    onSuccess: () => {
      setSimulationStatus("paused");
    },
    onError: () => {
      params.toast({
        title: "Pause failed",
        description: "Could not pause simulation",
        variant: "destructive",
      });
    },
  });
 
  const resumeMutation = useMutation({
    mutationFn: async () => {
      params.addDebugMessage({
        source: "frontend",
        type: "resume_simulation",
        data: JSON.stringify({ type: "resume_simulation" }, null, 2),
        protocol: "websocket",
      });
      params.sendMessage({ type: "resume_simulation" });
      return { success: true };
    },
    onSuccess: () => {
      setSimulationStatus("running");
    },
    onError: () => {
      params.toast({
        title: "Resume failed",
        description: "Could not resume simulation",
        variant: "destructive",
      });
    },
  });
 
  const startMutation = useMutation({
    mutationFn: async () => {
      logger.debug(`[CLIENT] startMutation invoked, simulationTimeout=${simulationTimeout}`);
      params.resetPinUI({ keepDetected: true });
      params.addDebugMessage({
        source: "frontend",
        type: "start_simulation",
        data: JSON.stringify({ type: "start_simulation", timeout: simulationTimeout }, null, 2),
        protocol: "websocket",
      });
      // Use immediate send for start_simulation when available to ensure
      // WS frame is emitted deterministically for E2E tests and real-time control.
      Iif (typeof params.sendMessageImmediate === "function") {
        const sent = params.sendMessageImmediate({ type: "start_simulation", timeout: simulationTimeout });
        logger.debug(`[CLIENT] sendMessageImmediate returned ${String(sent)}`);
        // If immediate send failed (socket not open) fall back to buffered send
        if (!sent) {
          logger.debug("[CLIENT] falling back to buffered send for start_simulation");
          params.addDebugMessage({ source: "frontend", type: "start_simulation", data: "Immediate send failed, falling back to buffered send", protocol: "websocket" });
          params.sendMessage({ type: "start_simulation", timeout: simulationTimeout });
        }
      } else {
        logger.debug("[CLIENT] using buffered send for start_simulation (no immediate available)");
        params.sendMessage({ type: "start_simulation", timeout: simulationTimeout });
      }
      return { success: true };
    },
    onSuccess: () => {
      setSimulationStatus("running");
      params.toast({
        title: "Simulation Started",
        description: "Arduino simulation is now running",
      });
      try {
        if (params.pendingPinConflicts && params.pendingPinConflicts.length > 0) {
          const names = params.pendingPinConflicts
            .map((p) => (p >= 14 && p <= 19 ? `A${p - 14}` : `${p}`))
            .join(", ");
          setCliOutput(
            (prev) =>
              (prev ? prev + "\n\n" : "") +
              `⚠️ Pin usage conflict: Pins used as digital via pinMode(...) and also read with analogRead(): ${names}. This may be unintended.`,
          );
          params.setPendingPinConflicts([]);
        }
      } catch { }
    },
    onError: (error: unknown) => {
      const message = error instanceof Error ? error.message : JSON.stringify(error, null, 2);
      params.toast({
        title: "Start Failed",
        description: message || "Could not start simulation",
        variant: "destructive",
      });
      if (params.isModified && hasCompiledOnce) {
        params.toast({
          title: "Code Modified",
          description: "Compile to apply your latest changes",
        });
      }
    },
  });
 
  // internal start function used by compilation success handler
  const startSimulationInternal = useCallback(() => {
    startMutation.mutate();
  }, [startMutation]);
 
  startSimulationRef.current = startSimulationInternal;
 
  // ─── Helper functions for compile and start ─────────────────────────────
 
  /**
   * Extract main sketch code from editor, tabs, or state (in priority order)
   */
  const extractMainSketchCode = useCallback((): string => {
    if (params.editorRef.current) {
      try {
        return params.editorRef.current.getValue();
      } catch (error) {
        console.error("[CLIENT] Error getting code from editor:", error);
        // Fall through to tabs/code fallback
      }
    }
 
    if (params.tabs.length > 0 && params.tabs[0]?.content) {
      return params.tabs[0].content;
    }
 
    return params.code || "";
  }, [params.code, params.editorRef, params.tabs]);
 
  /**
   * Build compile payload with code + headers
   */
  const buildCompilePayload = useCallback(
    (mainSketchCode: string) => {
      const headers = params.tabs.slice(1).map((tab) => ({
        name: tab.name,
        content: tab.content,
      }));
      return { code: mainSketchCode, headers };
    },
    [params.tabs],
  );
 
  /**
   * Initialize IO registry with empty pin records
   */
  const initializeEmptyRegistry = useCallback(() => {
    const pins: IOPinRecord[] = [];
    for (let i = 0; i <= 13; i++) {
      pins.push({ pin: String(i), defined: false, usedAt: [] });
    }
    for (let i = 0; i <= 5; i++) {
      pins.push({ pin: `A${i}`, defined: false, usedAt: [] });
    }
    params.setIoRegistry(pins);
  }, [params]);
 
  // ─── Compile handlers ────────────────────────────────────────────────────
 
  const handleCompile = useCallback(() => {
    clearOutputs();
    params.resetPinUI();
    initializeEmptyRegistry();
 
    let mainSketchCode: string;
    if (params.activeTabId === params.tabs[0]?.id && params.editorRef.current) {
      mainSketchCode = params.editorRef.current.getValue();
    } else {
      mainSketchCode = params.tabs[0]?.content || params.code;
    }
 
    const headers = params.tabs.slice(1).map((tab) => ({
      name: tab.name,
      content: tab.content,
    }));
    logger.info(`[CLIENT] Compiling with ${headers.length} headers`);
    lastCompilePayloadRef.current = { code: mainSketchCode, headers };
    compileMutation.mutate({ code: mainSketchCode, headers });
  }, [
    params.activeTabId,
    clearOutputs,
    params.code,
    compileMutation,
    params.editorRef,
    params.resetPinUI,
    params.tabs,
    initializeEmptyRegistry,
  ]);
 
  const handleCompileAndStart = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation starten")) return;
    params.setDebugMessages([]);
 
    // Extract code
    const mainSketchCode = extractMainSketchCode();
    if (!mainSketchCode || mainSketchCode.trim().length === 0) {
      params.toast({
        title: "No Code",
        description: "Please write some code before compiling",
        variant: "destructive",
      });
      return;
    }
 
    // Build payload
    const payload = buildCompilePayload(mainSketchCode);
    logger.info(`[CLIENT] Compile & Start with ${payload.headers.length} headers`);
    logger.info(`[CLIENT] Code length: ${mainSketchCode.length} bytes`);
 
    // Determine code source (editor > tabs > state) — helper is module-level (fixes S3776)
    const codeSource = determineCodeSource(params.editorRef, params.tabs);
    logger.info(`[CLIENT] Main code from: ${codeSource}`);
    logger.info(
      `[CLIENT] Tabs: ${params.tabs
        .map((t) => `${t.name}(${t.content.length}b)`)
        .join(", ")}`,
    );
 
    // Clear and prepare
    clearOutputs();
    setCompilationStatus("compiling");
    setArduinoCliStatus("compiling");
 
    // Compile with custom handlers for compile + start flow
    compileMutation.mutate(payload, {
      onSuccess: (data) => {
        logger.info(`[CLIENT] Compile response: ${JSON.stringify(data, null, 2)}`);
 
        if (data.success) {
          initializeEmptyRegistry();
          (startSimulationRef.current ?? startSimulationInternal)();
          setCompilationStatus("success");
          setHasCompiledOnce(true);
          params.setIsModified(false);
          scheduleCliIdle(setArduinoCliStatus);
        } else {
          handleCompileError(data);
          setCompilationStatus("error");
          params.toast({
            title: "Compilation Completed with Errors",
            description: "Simulation will not start due to compilation errors.",
            variant: "destructive",
          });
          scheduleCliIdle(setArduinoCliStatus);
        }
      },
      onError: () => {
        setCompilationStatus("error");
        setArduinoCliStatus("error");
        params.toast({
          title: "Compilation Failed",
          description: "Simulation will not start due to compilation errors.",
          variant: "destructive",
        });
        scheduleCliIdle(setArduinoCliStatus);
      },
    });
  }, [
    params,
    extractMainSketchCode,
    buildCompilePayload,
    clearOutputs,
    compileMutation,
    startSimulationInternal,
    startSimulationRef,
    initializeEmptyRegistry,
    handleCompileError,
  ]);
 
  const handleClearCompilationOutput = useCallback(() => {
    setCliOutput("");
    setLastCompilationResult(null);
    params.setParserMessages([]);
  }, [setCliOutput, setLastCompilationResult, params.setParserMessages]);
 
  const handleStart = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation starten")) return;
    startMutation.mutate();
  }, [params.ensureBackendConnected, startMutation]);
 
  const handleStop = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation stoppen")) return;
    stopMutation.mutate();
  }, [params.ensureBackendConnected, stopMutation]);
 
  const handlePause = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation pausieren")) return;
    pauseMutation.mutate();
  }, [params.ensureBackendConnected, pauseMutation]);
 
  const handleResume = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation fortsetzen")) return;
    resumeMutation.mutate();
  }, [params.ensureBackendConnected, resumeMutation]);
 
  const handleReset = useCallback(() => {
    Iif (!params.ensureBackendConnected("Reset simulation")) return;
    Eif (simulationStatus === "running") {
      params.sendMessage({ type: "stop_simulation" });
      setSimulationStatus("stopped");
    }
    clearOutputs();
    params.resetPinUI({ keepDetected: true });
 
    params.toast({
      title: "Resetting...",
      description: "Recompiling and restarting simulation",
    });
 
    setTimeout(() => {
      handleCompileAndStart();
    }, 100);
  }, [
    clearOutputs,
    params.ensureBackendConnected,
    handleCompileAndStart,
    params.resetPinUI,
    params.sendMessage,
    simulationStatus,
    params.toast,
  ]);
 
  // lifecycle automation (reuse earlier hook)
  const { suppressAutoStopOnce } = useSimulationLifecycle({
    code: params.code,
    simulationStatus,
    setSimulationStatus,
    sendMessage: params.sendMessage,
    resetPinUI: params.resetPinUI,
    clearOutputs,
    handlePause,
    handleResume,
    handleReset,
    hasCompilationErrors,
  });
 
  return {
    compilationStatus,
    setCompilationStatus,
    arduinoCliStatus,
    setArduinoCliStatus,
    hasCompilationErrors,
    setHasCompilationErrors,
    compilerErrors,
    setCompilerErrors,
    lastCompilationResult,
    setLastCompilationResult,
    cliOutput,
    setCliOutput,
    compileMutation,
    handleCompile,
    handleCompileAndStart,
    handleClearCompilationOutput,
    clearOutputs,
 
    simulationStatus,
    setSimulationStatus,
    hasCompiledOnce,
    setHasCompiledOnce,
    simulationTimeout,
    setSimulationTimeout,
    startMutation,
    stopMutation,
    pauseMutation,
    resumeMutation,
    handleStart,
    handleStop,
    handlePause,
    handleResume,
    handleReset,
 
    startSimulation: startSimulationInternal,
    startSimulationRef,
    suppressAutoStopOnce,
  };
}