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

84.05% Statements 58/69
74.07% Branches 20/27
76.92% Functions 10/13
86.15% Lines 56/65

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                            4x                   5x 1x                 15x 2x 1x                                                                                                                                                                                             111x         111x                                                       111x                                                                       111x                                 111x 35x 35x       35x 35x         111x 18x 2x 2x   16x       16x 13x 13x   1x     3x     16x 1x 1x       15x 15x 15x     15x 15x 15x   24x         15x 15x 15x     15x   14x   14x 10x 10x 10x 10x 10x   4x 4x 4x 4x       1x 1x 1x 1x         111x                                       111x                                                                                    
import { useCallback, useEffect, type MutableRefObject, type RefObject } from "react";
import { type UseMutationResult } from "@tanstack/react-query";
import { Logger } from "@shared/logger";
import type { IOPinRecord, OutputLine, ParserMessage } from "@shared/schema";
import type { SimulationStatus } from "@shared/types/arduino.types";
import type { CompilationStatus, CompilationResultType } from "@/types/compilation.types";
import type { DebugMessage } from "@/hooks/use-debug-console";
import { useSimulatorControllerState } from "./use-simulator-controller-state";
import type { IncomingArduinoMessage, CompileConfig, CompileResult, CompilerError } from "@/types/websocket";
import { useUiFeedbackAdapter } from "./use-ui-feedback-adapter";
import { useCompileController } from "./use-compile-controller";
import { useSimulationController } from "./use-simulation-controller";
import { buildCompileCommand } from "./compile-command-builder";
 
const logger = new Logger("useCompileAndRun");
 
/** Tracks the Docker/sandbox GCC compile phase for granular UI feedback. */
export type DockerGccPhase = "idle" | "queued" | "active";
 
/** Arduino CLI status type */
export type CliStatus = "idle" | "compiling" | "success" | "error";
 
/** 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";
}
 
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>;
  /** Docker/sandbox GCC compile phase for granular button feedback. */
  dockerGccPhase: DockerGccPhase;
  setDockerGccPhase: SetState<DockerGccPhase>;
  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 {
  const controllerState = useSimulatorControllerState();
 
  // ------------------------------------------------------------
  // UI Feedback Adapter (extrahiert für Schritt 1 von Phase 2.1)
  // ------------------------------------------------------------
  const uiFeedback = useUiFeedbackAdapter({
    toast: params.toast,
    addDebugMessage: params.addDebugMessage,
    triggerErrorGlitch: params.triggerErrorGlitch,
    setCliOutput: controllerState.setCliOutput,
    setPendingPinConflicts: params.setPendingPinConflicts,
  });
 
  // ------------------------------------------------------------
  // Compile Controller (extrahiert für Schritt 2 von Phase 2.1)
  // ------------------------------------------------------------
  const {
    compilationStatus,
    setCompilationStatus,
    arduinoCliStatus,
    setArduinoCliStatus,
    hasCompilationErrors,
    setHasCompilationErrors,
    compilerErrors,
    setCompilerErrors,
    lastCompilationResult,
    setLastCompilationResult,
    cliOutput,
    setCliOutput,
    compileMutation,
    handleCompile,
    handleClearCompilationOutput,
    clearOutputs,
  } = useCompileController({
    ...controllerState,
    // Callbacks
    setParserMessages: params.setParserMessages,
    setParserPanelDismissed: params.setParserPanelDismissed,
    setIoRegistry: params.setIoRegistry,
    setIsModified: params.setIsModified,
    resetPinUI: params.resetPinUI,
 
    // UI Feedback
    uiFeedback: {
      logCompileRequest: uiFeedback.logCompileRequest,
      logCompilationSuccess: uiFeedback.logCompilationSuccess,
      logCompilationError: uiFeedback.logCompilationError,
      triggerCompileErrorGlitch: uiFeedback.triggerCompileErrorGlitch,
      showCompileSuccessToast: uiFeedback.showCompileSuccessToast,
      showCompileErrorToast: uiFeedback.showCompileErrorToast,
      showBackendUnreachableToast: uiFeedback.showBackendUnreachableToast,
      showCompilationFailedWithErrorsToast: uiFeedback.showCompilationFailedWithErrorsToast,
      showNoCodeToast: uiFeedback.showNoCodeToast,
      setCompileSuccessOutput: uiFeedback.setCompileSuccessOutput,
      setCompileErrorOutput: uiFeedback.setCompileErrorOutput,
    },
    isBackendUnreachableError: params.isBackendUnreachableError,
 
    // Editor
    editorRef: params.editorRef,
    tabs: params.tabs,
    activeTabId: params.activeTabId,
    code: params.code,
 
    // Simulation coordination
    clearSerialOutput: params.clearSerialOutput,
    setSerialOutput: params.setSerialOutput,
  });
 
  const simulation = useSimulationController({
    code: params.code,
    hasCompilationErrors,
    isModified: params.isModified,
    ensureBackendConnected: params.ensureBackendConnected,
    sendMessage: params.sendMessage,
    sendMessageImmediate: params.sendMessageImmediate,
    resetPinUI: params.resetPinUI,
    clearOutputs,
    serialEventQueueRef: params.serialEventQueueRef,
    pendingPinConflicts: params.pendingPinConflicts,
    startSimulationRef: params.startSimulationRef,
    uiFeedback,
  });
 
  // Expose a test-only setter so E2E tests can inject the REST-compiled code
  // into the simulation controller before starting a simulation.
  useEffect(() => {
    Eif (import.meta.env.DEV) {
      (globalThis as Record<string, unknown>).__SET_LAST_COMPILED_CODE__ = (code: string, headers: Array<{ name: string; content: string }> = []) => {
        simulation.setCompiledCode(code);
        simulation.setCompiledHeaders?.(headers);
      };
      return () => {
        delete (globalThis as Record<string, unknown>).__SET_LAST_COMPILED_CODE__;
      };
    }
  }, [simulation.setCompiledCode]);
 
  const handleCompileAndStart = useCallback(() => {
    if (!params.ensureBackendConnected("Simulation starten")) {
      simulation.setSimulationStatus("idle");
      return;
    }
    params.setDebugMessages([]);
 
    // Extract code
    let mainSketchCode: string;
    if (params.activeTabId === params.tabs[0]?.id && params.editorRef.current) {
      try {
        mainSketchCode = params.editorRef.current.getValue();
      } catch {
        mainSketchCode = params.tabs[0]?.content || params.code;
      }
    } else {
      mainSketchCode = params.tabs[0]?.content || params.code;
    }
 
    if (!mainSketchCode || mainSketchCode.trim().length === 0) {
      uiFeedback.showNoCodeToast();
      return;
    }
 
    // Build payload
    const { headers } = buildCompileCommand(mainSketchCode, params.tabs);
    logger.info(`[CLIENT] Compile & Start with ${headers.length} headers`);
    logger.info(`[CLIENT] Code length: ${mainSketchCode.length} bytes`);
 
    // Determine code source (editor > tabs > state)
    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();
    params.resetPinUI();
    setCompilationStatus("compiling");
 
    // Compile with custom handlers for compile + start flow
    compileMutation.mutate({ code: mainSketchCode, headers }, {
      onSuccess: (data) => {
        logger.info(`[CLIENT] Compile response: ${JSON.stringify(data, null, 2)}`);
 
        if (data.success) {
          simulation.setCompiledCode(mainSketchCode);
          simulation.setCompiledHeaders?.(headers);
          simulation.startSimulation();
          simulation.setHasCompiledOnce(true);
          params.setIsModified(false);
        } else {
          setCompilationStatus("error");
          simulation.setSimulationStatus("idle");
          uiFeedback.showCompilationFailedWithErrorsToast();
          scheduleCliIdle(setArduinoCliStatus);
        }
      },
      onError: () => {
        setCompilationStatus("error");
        simulation.setSimulationStatus("idle");
        uiFeedback.showCompilationFailedWithErrorsToast();
        scheduleCliIdle(setArduinoCliStatus);
      },
    });
  }, [params, clearOutputs, compileMutation, simulation, uiFeedback]);
 
  const handleReset = useCallback(() => {
    if (!params.ensureBackendConnected("Reset simulation")) return;
    if (simulation.simulationStatus === "running") simulation.handleStop();
    clearOutputs();
    params.resetPinUI({ keepDetected: true });
 
    uiFeedback.showResettingToast();
 
    setTimeout(() => {
      handleCompileAndStart();
    }, 100);
  }, [
    clearOutputs,
    params.ensureBackendConnected,
    handleCompileAndStart,
    params.resetPinUI,
    simulation,
    uiFeedback,
  ]);
 
  return {
    compilationStatus,
    setCompilationStatus,
    arduinoCliStatus,
    setArduinoCliStatus,
    hasCompilationErrors,
    setHasCompilationErrors,
    compilerErrors,
    setCompilerErrors,
    lastCompilationResult,
    setLastCompilationResult,
    cliOutput,
    setCliOutput,
    compileMutation,
    handleCompile,
    handleCompileAndStart,
    handleClearCompilationOutput,
    clearOutputs,
 
    simulationStatus: simulation.simulationStatus,
    setSimulationStatus: simulation.setSimulationStatus,
    hasCompiledOnce: simulation.hasCompiledOnce,
    setHasCompiledOnce: simulation.setHasCompiledOnce,
    simulationTimeout: simulation.simulationTimeout,
    setSimulationTimeout: simulation.setSimulationTimeout,
    dockerGccPhase: controllerState.dockerGccPhase,
    setDockerGccPhase: controllerState.setDockerGccPhase,
    startMutation: simulation.startMutation,
    stopMutation: simulation.stopMutation,
    pauseMutation: simulation.pauseMutation,
    resumeMutation: simulation.resumeMutation,
    handleStart: simulation.handleStart,
    handleStop: simulation.handleStop,
    handlePause: simulation.handlePause,
    handleResume: simulation.handleResume,
    handleReset,
 
    startSimulation: simulation.startSimulation,
    startSimulationRef: simulation.startSimulationRef,
    suppressAutoStopOnce: simulation.suppressAutoStopOnce,
  };
}