Systems

Published Updated
Headless, singleton manager classes in the Aircada SDK decorated with @System to coordinate global state orchestration and background tasks.

While Operators represent modular visual or physical instances scattered across 3D meshes, Systems represent headless, singleton controllers running continuously in the background of the Aircada experience.

They have the same capabilities as Operators, but they have no Visual Studio presence (so their @Property fields are not visually exposed) and are instantiated exactly once to coordinate global application logic, analytical triggers, or complex multi-component rules.

Configuration Orchestrator System Pattern#

An example of a System managing global state and routing events.

Implementation of a hub orchestrator managing global state, applying rules, and communicating with spoke Operators.

ConfigOrchestrator.ts (typescript)
// src/systems/ConfigOrchestrator.ts

import {
	System, Context, Input, Output, Setup, Dispose,
	AircadaContext, AirEvent
} from "@aircada/spec";
import { Events, EventPayloads, PedestalColor, SpinState } from "../registry/registry.generated";

@System({
	name: "Configuration Orchestrator",
	type: "config_orchestrator"
})
export class ConfigOrchestrator {

	// 1. Context Fencing
	@Context()
	air!: AircadaContext;

	// 2. The Master State (The single source of truth)
	private currentColor: PedestalColor = "BLUE";
	private currentSpin: SpinState = "IDLE";

	// 3. Execution Commands (Outputs sent to the Spokes)
	@Output({ name: "Apply Color", emits: Events.APPLY_COLOR })
	onApplyColor = new AirEvent<EventPayloads[typeof Events.APPLY_COLOR]>();

	@Output({ name: "Apply Spin State", emits: Events.APPLY_SPIN_STATE })
	onApplySpinState = new AirEvent<EventPayloads[typeof Events.APPLY_SPIN_STATE]>();

	// 4. Facts (Outcomes sent back to the UI)
	@Output({ name: "Validation Failed", emits: Events.VALIDATION_FAILED })
	onValidationFailed = new AirEvent<EventPayloads[typeof Events.VALIDATION_FAILED]>();

	// Memory management closures
	private unsubValidation?: () => void;

	@Setup()
	setup() {
		console.log("ConfigOrchestrator initialized. Master state set to defaults.");

		// Example of capturing local events for logging and memory safety
		this.unsubValidation = this.onValidationFailed.addListener((payload) => {
			console.warn(`[Hub Validation Error]: ${payload.reason}`);
		});

		// Initialize the scene to the default state
		// We defer slightly to ensure all Spoke Operators have mounted
		setTimeout(() => {
			this.onApplyColor.invoke({ color: this.currentColor });
			this.onApplySpinState.invoke({ state: this.currentSpin });
		}, 100);
	}

	// 5. Hub Logic: Intercept UI Requests

	@Input({ name: "Handle Color Request", onEvent: Events.REQUEST_COLOR_CHANGE })
	handleColorRequest(payload: EventPayloads[typeof Events.REQUEST_COLOR_CHANGE]) {
		this.currentColor = payload.color;

		// Enforce implicit rule: If we turn red, we must stop spinning
		if (this.currentColor === "RED" && this.currentSpin === "SPINNING") {
			this.currentSpin = "IDLE";
			this.onApplySpinState.invoke({ state: "IDLE" });
		}

		// Fire the validated execution command
		this.onApplyColor.invoke({ color: this.currentColor });
	}

	@Input({ name: "Handle Spin Request", onEvent: Events.REQUEST_SPIN_TOGGLE })
	handleSpinRequest(payload: EventPayloads[typeof Events.REQUEST_SPIN_TOGGLE]) {
		// Enforce explicit business rule: Red cannot spin.
		if (this.currentColor === "RED" && payload.state === "SPINNING") {
			// Reject the command and inform the UI
			this.onValidationFailed.invoke({ reason: "The pedestal cannot spin while it is RED." });
			return;
		}

		// State is valid. Update master state and execute.
		this.currentSpin = payload.state;
		this.onApplySpinState.invoke({ state: this.currentSpin });
	}

	@Dispose()
	dispose() {
		if (this.unsubValidation) {
			this.unsubValidation();
		}
	}
}
System class orchestrating pedestal color and spin states based on requests.

Systems vs Operators Architecture and Rules#

Systems have the same capabilities as Operators but are singleton-managed by the backend and have no Studio UI presence.

A system class can implement all the same logic and use the same decorators that an operator can, but its instantiation and lifecycle are completely managed by the backend, in contrast to operators that can be instantiated numerous times.

And unlike operators, @Property declarations cannot be viewed or controlled in the docs.studio environment.

Core Architectural Rule: @System classes should be prioritized over @Operator classes for all scene and product modifications, unless the operator class needs to be reused or recreated at runtime. Single-instance scene manipulations belong in a centralized @System manager rather than multiple fragmented operators.

  • Singleton Lifecycle: Automatically managed by the backend as a headless singleton.
  • Prioritize @System over @Operator: @System classes should be prioritized over @Operator classes for all scene and product modifications, unless the operator class needs to be reused or recreated at runtime.
  • No Studio UI: @Property declarations are not visible in the Visual Studio.

Setup Lifecycle Stages and Startup Handshakes#

How Aircada schedules multi-stage setup in System components, automatically hydrates option state, avoids barrel re-export duplicates, and coordinates secondary systems via event handshakes.

Headless @System controllers support lifecycle stages, async scheduling, and topological dependency sorting mechanisms.

1. The Anti-Barrel Rule (Preventing Duplicate System Registration)

CRITICAL ARCHITECTURAL RULE: Never create barrel re-export files (such as src/System.ts or src/systems/index.ts) for @System or @Operator classes.

  • Filesystem AST Discovery: The Aircada engine discovers systems and operators by scanning the project filesystem for class decorators (@System(), @Operator()) rather than relying on entrypoint imports.
  • Duplicate Instantiation Bug: If a system is re-exported from a barrel file, the engine encounters the class symbol multiple times, causing duplicate event listeners, redundant 3D scene construction, and broken state synchronization.
  • Solution: Keep each system in its own dedicated file inside src/systems/ (e.g. src/systems/SetupManager.ts, src/systems/WatchManager.ts) with NO barrel export files.

2. Automatic Store Options Hydration on Boot

On application boot, the Aircada SDK client runtime automatically hydrates the useAirStore options namespaces using InitialOptionState (generated in src/registry/options.generated.ts) prior to invoking @Setup() hooks or rendering React UI overlays.

  • Systems and React components can safely read initial option values from the store immediately without requiring manual store.patch({ options: ... }) calls in setup methods.
  • Automatic hydration prevents stale ID collisions and eliminating 1-frame unstyled rendering flashes.

3. The SetupManager Pattern (Recommended for Multi-System Projects)

To prevent startup race conditions, repeated 3D scene rebuilds, and fragmented initialization logic, multi-system configurator projects should centralize setup coordination in a primary SetupManager @System.

  • Multi-Stage Coordination: SetupManager executes async methods across the 4 boot stages (bootstrap -> initialize -> finalize -> runtime) awaited sequentially by the Aircada SDK engine.
  • Event Handshake Orchestration: Rather than having multiple systems declare independent @Setup hooks that compete or race against each other, SetupManager coordinates initialization by dispatching setup handshake events (e.g. SETUP_EVENT_INIT_STORE, SETUP_EVENT_BUILD_3D, SETUP_EVENT_EXPERIENCE_READY).
  • Secondary System Asynchronous Initialization: Secondary systems (such as CommercialPricingSystem, 3DSceneManager, SizingCalculatorSystem) listen for these setup events via @Input({ onEvent: ... }) to asynchronously initialize their subsystems (e.g. instantiating ProductPurchasers, building scene geometry, or seeding store defaults).

4. Stage Scheduling and Coordination

Systems declare @Setup({ stage: 'bootstrap' | 'initialize' | 'finalize' | 'runtime' }) methods:

  1. bootstrap: Foundation setup and programmatic instantiation of child operators or service connections.
  1. initialize: Seeding initial store state, option defaults, and 3D scene assembly.
  1. finalize: Camera framing, shader pre-warming, and post-processing attachment.
  1. runtime: Final experience handoff, emitting SETUP_EVENT_EXPERIENCE_READY to unlock UI customizer drawers and trigger async purchasing subsystem readiness.

5. Topological Constraints Across Systems

Systems can declare before and after execution dependencies relative to other Systems or Operators (e.g. @Setup({ stage: 'initialize', after: 'StoreBootSystem' })), establishing a deterministic startup sequence.

SetupManager.ts (typescript)
import { System, Context, Setup, AircadaContext } from '@aircada/spec';
import {
  SETUP_EVENT_INIT_STORE,
  SETUP_EVENT_STORE_READY,
  SETUP_EVENT_BUILD_3D,
  SETUP_EVENT_3D_READY,
  SETUP_EVENT_EXPERIENCE_READY
} from '../schemas/ConfiguratorSchemas';

@System({
  name: 'Setup Manager',
  type: 'SETUP_MANAGER'
})
export class SetupManager {
  @Context()
  air!: AircadaContext;

  @Setup({ stage: 'bootstrap' })
  async onBootstrap() {
    console.log('âš¡ [SetupManager] Stage 1/4: Bootstrap foundation verification');
  }

  @Setup({ stage: 'initialize' })
  async onInitialize() {
    console.log('âš¡ [SetupManager] Stage 2/4: Initializing store and 3D scene');
    await this.dispatchAndWait(SETUP_EVENT_INIT_STORE, SETUP_EVENT_STORE_READY, 5000);
    await this.dispatchAndWait(SETUP_EVENT_BUILD_3D, SETUP_EVENT_3D_READY, 8000);
  }

  @Setup({ stage: 'finalize' })
  async onFinalize() {
    console.log('âš¡ [SetupManager] Stage 3/4: Finalizing camera framing and shaders');
  }

  @Setup({ stage: 'runtime' })
  async onRuntime() {
    console.log('âš¡ [SetupManager] Stage 4/4: Experience ready. Dispatched runtime handoff.');
    this.air.events.emit(SETUP_EVENT_EXPERIENCE_READY, { readyAt: Date.now() });
  }

  private dispatchAndWait(emitEvent: string, waitForEvent: string, timeoutMs = 5000): Promise<void> {
    return new Promise((resolve) => {
      const timer = setTimeout(() => {
        console.warn(`[SetupManager] Timeout waiting for ${waitForEvent}`);
        resolve();
      }, timeoutMs);

      const unsubscribe = this.air.events.on(waitForEvent, () => {
        clearTimeout(timer);
        unsubscribe();
        resolve();
      });

      this.air.events.emit(emitEvent);
    });
  }
}
A centralized SetupManager orchestrating 4-stage boot and secondary system event handshakes.
CommercialPricingSystem.ts (typescript)
import { System, Context, Input, AircadaContext, PurchaserPluginOperator } from '@aircada/spec';
import { ProductPurchasers } from '../registry/plugins.generated';
import { SETUP_EVENT_EXPERIENCE_READY, STORE_KEY_CALCULATED_PRICE } from '../schemas/ConfiguratorSchemas';

@System({
  name: 'Commercial Pricing System',
  type: 'COMMERCIAL_PRICING_SYSTEM'
})
export class CommercialPricingSystem {
  @Context()
  air!: AircadaContext;

  private purchaser: PurchaserPluginOperator | null = null;

  @Input({ onEvent: SETUP_EVENT_EXPERIENCE_READY })
  async onExperienceReady() {
    console.log('âš¡ [CommercialPricingSystem] Setup handshake received. Initializing purchaser...');
    if (ProductPurchasers && this.air.ecommerce) {
      this.purchaser = await (ProductPurchasers as any).MAIN_MODEL_TEST(this.air);
      this.purchaser?.price?.addListener?.((newPrice: string) => {
        this.air.store.patch({ [STORE_KEY_CALCULATED_PRICE]: parseFloat(newPrice) });
      });
    }
  }
}
A secondary system asynchronously initializing on the setup handshake event.

Programmatic Operator Creation in Systems#

Details how custom Systems can dynamically create, configure, and manage Operators programmatically at runtime.

In advanced orchestration scenarios, a headless @System can dynamically spawn, configure, and manage Operator instances at runtime rather than relying purely on static, designer-placed operators in the Studio scene.

This is accomplished using the this.air.operators.create("OPERATOR_TYPE", { properties }) API, exposing dynamic event listening and lifecycle delegation.

Lifecycle Stage Scheduling

Operators instantiated during a System's @Setup({ stage: 'bootstrap' }) hook are registered with the engine's loading manager in time to participate in all subsequent lifecycle phases. Once created, their @Setup hooks for initialize, finalize, and runtime stages will be automatically scheduled and executed in order by the engine alongside static operators.

Programmatically created operators function as headless, runtime-managed processors that can process inputs and emit signals, completely governed by the orchestrating System.

  • Dynamic Creation: Instantiate helper operators on-demand during system initialization or in response to events.
  • Lifecycle Delegation: The system must explicitly manage and clean up any programmatically spawned operators.
  • Property Configuration: Properties are passed dynamically as configuration options matching the operator's @Property keys.
UnderlineSystem.ts (typescript)
import {
    System, Context, Setup, Dispose,
    AircadaContext
} from "@aircada/spec";

@System({
    name: "Underline System",
    type: "underline_system"
})
export class UnderlineSystem {
    @Context()
    air!: AircadaContext;

    private boundsOperator!: any;

    @Setup()
    async setup() {
        console.log("Initializing UnderlineSystem...");

        // Programmatically spawn a helper operator at runtime
        this.boundsOperator = await this.air.operators.create("BOUNDS", {
            targetUnitId: "some-unit-id"
        });

        // Event subscription mapping for programmatically created operator signals
        if (this.boundsOperator && this.boundsOperator.onBoundsChanged) {
            this.boundsOperator.onBoundsChanged.addListener((bounds: any) => {
                console.log("Dynamic bounds update received in System:", bounds);
            });
        }
    }

    @Dispose()
    async dispose() {
        console.log("Disposing UnderlineSystem and programmatically created operators...");
        
        // CRITICAL: Clean up dynamically created operators to prevent runtime leaks
        if (this.boundsOperator) {
            await this.boundsOperator.dispose();
        }
    }
}
System dynamically spawning a BOUNDS operator at setup and disposing it on cleanup.