Skip to content

controller

COMMAND_SUGGESTIONS module-attribute

Python
COMMAND_SUGGESTIONS = (
    "gen",
    "run",
    "seed ",
    "trial ",
    "watch",
    "record",
    "dojo",
    "stop",
    "help",
    "explain ",
    "generate",
    "quit",
    "runtime",
    "run until time ",
    "run until step ",
    "pause",
    "step ",
    "speed ",
)

Command names offered as completions by the terminal UI.

Outcome

Bases: StrEnum

How the most recent job ended.

ControllerStatus dataclass

Python
ControllerStatus(
    state: RunState,
    last_command: str,
    seed: int | None,
    trial_num: int,
    playback_speed: float,
    watch: bool,
    record: bool,
    last_duration: float | None,
    last_outcome: Outcome | None,
)

Snapshot of everything the terminal UI shows about the session.

LogEvent dataclass

Python
LogEvent(message: str, markup: bool = True)

A line for the log pane.

markup class-attribute instance-attribute

Python
markup: bool = True

Whether message is rich markup (the default) or plain text.

HelpEvent dataclass

Python
HelpEvent()

The user asked for the command list.

ExitEvent dataclass

Python
ExitEvent()

The user asked to close Reloaded.

ReloadedSession

Bases: Protocol

The slice of MojoReloaded the controller reads, writes, and calls.

ReloadedController dataclass

Python
ReloadedController(
    session: ReloadedSession,
    backend: ViewerBackend,
    *,
    watch_path: Path = cwd(),
    sink: EventSink = _discard,
)

Holds the state of a Reloaded session and turns commands into jobs, without knowing how either is displayed.

The terminal UI sends typed commands to submit and receives ControllerEvents through the sink. The sink is called from whichever thread produced the event (the caller of submit, the job thread, or the file watcher), so it must be thread safe.

session instance-attribute

Python
session: ReloadedSession

What the controller reads and changes, and whose generate_construct it runs.

backend instance-attribute

Python
backend: ViewerBackend

The viewer a generated model is shown in.

watch_path class-attribute instance-attribute

Python
watch_path: Path = field(default_factory=cwd, kw_only=True)

The directory watched for *.py changes when watching is on. Defaults to the current directory.

sink class-attribute instance-attribute

Python
sink: EventSink = field(default=_discard, kw_only=True)

Receives every ControllerEvent, from whichever thread produced it.

has_runtime property

Python
has_runtime: bool

Whether the session was given a runtime function, i.e. whether run has anything to run.

paused property

Python
paused: bool

Whether the run in progress is being held, which is what a viewer's pause button shows.

speed property

Python
speed: float

The playback speed, which is what a viewer's speed slider shows.

rerun

Python
rerun() -> None

Runs the last command again, which is what a viewer's Reset and Reload buttons ask for. A run in progress has to be stopped first.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def rerun(self) -> None:
    """Runs the last command again, which is what a viewer's Reset and Reload buttons ask for. A run in progress has to be stopped first."""
    with self._lock:
        idle = self._state is RunState.IDLE
        last_command = self._last_command
    if idle:
        self._start(last_command)
    else:
        self._log(
            "[dim]A run is in progress - type [bold]stop[/bold] to end it, then run it again.[/dim]"
        )

help_entries

Python
help_entries() -> list[tuple[str, str]]

Command and description pairs for the help screen.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def help_entries(self) -> list[tuple[str, str]]:
    """Command and description pairs for the help screen."""
    entries = [
        ("ENTER", "Repeat the last command, or step a paused run"),
        (_words("gen"), "Generate only"),
    ]
    if self.session.runtime:
        entries += [
            (
                f"{_words('run')} [X]",
                "Generate and run the runtime, at speed X if given (1.0 is real time, 0.5 is half). Carries a paused run on",
            ),
            (
                "run [X] until time <N>",
                "Run, then pause when the simulation time reaches N",
            ),
            (
                "run [X] until step <N>",
                "Run, then pause once N steps have been taken since the run began",
            ),
            (
                "speed <X>",
                "Set the playback speed, even during a run: a multiple of real time, 0 to step by hand with Enter, or inf for as fast as possible",
            ),
            (_words("pause"), "Hold the run in progress where it is"),
            (
                "step [N]",
                "Advance a run by N steps (1 if left out), pausing it first",
            ),
        ]
    entries += [
        ("seed <N>", "Set the seed (seed none clears it)"),
        ("trial <N>", "Set the trial number"),
        (_words("watch"), "Toggle reloading when *.py files change"),
        (
            _words("record"),
            "Toggle telemetry for mujoco-mojo dojo and video recording",
        ),
        ("dojo", "Print the command that opens the Dojo for this session"),
        ("explain <cmd>", "Say what a command would do, without running it"),
        ("<cmd>?", "The same, written as a question (a lone ? opens help)"),
        (_words("stop"), "Abort the run in progress"),
        (_words("help"), "Show this list"),
        ("quit", "Close Reloaded. To end a run, use stop"),
    ]
    return entries

describe

Python
describe(text: str) -> str

Says in one very short plain sentence what submitting text would do right now.

It only reads the session's state and changes nothing, so the terminal UI can call it on every keystroke.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def describe(self, text: str) -> str:
    """
    Says in one very short plain sentence what submitting `text` would do right now.

    It only reads the session's state and changes nothing, so the terminal UI can call it on every keystroke.
    """
    raw = text.strip().lower()
    status = self.status()

    target = self._explain_target(text)
    if target is not None:
        return (
            "Prints what Enter would do."
            if target == ""
            else "Prints what that would do."
        )

    # a command that takes no argument only matches on its own, so `gen now` is not `gen`
    command, _, arg = raw.partition(" ")
    command, arg = _canonical(command), arg.strip()

    if status.state is not RunState.IDLE:
        return self._describe_while_running(command, arg, status.state)

    match (command, arg):
        case ("", ""):
            if status.last_command == "gen":
                return "Repeats gen: generates only."
            if not self.has_runtime:
                return "Repeats run: generates only."
            if status.playback_speed == 0:
                return "Repeats run: steps on Enter."
            return f"Repeats run at {speed_label(status.playback_speed)}."
        case ("gen", ""):
            return "Generates the model only."
        case ("run", _):
            return self._describe_run(arg, status.playback_speed)
        case ("quit", ""):
            return "Closes Reloaded."
        case ("help", ""):
            return "Opens help."
        case ("stop", ""):
            return "Nothing is running to stop."
        case ("pause", ""):
            return "Nothing is running to pause."
        case ("step", _):
            return "Nothing is running to step."
        case ("speed", _):
            return self._describe_speed(arg, running=False)
        case ("watch", ""):
            return f"Turns auto reload {'off' if status.watch else 'on'}."
        case ("record", ""):
            return f"Turns recording {'off' if status.record else 'on'}."
        case ("dojo", ""):
            return "Prints the Dojo command."
        case ("seed", _):
            return self._describe_seed(arg)
        case ("trial", _):
            return self._describe_trial(arg)
        case _:
            return self._describe_unknown(raw)

start

Python
start() -> None

Routes the session's own messages to the sink and starts the file watcher if enabled.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def start(self) -> None:
    """Routes the session's own messages to the sink and starts the file watcher if enabled."""
    self.session.output_sink = self._on_session_output
    self.session.run_control.on_hold = self._on_hold
    if self.session.watch:
        self._start_watcher()
    self._log(
        "[bold green]MuJoCo Mojo Reloaded is live.[/bold green] Type [bold cyan]help[/bold cyan] for commands."
    )
    info = self.backend.connection_info()
    if info is not None:
        for line in connection_lines(info):
            self._log(line)
    self._emit_status()

shutdown

Python
shutdown() -> None

Stops the watcher and any run in progress. Safe to call more than once.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def shutdown(self) -> None:
    """Stops the watcher and any run in progress. Safe to call more than once."""
    self._stop_watcher()
    with self._lock:
        thread = self._job_thread
        busy = self._state is not RunState.IDLE
    if busy:
        self.session.stop_event.set()
        if thread is not None:
            thread.join(timeout=5)
    self.session.output_sink = None
    self.session.run_control.on_hold = None

submit

Python
submit(text: str) -> None

Handles one line typed by the user. An empty line repeats the last command.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def submit(self, text: str) -> None:
    """Handles one line typed by the user. An empty line repeats the last command."""
    raw = text.strip().lower()

    target = self._explain_target(text)
    if target is not None:
        self._explain(target)
        return

    # a command that takes no argument only matches on its own, so `gen now` is not `gen`
    command, _, arg = raw.partition(" ")
    command, arg = _canonical(command), arg.strip()

    if self.status().state is not RunState.IDLE:
        self._submit_while_running(command, arg)
        return

    match (command, arg):
        case ("quit", ""):
            self._emit(ExitEvent())
        case ("stop", ""):
            self._log("[dim]No run is currently in progress.[/dim]")
        case ("pause", ""):
            self.pause()
        case ("step", _):
            self.step(arg)
        case ("speed", _):
            self.set_speed(arg)
        case ("help", ""):
            self._emit(HelpEvent())
        case ("watch", ""):
            self.toggle_watch()
        case ("dojo", ""):
            self._show_dojo_hint()
        case ("record", ""):
            self.toggle_record()
        case ("seed", _) if arg:
            self.set_seed(arg)
        case ("trial", _) if arg:
            self.set_trial(arg)
        case ("", ""):
            with self._lock:
                last_command = self._last_command
            self._start(last_command)
        case ("gen", ""):
            self._start("gen")
        case ("run", _):
            self.run(arg)
        case _:
            self._log(
                f"[bold red]Unknown command:[/bold red] '{escape(raw)}'. Type [bold cyan]help[/bold cyan] for the command list."
            )

on_file_change

Python
on_file_change(count: int) -> None

Reloads with the last command when watched source files change, unless a run is in progress.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def on_file_change(self, count: int) -> None:
    """Reloads with the last command when watched source files change, unless a run is in progress."""
    plural = "s" if count != 1 else ""
    with self._lock:
        busy = self._state is not RunState.IDLE
        last_command = self._last_command

    if busy:
        self._log(
            f"[dim]{count} change{plural} detected, but a run is in "
            "progress - ignoring. Save again once it finishes to reload.[/dim]"
        )
        return

    self._log(
        f"[dim]{count} change{plural} detected, reloading with last command...[/dim]"
    )
    self._start_job(use_runtime=last_command != "gen")

run

Python
run(arg: str = '') -> None

Generates and runs the runtime, or carries a paused run on.

arg is an optional speed followed by an optional target, as in 0.5, until time 3, or 0.5 until step 500. The speed is set first, so run 0.5 is a run at half speed, and the run pauses itself when it reaches the target. For a run that is already going it only changes the speed or sets the target.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def run(self, arg: str = "") -> None:
    """
    Generates and runs the runtime, or carries a paused run on.

    `arg` is an optional speed followed by an optional target, as in `0.5`, `until time 3`, or `0.5 until step 500`. The speed is set first, so `run 0.5` is a run at half speed, and the run pauses itself when it reaches the target. For a run that is already going it only changes the speed or sets the target.
    """
    speed_text, target_words = self._split_run(arg)
    speed: float | None = None
    if speed_text is not None:
        speed = self._parse_speed(speed_text)
        if speed is None:
            return
    target: rt.RunTarget | None = None
    if target_words:
        target = self._read_target(target_words)
        if target is None:
            self._log(_INVALID_TARGET)
            return

    state = self.status().state
    if state is RunState.STOPPING:
        self._log(self._cannot(state, "run"))
        return
    if target is not None and state is not RunState.IDLE:
        if target.reached(*self.session.run_control.position):
            time_now, steps_now = self.session.run_control.position
            self._log(
                f"[bold red]Already at or past {target.label}[/bold red] "
                f"- the run is at time {time_now:g}, step {steps_now}."
            )
            return
    if speed is not None:
        self._apply_speed(speed)
    if target is not None:
        self._log(f"[dim]Will pause at {target.label}.[/dim]")

    match state:
        case RunState.IDLE:
            self._start("run", target)
        case RunState.PAUSED:
            if self.session.playback_speed == 0:
                self._log(f"[dim]{_MANUAL_HELP}[/dim]")
            else:
                self.session.run_control.run_until(target)
                self.resume()
        case RunState.RUNNING:
            self.session.run_control.run_until(target)
            if speed is None and target is None:
                self._log("[dim]The run is already going.[/dim]")
        case RunState.STOPPING:
            pass

set_seed

Python
set_seed(arg: str) -> None

Sets the seed from text. An empty string, none, or null clears it. Refused while a run is in progress.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def set_seed(self, arg: str) -> None:
    """Sets the seed from text. An empty string, `none`, or `null` clears it. Refused while a run is in progress."""
    if not self._idle_or_hint():
        return
    arg = arg.strip().lower()
    if arg in ("", "none", "null"):
        self.session.seed = None
        self._log("[dim]Seed cleared.[/dim]")
    else:
        try:
            self.session.seed = int(arg)
        except ValueError:
            self._log(
                "[bold red]Invalid seed.[/bold red] Use: seed <integer> or seed none"
            )
            return
        self._log(f"[dim]Seed set to {self.session.seed}.[/dim]")
    self._emit_status()

set_trial

Python
set_trial(arg: str) -> None

Sets the trial number from text. Refused while a run is in progress.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def set_trial(self, arg: str) -> None:
    """Sets the trial number from text. Refused while a run is in progress."""
    if not self._idle_or_hint():
        return
    try:
        self.session.trial_num = int(arg.strip())
    except ValueError:
        self._log("[bold red]Invalid trial number.[/bold red] Use: trial <integer>")
        return
    self._log(f"[dim]Trial number set to {self.session.trial_num}.[/dim]")
    self._emit_status()

set_speed

Python
set_speed(arg: str) -> None

Sets the playback speed, without starting a run. 1.0 is real time and 0 runs as fast as possible. A run in progress picks the new speed up at its next step.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def set_speed(self, arg: str) -> None:
    """Sets the playback speed, without starting a run. 1.0 is real time and 0 runs as fast as possible. A run in progress picks the new speed up at its next step."""
    speed = self._parse_speed(arg)
    if speed is not None:
        self._apply_speed(speed)

pause

Python
pause() -> None

Holds a run in progress at its next step.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def pause(self) -> None:
    """Holds a run in progress at its next step."""
    with self._lock:
        state = self._state
        if state is RunState.RUNNING:
            self._state = RunState.PAUSED
            self.session.run_control.pause()
    if state is RunState.RUNNING:
        self._log(f"[dim]Paused. {_HOLD_HELP}[/dim]")
        self._emit_status()
    else:
        self._log(self._cannot(state, "pause"))

resume

Python
resume() -> None

Lets a paused run carry on.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def resume(self) -> None:
    """Lets a paused run carry on."""
    with self._lock:
        state = self._state
        if state is RunState.PAUSED:
            self._state = RunState.RUNNING
            self.session.run_control.resume()
    if state is RunState.PAUSED:
        self._log("[dim]Resumed.[/dim]")
        self._emit_status()
    elif state is RunState.RUNNING:
        self._log("[dim]The run is not paused.[/dim]")
    else:
        self._log(self._cannot(state, "resume"))

toggle_pause

Python
toggle_pause() -> None

Pauses a run that is going and resumes one that is paused, which is what a single pause key does.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def toggle_pause(self) -> None:
    """Pauses a run that is going and resumes one that is paused, which is what a single pause key does."""
    if self.status().state is RunState.PAUSED:
        self.resume()
    else:
        self.pause()

step

Python
step(arg: str = '') -> None

Advances a run in progress by arg steps, or by one if it is empty, and leaves it paused. A run that is going is paused first.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def step(self, arg: str = "") -> None:
    """Advances a run in progress by `arg` steps, or by one if it is empty, and leaves it paused. A run that is going is paused first."""
    try:
        count = int(arg.strip() or 1)
    except ValueError:
        count = 0
    if count < 1:
        self._log(
            "[bold red]Invalid step count.[/bold red] Use: step or step <whole number>"
        )
        return
    with self._lock:
        state = self._state
        if state in (RunState.RUNNING, RunState.PAUSED):
            self._state = RunState.PAUSED
            self.session.run_control.step(count)
    if state in (RunState.RUNNING, RunState.PAUSED):
        self._log(f"[dim]Stepping {count} step{'s' if count != 1 else ''}.[/dim]")
        if state is RunState.RUNNING:
            self._emit_status()
    else:
        self._log(self._cannot(state, "step"))

toggle_record

Python
toggle_record() -> None

Turns telemetry recording on or off. Refused while a run is in progress.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def toggle_record(self) -> None:
    """Turns telemetry recording on or off. Refused while a run is in progress."""
    if not self._idle_or_hint():
        return
    self.session.record = not self.session.record
    if self.session.record:
        self._log(
            "[dim]Telemetry recording enabled - "
            "the next reload will be visible in `mujoco-mojo dojo`.[/dim]"
        )
    else:
        self._log("[dim]Telemetry recording disabled[/dim]")
    self._emit_status()

toggle_watch

Python
toggle_watch() -> None

Turns reloading on file changes on or off. Refused while a run is in progress.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def toggle_watch(self) -> None:
    """Turns reloading on file changes on or off. Refused while a run is in progress."""
    if not self._idle_or_hint():
        return
    self.session.watch = not self.session.watch
    if self.session.watch:
        self._start_watcher()
        self._log("[dim]Auto-watch enabled[/dim]")
    else:
        self._stop_watcher()
        self._log("[dim]Auto-watch disabled[/dim]")
    self._emit_status()

speed_label

Python
speed_label(speed: float) -> str

A speed as it is written in the status bar and the log: manual for 0, which steps only on Enter, inf for as fast as the machine goes, and otherwise a multiple of real time such as 0.5x.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def speed_label(speed: float) -> str:
    """A speed as it is written in the status bar and the log: `manual` for 0, which steps only on Enter, `inf` for as fast as the machine goes, and otherwise a multiple of real time such as `0.5x`."""
    if speed == 0:
        return "manual"
    if math.isinf(speed):
        return "inf"
    return f"{speed:g}x"

connection_lines

Python
connection_lines(info: ConnectionInfo) -> list[str]

How to reach a browser viewer, as rich markup lines for the log: where to open it, how to forward its port from another machine, and the standing warning.

Source code in src/mujoco_mojo/utils/layers/reloaded/controller.py
Python
def connection_lines(info: ConnectionInfo) -> list[str]:
    """How to reach a browser viewer, as rich markup lines for the log: where to open it, how to forward its port from another machine, and the standing warning."""
    lines = [
        f"Open [bold underline]{escape(info.url)}[/bold underline] in a browser to see the model."
    ]
    if info.tunnel_command is not None:
        lines.append(
            f"From your computer, forward the port first: [bold]{escape(info.tunnel_command)}[/bold]"
        )
    if info.warning is not None:
        lines.append(f"[yellow]{escape(info.warning)}[/yellow]")
    return lines