All files / server/services/sandbox execution-manager.ts

71.76% Statements 216/301
54.59% Branches 95/174
80% Functions 32/40
72.82% Lines 209/287

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 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818        14x                                     14x 14x 14x 14x 14x 14x     14x                                                                                                                                                                                             69x 69x                                     69x 69x 69x 69x 69x 69x 69x 69x       41x             45x 45x     45x 45x 1x 1x       44x     44x                                     44x 44x     44x 44x 44x 45x     45x     45x       16x   16x                               16x 16x 16x 31x 31x 12x   19x 31x       45x 45x   45x   45x 44x   44x           44x     44x   8x 8x 8x 3x   8x 8x   8x 8x                           44x   44x 44x   44x 44x     44x   44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x                   44x 44x 44x 44x                       41x   41x 41x     41x               32x 32x 32x 20x 20x     28x 28x                               44x 44x   44x   44x 3x   41x                           3x 3x   3x                     3x   3x 3x 3x 3x 3x 3x   3x                   3x           3x                 3x 4x 4x       4x 4x     3x       3x 4x 4x                                                       41x   41x 41x 41x 20x   20x 6x 6x     14x 14x 14x 14x 14x   8x 8x 8x 8x 8x 8x 8x                         14x   14x 1x     14x   14x                                 14x 14x   14x 34x         14x 19x 19x 19x     14x 14x 14x   14x         14x                 14x   14x 13x 13x 13x 13x   13x 13x 13x       14x 12x 12x         14x 14x                         44x   4x                         4x 3x 1x 1x                           2x 2x                               19x   19x                 19x           19x 19x             18x 18x                                             16x 16x   16x 16x                       1x 1x   1x             5x 1x     4x 4x       4x                                                           88x         88x         88x               88x 5x     83x 83x             40x                  
// execution-manager.ts
// Orchestrates the complete simulation lifecycle (prepare, compile, run)
// Extracted from SandboxRunner to reduce runner complexity
 
import { randomUUID } from "node:crypto";
import { Logger } from "@shared/logger";
import { ProcessExecutor } from "../process-executor";
import type { IOPinRecord } from "@shared/schema";
import type { IProcessController } from "../process-controller";
import { ArduinoOutputParser as StderrParser } from "../arduino-output-parser";
import { RegistryManager } from "../registry-manager";
import { SimulationTimeoutManager } from "../simulation-timeout-manager";
import { DockerCommandBuilder } from "../docker-command-builder";
import { SketchFileBuilder } from "../sketch-file-builder";
import { LocalCompiler } from "../local-compiler";
import { PinStateBatcher, type PinStateBatch } from "../pin-state-batcher";
import { SerialOutputBatcher } from "../serial-output-batcher";
import type { RunSketchOptions } from "../run-sketch-types";
import { getCompileGatekeeper } from "../compile-gatekeeper";
import { DockerManager } from "./docker-manager";
import { StreamHandler } from "./stream-handler";
import { FilesystemHelper } from "./filesystem-helper";
 
export enum SimulationState {
  STOPPED = "stopped",
  STARTING = "starting",
  RUNNING = "running",
  PAUSED = "paused",
  ERROR = "error",
}
 
export const SANDBOX_CONFIG = {
  dockerImage: process.env.DOCKER_SANDBOX_IMAGE ?? "unosim-sandbox:latest",
  useDocker: true,
  maxMemoryMB: 256,
  maxCpuPercent: 50,
  maxExecutionTimeSec: 60,
  maxOutputBytes: 100 * 1024 * 1024,
  noNetwork: true,
  readOnlyFs: true,
  dropCapabilities: true,
};
 
// Type aliases for callbacks
// Output / error / pin state callbacks (from sandbox runner to consumers)
type OutputCallback = (line: string, isComplete?: boolean) => void;
type PinStateCallback = (pin: number, type: "mode" | "value" | "pwm", value: number) => void;
type ErrorCallback = (line: string) => void;
 
export interface TelemetryMetrics {
  timestamp: number;
  intendedPinChangesPerSecond: number;
  actualPinChangesPerSecond: number;
  droppedPinChangesPerSecond: number;
  batchesPerSecond: number;
  avgStatesPerBatch: number;
  serialOutputPerSecond: number;
  serialBytesPerSecond: number;
  serialBytesTotal: number;
  serialIntendedBytesPerSecond: number;
  serialDroppedBytesPerSecond: number;
}
 
type TelemetryCallback = (metrics: TelemetryMetrics) => void;
 
type ProcessMessage =
  | { type: "pinState"; data: { pin: number; stateType: "mode" | "value" | "pwm"; value: number } }
  | { type: "output"; data: { line: string; isComplete?: boolean } }
  | { type: "error"; data: { line: string } };
 
type ParsedStderrOutput = ReturnType<InstanceType<typeof StderrParser>["parseStderrLine"]>;
 
type DockerState = {
  isCompilePhase: { value: boolean };
  compileErrorBuffer: { value: string };
  compileSuccessSent: { value: boolean };
  totalOutputBytes: number;
  processStartTime: number | null;
  stderrFallbackBuffer: string;
  flushTimer: NodeJS.Timeout | null;
};
 
interface ExecutionCallbacks {
  onOutput: OutputCallback;
  onError: ErrorCallback;
  onPinState?: PinStateCallback;
}
 
type IORegistryCallback = (registry: IOPinRecord[], baudrate: number | undefined, reason?: string) => void;
 
// Nullable type aliases
type Nullable<T> = T | null;
 
export interface ExecutionState {
  outputBuffer: string;
  outputBufferIndex: number;
  isSendingOutput: boolean;
  totalOutputBytes: number;
  messageQueue: ProcessMessage[];
  pauseStartTime: Nullable<number>;
  totalPausedTime: number;
  isCompiling: boolean;
  currentSketchDir: Nullable<string>;
  currentRegistryFile: Nullable<string>;
  processStartTime: Nullable<number>;
  onOutputCallback: Nullable<OutputCallback>;
  pinStateCallback: Nullable<PinStateCallback>;
  errorCallback: Nullable<ErrorCallback>;
  telemetryCallback: Nullable<TelemetryCallback>;
  ioRegistryCallback?: IORegistryCallback;
  pinStateBatcher: Nullable<PinStateBatcher>;
  serialOutputBatcher: Nullable<SerialOutputBatcher>;
  backpressurePaused: boolean;
  baudrate: number;
  stderrFallbackBuffer: string;
  flushTimer: Nullable<NodeJS.Timeout>;
  state: SimulationState;
  processKilled: boolean;
  pendingCleanup: boolean;
  processController: IProcessController;
  currentContainerName?: string;
  dockerAvailable?: boolean;
  dockerImageBuilt?: boolean;
}
 
export class ExecutionManager {
  private readonly logger = new Logger("ExecutionManager");
  private readonly stderrParser = new StderrParser();
  private readonly registryManager: RegistryManager;
  private readonly timeoutManager: SimulationTimeoutManager;
  private readonly fileBuilder: SketchFileBuilder;
  private readonly localCompiler: LocalCompiler;
  private readonly dockerManager: DockerManager;
  private readonly streamHandler: StreamHandler;
  private readonly filesystemHelper: FilesystemHelper;
  private readonly processExecutor: ProcessExecutor;
 
  constructor(
    registryManager: RegistryManager,
    timeoutManager: SimulationTimeoutManager,
    fileBuilder: SketchFileBuilder,
    localCompiler: LocalCompiler,
    dockerManager: DockerManager,
    streamHandler: StreamHandler,
    filesystemHelper: FilesystemHelper,
  ) {
    this.registryManager = registryManager;
    this.timeoutManager = timeoutManager;
    this.fileBuilder = fileBuilder;
    this.localCompiler = localCompiler;
    this.dockerManager = dockerManager;
    this.streamHandler = streamHandler;
    this.filesystemHelper = filesystemHelper;
    this.processExecutor = new ProcessExecutor();
  }
 
  private static get compileGatekeeper() {
    return getCompileGatekeeper();
  }
 
  /**
   * Main execution entry point: prepare, compile, and run a sketch
   */
  async runSketch(options: RunSketchOptions, state: ExecutionState): Promise<void> {
    const opts = options;
    const { code, onOutput, onError, onExit, onCompileError, onPinState, timeoutSec, onIORegistry, onTelemetry, onPinStateBatch } = opts;
 
    // Transition to STARTING state
    const canStart = this.transitionTo(state, SimulationState.STARTING);
    if (!canStart) {
      this.logger.warn(`runSketch ignored - invalid state: ${state.state}`);
      return;
    }
 
    // Clear pending cleanup for a fresh run
    state.pendingCleanup = false;
 
    // Create and start PinStateBatcher
    state.pinStateBatcher = new PinStateBatcher({
      tickIntervalMs: 50,
      onBatch: (batch: PinStateBatch) => {
        if (state.messageQueue && this.registryManager.isWaiting()) {
          for (const s of batch.states) {
            state.messageQueue.push({
              type: "pinState",
              data: { pin: s.pin, stateType: s.stateType, value: s.value },
            });
          }
        } else if (onPinStateBatch) {
          onPinStateBatch(batch);
        } else if (onPinState) {
          for (const s of batch.states) {
            onPinState(s.pin, s.stateType, s.value);
          }
        }
      },
    });
    state.pinStateBatcher.start();
    this.registryManager.setPinStateBatcher(state.pinStateBatcher);
 
    // Bind callbacks
    state.onOutputCallback = onOutput;
    state.errorCallback = onError;
    state.pinStateCallback = onPinState || null;
    state.telemetryCallback = onTelemetry || null;
 
    // Initialize run state
    this.initializeRunState(code, onOutput, onIORegistry, timeoutSec, state);
 
    // Create and start SerialOutputBatcher
    state.serialOutputBatcher = new SerialOutputBatcher({
      baudrate: state.baudrate,
      tickIntervalMs: 50,
      onChunk: (data: string, firstLineIncomplete?: boolean) => {
        Iif (typeof onOutput !== "function") return;
 
        Iif (state.backpressurePaused) {
          setTimeout(() => {
            if (
              state.backpressurePaused &&
              state.serialOutputBatcher &&
              !state.serialOutputBatcher.isOverloaded() &&
              state.state !== SimulationState.PAUSED &&
              state.processController.hasProcess()
            ) {
              this.logger.info("Backpressure relieved, sending SIGCONT");
              state.processController.kill("SIGCONT");
              state.backpressurePaused = false;
            }
          }, 0);
        }
 
        const endsWithNewline = data.endsWith("\n");
        const parts = data.split("\n");
        for (let i = 0; i < parts.length; i++) {
          const isLastPart = i === parts.length - 1;
          if (isLastPart && endsWithNewline) {
            break;
          }
          const isComplete = !isLastPart && !(i === 0 && firstLineIncomplete);
          onOutput(parts[i], isComplete);
        }
      },
    });
    state.serialOutputBatcher.start();
    this.registryManager.setSerialOutputBatcher(state.serialOutputBatcher);
 
    try {
      // Prepare environment
      const files = await this.prepareEnvironment(code, state);
      state.processKilled = false;
 
      Iif (state.pendingCleanup || state.processKilled || state.state === SimulationState.STOPPED) {
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
        return;
      }
 
      // Create wrapped callbacks
      const wrapped = this.createWrappedCallbacks(onOutput, onError, onPinState, state);
 
      // Setup and run simulation
      await this.setupSimulationProcess(files, wrapped, opts, state);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      this.logger.error(`Kompilierfehler oder Timeout: ${errorMessage}`);
      if (onCompileError) {
        onCompileError(errorMessage);
      }
      Eif (onExit) {
        onExit(-1);
      }
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
    }
  }
 
  /**
   * Initialize run state for a new execution
   */
  private initializeRunState(
    code: string,
    onOutput: (line: string, isComplete?: boolean) => void,
    onIORegistry?: (registry: IOPinRecord[], baudrate: number | undefined, reason?: string) => void,
    timeoutSec?: number,
    state?: ExecutionState,
  ): void {
    Iif (!state) return;
 
    const baudMatch = /Serial\s*\.\s*begin\s*\(\s*(\d+)\s*\)/.exec(code);
    state.baudrate = baudMatch ? Number.parseInt(baudMatch[1]) : 9600;
 
    const executionTimeout = timeoutSec ?? SANDBOX_CONFIG.maxExecutionTimeSec;
    this.logger.info(
      `🕐 runSketch called with timeoutSec=${timeoutSec}, using executionTimeout=${executionTimeout}s`,
    );
    this.logger.info(`Parsed baudrate: ${state.baudrate}`);
 
    state.pauseStartTime = null;
    state.totalPausedTime = 0;
    this.registryManager.reset();
    this.registryManager.setBaudrate(state.baudrate);
    this.registryManager.enableWaitMode(5000); // Original 5s timeout
    state.messageQueue = [];
    state.outputBuffer = "";
    state.outputBufferIndex = 0;
    state.isSendingOutput = false;
    state.totalOutputBytes = 0;
    state.onOutputCallback = onOutput;
    state.ioRegistryCallback = onIORegistry;
  }
 
  /**
   * Prepare environment: write sketch files
   */
  private async prepareEnvironment(
    code: string,
    state: ExecutionState,
  ): Promise<{ sketchDir: string; sketchFile: string; exeFile: string }> {
    const sketchId = randomUUID();
    const files = await this.fileBuilder.build(code, sketchId);
    state.currentSketchDir = files.sketchDir;
    return files;
  }
 
  /**
   * Perform compilation (local path only; Docker handles internally)
   */
  private async performCompilation(
    sketchFile: string,
    exeFile: string,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    const WAIT_TIMEOUT_MS = 30000;
    let release: () => void;
    try {
      release = await Promise.race([
        ExecutionManager.compileGatekeeper.acquireHighPriority(),
        new Promise<never>((_, reject) =>
          setTimeout(() => reject(new Error("compile-gatekeeper timeout")), WAIT_TIMEOUT_MS),
        ),
      ]);
    } catch (err) {
      this.logger.error(`Gatekeeper wait failed: ${err instanceof Error ? err.message : String(err)}`);
      this.transitionTo(state, SimulationState.ERROR);
      throw err;
    }
    try {
      Eif (state.processController && this.localCompiler) {
        await this.localCompiler.compile(sketchFile, exeFile);
        if (opts.onCompileSuccess) opts.onCompileSuccess();
        await this.localCompiler.makeExecutable(exeFile);
      }
    } finally {
      try {
        release();
      } catch {
        // should never happen
      }
    }
  }
 
  /**
   * Setup simulation process: compile and spawn
   */
  private async setupSimulationProcess(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    const { timeoutSec } = opts;
    const executionTimeout = timeoutSec ?? SANDBOX_CONFIG.maxExecutionTimeSec;
 
    const useDocker = !!(state.dockerAvailable && state.dockerImageBuilt);
 
    if (useDocker) {
      await this.runDocker(files, callbacks, opts, state, executionTimeout);
    } else {
      await this.runLocal(files, callbacks, opts, state, executionTimeout);
    }
  }
 
  /**
   * Run in Docker container
   */
  private async runDocker(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
    executionTimeout: number,
  ): Promise<void> {
    const containerName = `unosim-sandbox-${randomUUID()}`;
    state.currentContainerName = containerName;
 
    const dockerArgs = DockerCommandBuilder.buildSecureRunCommand({
      sketchDir: files.sketchDir,
      memoryMB: SANDBOX_CONFIG.maxMemoryMB,
      cpuLimit: "0.5",
      pidsLimit: 50,
      imageName: SANDBOX_CONFIG.dockerImage,
      command: DockerCommandBuilder.buildCompileAndRunCommand(),
      containerName,
      arduinoCacheDir: process.env.ARDUINO_CACHE_DIR,
    });
 
    const { onCompileError, onCompileSuccess, onExit } = opts;
 
    try {
      state.processController.clearListeners();
      await state.processController.spawn("docker", dockerArgs);
      this.logger.info("🚀 Docker: Compile + Run in single container");
      state.processStartTime = Date.now();
      this.transitionTo(state, SimulationState.RUNNING);
 
      const dockerState: DockerState = {
        isCompilePhase: { value: true },
        compileErrorBuffer: { value: "" },
        compileSuccessSent: { value: false },
        totalOutputBytes: state.totalOutputBytes,
        processStartTime: state.processStartTime,
        stderrFallbackBuffer: state.stderrFallbackBuffer,
        flushTimer: state.flushTimer,
      };
 
      const dockerCallbacks = {
        onOutput: callbacks.onOutput,
        onPinState: callbacks.onPinState ?? (() => {}),
        onError: callbacks.onError,
      };
 
      state.processController.onError((err) => {
        this.logger.error(`Docker process error: ${err.message}`);
        callbacks.onError(`Docker process failed: ${err.message}`);
      });
 
      // Single close handler: state transition + cleanup.
      // Note: compile callbacks, batchers, and onExit are handled exclusively
      // by dockerManager.setupDockerHandlers → handleDockerExit to avoid
      // double invocation (which previously caused a double "stopped" event).
      state.processController.onClose((_code) => {
        this.transitionTo(state, SimulationState.STOPPED);
        Iif (state.flushTimer) {
          clearTimeout(state.flushTimer);
          state.flushTimer = null;
        }
        void this.cleanupDockerContainer(state.currentContainerName);
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      });
 
      this.dockerManager.setupDockerHandlers(
        dockerCallbacks,
        dockerState,
        {
          flushBatchers: () => this.flushBatchers(state),
          flushMessageQueue: () => this.flushMessageQueue(state),
          getProcessKilled: () => state.processKilled,
          executionTimeout,
        },
        {
          onCompileError,
          onCompileSuccess,
          onExit,
        },
      );
    } catch (err) {
      this.logger.error(`Docker process spawn failed: ${err instanceof Error ? err.message : String(err)}`);
      this.transitionTo(state, SimulationState.STOPPED);
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      throw err;
    }
  }
 
  /**
   * Run locally (without Docker)
   */
  private async runLocal(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
    executionTimeout: number,
  ): Promise<void> {
    const { onCompileError, onExit } = opts;
 
    try {
      state.isCompiling = true;
      await this.performCompilation(files.sketchFile, files.exeFile, opts, state);
      state.isCompiling = false;
 
      if (state.pendingCleanup || state.processKilled || state.state === SimulationState.STOPPED) {
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
        return;
      }
 
      state.processController.clearListeners();
      await state.processController.spawn(files.exeFile);
      state.processStartTime = Date.now();
      this.transitionTo(state, SimulationState.RUNNING);
      this.setupLocalHandlers(callbacks, onExit, executionTimeout, state);
    } catch (err) {
      state.isCompiling = false;
      if (onCompileError) onCompileError(err instanceof Error ? err.message : String(err));
      Eif (onExit) onExit(-1);
      this.transitionTo(state, SimulationState.STOPPED);
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      throw err;
    }
  }
 
  /**
   * Setup event handlers for local process
   */
  private setupLocalHandlers(
    callbacks: ExecutionCallbacks,
    onExit?: (code: number | null) => void,
    executionTimeout?: number,
    state?: ExecutionState,
  ): void {
    Iif (!state) return;
 
    const handleTimeout = () => {
      this.handleExecutionTimeout(executionTimeout, state, callbacks);
    };
 
    this.timeoutManager.schedule(executionTimeout && executionTimeout > 0 ? executionTimeout * 1000 : null, handleTimeout);
 
    state.processController.onStdout((data) => {
      const str = data.toString();
      state.totalOutputBytes += str.length;
      if (state.totalOutputBytes > SANDBOX_CONFIG.maxOutputBytes) {
        state.processController.kill("SIGKILL"); // Trigger stop
        callbacks.onError("Output size limit exceeded");
        return;
      }
 
      const lines = str.split(/\r?\n/);
      lines.forEach((line) => {
        if (!line) return;
        const parsed = this.stderrParser.parseStderrLine(line, state.processStartTime);
        this.delegateParsedLineToStreamHandler(parsed, callbacks.onPinState, callbacks.onOutput, callbacks.onError, state);
      });
    });
 
    const useFallbackParser = !state.processController.supportsStderrLineStreaming();
    state.stderrFallbackBuffer = "";
 
    state.processController.onStderr((data) => {
      Iif (useFallbackParser) {
        this.handleStderrFallbackData(data, state, callbacks);
      }
    });
 
    state.processController.onStderrLine((line) => {
      Iif (line.length === 0) return;
      const parsed = this.stderrParser.parseStderrLine(line, state.processStartTime);
      this.delegateParsedLineToStreamHandler(parsed, callbacks.onPinState, callbacks.onOutput, callbacks.onError, state);
    });
 
    state.processController.onClose((code) => {
      const wasRunning = state.state === SimulationState.RUNNING;
      this.transitionTo(state, SimulationState.STOPPED);
 
      Iif (state.flushTimer) {
        clearTimeout(state.flushTimer);
        state.flushTimer = null;
      }
 
      Iif (state.stderrFallbackBuffer) {
        const buffered = state.stderrFallbackBuffer;
        state.stderrFallbackBuffer = "";
        if (buffered.trim()) {
          const parsed = this.stderrParser.parseStderrLine(buffered, state.processStartTime);
          this.delegateParsedLineToStreamHandler(parsed, callbacks.onPinState, callbacks.onOutput, callbacks.onError, state);
        }
      }
 
      this.flushMessageQueue(state);
 
      if (wasRunning) {
        this.flushBatchers(state);
        Eif (state.serialOutputBatcher) {
          state.serialOutputBatcher.destroy();
          state.serialOutputBatcher = null;
        }
        Eif (state.pinStateBatcher) {
          state.pinStateBatcher.destroy();
          state.pinStateBatcher = null;
        }
      }
 
      if (state.ioRegistryCallback) {
        const finalRegistry = this.registryManager.getRegistry();
        Iif (finalRegistry.length > 0) {
          state.ioRegistryCallback([...finalRegistry], state.baudrate, "process-exit");
        }
      }
 
      if (!state.processKilled && onExit) onExit(code);
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
    });
  }
 
  /**
   * Create wrapped callbacks for message queuing
   */
  private createWrappedCallbacks(
    onOutput: OutputCallback,
    onError: ErrorCallback,
    onPinState?: PinStateCallback,
    state?: ExecutionState,
  ) {
    return {
      onOutput: (line: string, isComplete?: boolean) => {
        Iif (typeof line === "string" && line.startsWith("[[SIM_TELEMETRY:") && line.endsWith("]]")) {
          try {
            const jsonStr = line.slice("[[SIM_TELEMETRY:".length, -2);
            const metrics = JSON.parse(jsonStr);
            if (state?.telemetryCallback) {
              state.telemetryCallback(metrics);
            }
            return;
          } catch (err) {
            this.logger.warn(`Failed to parse telemetry marker: ${err}`);
          }
        }
 
        if (state?.serialOutputBatcher) {
          state.serialOutputBatcher.enqueue(line);
        E} else if (onOutput && state?.processKilled === false) {
          onOutput(line, isComplete);
        }
      },
      onPinState: (pin: number, stateType: "mode" | "value" | "pwm", value: number) => {
        if (state && this.registryManager.isWaiting()) {
          state.messageQueue.push({
            type: "pinState",
            data: { pin, stateType, value },
          });
        } else if (onPinState) {
          onPinState(pin, stateType, value);
        }
      },
      onError: (line: string) => {
        Eif (onError) {
          onError(line);
        }
      },
    };
  }
 
  /**
   * Delegate parsed line to StreamHandler
   */
  private delegateParsedLineToStreamHandler(
    parsed: ParsedStderrOutput,
    onPinState?: (pin: number, type: "mode" | "value" | "pwm", value: number) => void,
    onOutput?: (line: string, isComplete?: boolean) => void,
    onError?: (line: string) => void,
    state?: ExecutionState,
  ): void {
    Iif (!state) return;
 
    const streamState = {
      pinStateBatcher: state.pinStateBatcher,
      serialOutputBatcher: state.serialOutputBatcher,
      backpressurePaused: state.backpressurePaused,
      isPaused: state.state === SimulationState.PAUSED,
      baudrate: state.baudrate,
      registryManager: this.registryManager,
    };
 
    const callbacks = {
      onPinState,
      onOutput,
      onError,
    };
 
    this.streamHandler.handleParsedLine(parsed, streamState, callbacks);
    state.backpressurePaused = streamState.backpressurePaused;
  }
 
  /**
   * Flush message queue
   */
  flushMessageQueue(state: ExecutionState): void {
    Eif (state.messageQueue.length === 0) {
      return;
    }
 
    this.logger.debug(`[Registry] Flushing ${state.messageQueue.length} queued messages`);
 
    const queue = state.messageQueue;
    state.messageQueue = [];
 
    for (const msg of queue) {
      if (msg.type === "pinState" && state.pinStateCallback) {
        state.pinStateCallback(msg.data.pin, msg.data.stateType, msg.data.value);
      } else if (msg.type === "output" && state.onOutputCallback) {
        state.onOutputCallback(msg.data.line, msg.data.isComplete);
      } else if (msg.type === "error" && state.errorCallback) {
        state.errorCallback(msg.data.line);
      }
    }
  }
 
  /**
   * Flush batchers
   */
  private flushBatchers(state: ExecutionState): void {
    Eif (state.serialOutputBatcher) {
      state.serialOutputBatcher.stop();
    }
    Eif (state.pinStateBatcher) {
      state.pinStateBatcher.stop();
    }
  }
 
  /**
   * Handle execution timeout by killing process and notifying output
   */
  private handleExecutionTimeout(
    executionTimeout: number | undefined,
    state: ExecutionState,
    callbacks: ExecutionCallbacks,
  ): void {
    state.processController.kill("SIGKILL");
    callbacks.onOutput(`--- Simulation timeout (${executionTimeout}s) ---`, true);
 
    void this.cleanupDockerContainer(state.currentContainerName);
  }
 
  /**
   * Ensure no container remains after Docker process exit or timeout.
   */
  private async cleanupDockerContainer(containerName?: string): Promise<void> {
    if (!containerName) {
      return;
    }
 
    try {
      await this.processExecutor.execute("docker", ["rm", "-f", containerName], {
        timeout: 5000,
        stdio: "pipe",
      });
      this.logger.info(`Docker container cleanup: ${containerName}`);
    } catch (error) {
      this.logger.debug(`Docker cleanup failed for ${containerName}: ${error}`);
    }
  }
 
  /**
   * Process buffered stderr data in fallback mode
   */
  private handleStderrFallbackData(
    data: Buffer,
    state: ExecutionState,
    callbacks: ExecutionCallbacks,
  ): void {
    state.stderrFallbackBuffer += data.toString();
    const lines = state.stderrFallbackBuffer.split(/\r?\n/);
    state.stderrFallbackBuffer = lines.pop() || "";
 
    for (const line of lines) {
      if (!line) continue;
      const parsed = this.stderrParser.parseStderrLine(line, state.processStartTime);
      this.delegateParsedLineToStreamHandler(parsed, callbacks.onPinState, callbacks.onOutput, callbacks.onError, state);
    }
  }
 
  /**
   * State transition (delegated from runner)
   */
  private transitionTo(state: ExecutionState, newState: SimulationState): boolean {
    // Guard: no transition from ERROR
    Iif (state.state === SimulationState.ERROR) {
      return false;
    }
 
    // Guard: can't stop paused simulation
    Iif (newState === SimulationState.STOPPED && state.state === SimulationState.PAUSED) {
      return true; // Allow stop from paused
    }
 
    // Check valid transitions
    const validTransitions: Record<SimulationState, SimulationState[]> = {
      [SimulationState.STOPPED]: [SimulationState.STARTING],
      [SimulationState.STARTING]: [SimulationState.STOPPED, SimulationState.RUNNING, SimulationState.ERROR],
      [SimulationState.RUNNING]: [SimulationState.PAUSED, SimulationState.STOPPED, SimulationState.ERROR],
      [SimulationState.PAUSED]: [SimulationState.RUNNING, SimulationState.STOPPED, SimulationState.ERROR],
      [SimulationState.ERROR]: [],
    };
 
    if (!validTransitions[state.state].includes(newState)) {
      return false;
    }
 
    state.state = newState;
    return true;
  }
 
  /**
   * Extract filesystem state for delegation
   */
  private extractFilesystemState(state: ExecutionState) {
    return {
      currentSketchDir: state.currentSketchDir,
      isCompiling: state.isCompiling,
      pendingCleanup: state.pendingCleanup,
      cleanupRetries: new Map(),
      currentRegistryFile: null,
    };
  }
}