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

93.12% Statements 122/131
85.48% Branches 53/62
87.5% Functions 21/24
94.16% Lines 113/120

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                                5x                   5x 1x                 44x 28x 1x                                                                                                                     46x   44x 2x 2x                   42x   13x 13x   1x   13x           29x 46x                                                                                                             218x 218x 218x 218x 218x 218x 237x 237x 15x 15x 15x   237x 237x   218x 112x 112x         218x 309x     218x 67x   218x         218x                                                       218x                                                                             218x                                     218x 64x 64x       64x 64x         218x 49x 49x 49x     1x 48x 2x 2x   46x   46x   46x 2x 2x     44x 5x       44x 44x     44x 44x 44x   55x         44x 44x 44x     44x 49x 49x 49x   37x 28x 28x   28x 24x 24x 24x 24x 24x 24x   4x 4x 4x 4x       1x 1x 1x 1x 1x 1x         218x 3x 3x 2x 2x 2x 2x   2x   2x 2x 1x 1x                       218x                             16x 16x                                         1x 1x           1x 1x                                          
import { useCallback, useEffect, useLayoutEffect, useRef, 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 { holdsServerSimulation, 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, type CompileCommand } from "./compile-command-builder";
import type { SourceProject } from "@shared/source-project";
import type { ServerCapabilities } from "@/lib/server-capabilities";
 
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 = {
  readonly capabilities?: ServerCapabilities;
  editorRef: RefObject<{ getValue: () => string } | null>;
  tabs: Array<{ id: string; name: string; path?: string; content: string }>;
  activeTabId: string | null;
  code: string;
  /** Synchronously tracks the latest editor value during batched updates. */
  codeRef?: { current: string };
  sourceProject?: SourceProject | null;
  setSerialOutput: SetState<OutputLine[]>;
  clearSerialOutput: () => void;
  setParserMessages: SetState<ParserMessage[]>;
  setParserPanelDismissed: SetState<boolean>;
  resetPinUI: (opts?: { keepDetected?: boolean }) => void;
  /** Runtime snapshot setter; null means no snapshot for the current run yet. */
  setIoRegistry: SetState<IOPinRecord[] | null>;
  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>;
};
 
type CompileSourceParams = Pick<
  CompileAndRunParams,
  "sourceProject" | "tabs" | "activeTabId" | "editorRef" | "code" | "codeRef"
>;
 
function resolveCompileCommand(params: CompileSourceParams): CompileCommand {
  if (params.sourceProject) return buildCompileCommand(params.sourceProject);
 
  if (params.sourceProject === null) {
    Eif (params.tabs.length === 0) {
      return buildCompileCommand({
        entryFile: "sketch.ino",
        files: {
          "sketch.ino": params.codeRef ? params.codeRef.current : params.code,
        },
      });
    }
    return { code: "", headers: [], entryFile: undefined };
  }
 
  if (params.activeTabId === params.tabs[0]?.id && params.editorRef.current) {
    let mainSketchCode: string;
    try {
      mainSketchCode = params.editorRef.current.getValue();
    } catch {
      mainSketchCode = params.tabs[0]?.content || params.code;
    }
    return {
      code: mainSketchCode,
      headers: buildCompileCommand(mainSketchCode, params.tabs).headers,
    };
  }
 
  const mainSketchCode = params.tabs[0]?.content || params.code;
  return {
    code: mainSketchCode,
    headers: buildCompileCommand(mainSketchCode, params.tabs).headers,
  };
}
 
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;
  /** Call before replacing the workspace or externally loading code. */
  invalidatePendingStart: () => void;
}
 
export function useCompileAndRun(params: CompileAndRunParams): UseCompileAndRunResult {
  const controllerState = useSimulatorControllerState();
  const startGeneration = useRef(0);
  const compileOwners = useRef(new WeakMap<CompileConfig, number>());
  const pendingCompileStart = useRef(false);
  const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const invalidatePendingStart = useCallback(() => {
    startGeneration.current++;
    if (pendingCompileStart.current) {
      controllerState.setCompilationStatus("ready");
      controllerState.setArduinoCliStatus("idle");
      pendingCompileStart.current = false;
    }
    if (resetTimer.current !== null) clearTimeout(resetTimer.current);
    resetTimer.current = null;
  }, [controllerState.setCompilationStatus, controllerState.setArduinoCliStatus]);
  const isCompileResultCurrent = useCallback((payload: CompileConfig) => {
    const owner = compileOwners.current.get(payload);
    return owner === undefined || owner === startGeneration.current;
  }, []);
 
  // Workspace identity excludes editor contents and the selected tab: ordinary
  // navigation/edits keep the captured compile snapshot semantics.
  const workspaceIdentity = JSON.stringify([
    params.tabs.map((tab) => [tab.id, tab.path ?? tab.name]),
    params.sourceProject?.entryFile,
  ]);
  useLayoutEffect(() => {
    invalidatePendingStart();
  }, [workspaceIdentity, invalidatePendingStart]);
  useEffect(() => invalidatePendingStart, [invalidatePendingStart]);
 
  // ------------------------------------------------------------
  // 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,
    capabilities: params.capabilities,
    isCompileResultCurrent,
    // 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,
    sourceProject: params.sourceProject,
 
    // Simulation coordination
    clearSerialOutput: params.clearSerialOutput,
    setSerialOutput: params.setSerialOutput,
  });
 
  const simulation = useSimulationController({
    onStartOrStop: invalidatePendingStart,
    code: params.code,
    hasCompilationErrors,
    isModified: params.isModified,
    ensureBackendConnected: params.ensureBackendConnected,
    capabilities: params.capabilities,
    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(() => {
    invalidatePendingStart();
    const generation = startGeneration.current;
    if (
      params.capabilities &&
      (!params.capabilities.canCompile || !params.capabilities.canSimulate)
    ) return;
    if (!params.ensureBackendConnected("Simulation starten")) {
      simulation.setSimulationStatus("idle");
      return;
    }
    params.setDebugMessages([]);
 
    const { code: mainSketchCode, headers, entryFile } = resolveCompileCommand(params);
 
    if (!mainSketchCode || mainSketchCode.trim().length === 0) {
      uiFeedback.showNoCodeToast();
      return;
    }
    // Compile/Upload restarts: the connection may own only one lifecycle.
    if (holdsServerSimulation(simulation.simulationStatus)) {
      simulation.stopSimulationImmediately();
    }
 
    // Build payload
    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
    const compilePayload = { code: mainSketchCode, headers, ...(entryFile ? { entryFile } : {}) };
    compileOwners.current.set(compilePayload, generation);
    pendingCompileStart.current = true;
    compileMutation.mutate(compilePayload, {
      onSuccess: (data) => {
        if (generation !== startGeneration.current) return;
        pendingCompileStart.current = false;
        logger.info(`[CLIENT] Compile response: ${JSON.stringify(data, null, 2)}`);
 
        if (data.success) {
          simulation.setCompiledCode(mainSketchCode);
          simulation.setCompiledHeaders?.(headers);
          simulation.setCompiledEntryFile?.(entryFile);
          simulation.startSimulation();
          simulation.setHasCompiledOnce(true);
          params.setIsModified(false);
        } else {
          setCompilationStatus("error");
          simulation.setSimulationStatus("idle");
          uiFeedback.showCompilationFailedWithErrorsToast();
          scheduleCliIdle(setArduinoCliStatus);
        }
      },
      onError: () => {
        Iif (generation !== startGeneration.current) return;
        pendingCompileStart.current = false;
        setCompilationStatus("error");
        simulation.setSimulationStatus("idle");
        uiFeedback.showCompilationFailedWithErrorsToast();
        scheduleCliIdle(setArduinoCliStatus);
      },
    });
  }, [params, clearOutputs, compileMutation, simulation, uiFeedback, invalidatePendingStart]);
 
  const handleReset = useCallback(() => {
    invalidatePendingStart();
    if (params.capabilities && !params.capabilities.canSimulate) return;
    Iif (!params.ensureBackendConnected("Reset simulation")) return;
    if (holdsServerSimulation(simulation.simulationStatus)) simulation.handleStop();
    clearOutputs();
    params.resetPinUI({ keepDetected: true });
 
    uiFeedback.showResettingToast();
 
    const generation = startGeneration.current;
    resetTimer.current = setTimeout(() => {
      resetTimer.current = null;
      Eif (generation === startGeneration.current) handleCompileAndStart();
    }, 100);
  }, [
    clearOutputs,
    params.ensureBackendConnected,
    handleCompileAndStart,
    params.resetPinUI,
    simulation,
    uiFeedback,
    invalidatePendingStart,
  ]);
 
  return {
    compilationStatus,
    setCompilationStatus,
    arduinoCliStatus,
    setArduinoCliStatus,
    hasCompilationErrors,
    setHasCompilationErrors,
    compilerErrors,
    setCompilerErrors,
    lastCompilationResult,
    setLastCompilationResult,
    cliOutput,
    setCliOutput,
    compileMutation,
    handleCompile: () => {
      invalidatePendingStart();
      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,
      mutate: (...args) => {
        invalidatePendingStart();
        simulation.startMutation.mutate(...args);
      },
      mutateAsync: (...args) => {
        invalidatePendingStart();
        return simulation.startMutation.mutateAsync(...args);
      },
    },
    stopMutation: {
      ...simulation.stopMutation,
      mutate: (...args) => {
        invalidatePendingStart();
        simulation.stopMutation.mutate(...args);
      },
      mutateAsync: (...args) => {
        invalidatePendingStart();
        return simulation.stopMutation.mutateAsync(...args);
      },
    },
    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,
    invalidatePendingStart,
  };
}