> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Managing State

> Start, stop, pause, and resume sandboxes to control their lifecycle. Learn how to manage sandbox state transitions, free resources when not in use, pause execution temporarily, and resume paused sandboxes. Essential for resource management and workflow control. Includes Python and JavaScript SDK examples and REST API endpoints.

Control the lifecycle of your sandboxes by starting, stopping, pausing, and resuming them. This allows you to manage resources efficiently and maintain state across sessions.

## Prerequisites

Before you begin, make sure you have:

* **Existing sandbox** - A sandbox that was created (see [Creating Sandboxes](/core-concepts/sandboxes/creating))
* **Sandbox object** - A `Sandbox` instance connected to your sandbox
* **Basic understanding** - Familiarity with sandbox states and lifecycle

## Sandbox States

Sandboxes can be in one of these states:

* **`running`** - Active and ready to execute code
* **`stopped`** - Shut down but can be restarted
* **`paused`** - Temporarily suspended, can be resumed
* **`creating`** - Currently being created

<Note>
  When you pause a sandbox, its state is preserved. When you resume it, everything continues from where it left off. Stopped sandboxes lose their runtime state but can be restarted.
</Note>

## Getting Current State

Check the current state of a sandbox:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")
    info = sandbox.get_info()

    print(f"Status: {info.status}")
    print(f"Sandbox ID: {info.sandbox_id}")
    ```

    **Expected Output:**

    ```
    Status: running
    Sandbox ID: 1763309903rt5vs4lm
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    const info = await sandbox.getInfo();

    console.log(`Status: ${info.status}`);
    console.log(`Sandbox ID: ${info.sandboxId}`);
    ```

    **Expected Output:**

    ```
    Status: running
    Sandbox ID: 1763309903rt5vs4lm
    ```
  </Tab>
</Tabs>

## Starting a Sandbox

Start a stopped sandbox:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    # Connect to a stopped sandbox
    sandbox = Sandbox.connect("sandbox_id")

    # Check current status
    info = sandbox.get_info()
    print(f"Current status: {info.status}")  # "stopped"

    # Start the sandbox
    sandbox.start()

    # Verify it's running
    info = sandbox.get_info()
    print(f"New status: {info.status}")  # "running"
    ```

    **Expected Output:**

    ```
    Current status: stopped
    New status: running
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    // Connect to a stopped sandbox
    const sandbox = await Sandbox.connect('sandbox_id');

    // Check current status
    let info = await sandbox.getInfo();
    console.log(`Current status: ${info.status}`);  // "stopped"

    // Start the sandbox
    await sandbox.start();

    // Verify it's running
    info = await sandbox.getInfo();
    console.log(`New status: ${info.status}`);  // "running"
    ```

    **Expected Output:**

    ```
    Current status: stopped
    New status: running
    ```
  </Tab>
</Tabs>

## Stopping a Sandbox

Stop a running sandbox (preserves filesystem but loses runtime state):

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Stop the sandbox
    sandbox.stop()

    # Verify it's stopped
    info = sandbox.get_info()
    print(f"Status: {info.status}")  # "stopped"

    # Can start it again later
    sandbox.start()
    ```

    **Expected Output:**

    ```
    Status: stopped
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Stop the sandbox
    await sandbox.stop();

    // Verify it's stopped
    let info = await sandbox.getInfo();
    console.log(`Status: ${info.status}`);  // "stopped"

    // Can start it again later
    await sandbox.start();
    ```

    **Expected Output:**

    ```
    Status: stopped
    ```
  </Tab>
</Tabs>

## Pausing a Sandbox

Pause a running sandbox (preserves full state including memory):

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set some state
    sandbox.run_code('x = 42', language="python")

    # Pause the sandbox
    sandbox.pause()

    # Verify it's paused
    info = sandbox.get_info()
    print(f"Status: {info.status}")  # "paused"
    ```

    **Expected Output:**

    ```
    Status: paused
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set some state
    await sandbox.runCode('x = 42', { language: 'python' });

    // Pause the sandbox
    await sandbox.pause();

    // Verify it's paused
    const info = await sandbox.getInfo();
    console.log(`Status: ${info.status}`);  // "paused"
    ```

    **Expected Output:**

    ```
    Status: paused
    ```
  </Tab>
</Tabs>

## Resuming a Sandbox

Resume a paused sandbox (restores full state):

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.connect("sandbox_id")  # Automatically resumes if paused

    # Or manually resume
    sandbox.resume()

    # Verify it's running
    info = sandbox.get_info()
    print(f"Status: {info.status}")  # "running"

    # State is preserved
    result = sandbox.run_code('print(x)', language="python")
    print(result.stdout)  # "42" - state preserved!
    ```

    **Expected Output:**

    ```
    Status: running
    42
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.connect('sandbox_id');  // Automatically resumes if paused

    // Or manually resume
    await sandbox.resume();

    // Verify it's running
    const info = await sandbox.getInfo();
    console.log(`Status: ${info.status}`);  // "running"

    // State is preserved
    const result = await sandbox.runCode('print(x)', { language: 'python' });
    console.log(result.stdout);  // "42" - state preserved!
    ```

    **Expected Output:**

    ```
    Status: running
    42
    ```
  </Tab>
</Tabs>

## Complete State Management Example

Here's a complete example showing all state operations:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    # Create sandbox
    sandbox = Sandbox.create(template="code-interpreter")
    print(f"Created: {sandbox.get_info().status}")  # "running"

    # Set some state
    sandbox.run_code('data = [1, 2, 3, 4, 5]', language="python")

    # Pause
    sandbox.pause()
    print(f"After pause: {sandbox.get_info().status}")  # "paused"

    # Resume (state preserved)
    sandbox.resume()
    print(f"After resume: {sandbox.get_info().status}")  # "running"

    # Verify state preserved
    result = sandbox.run_code('print(sum(data))', language="python")
    print(f"Sum: {result.stdout}")  # "15" - state preserved!

    # Stop
    sandbox.stop()
    print(f"After stop: {sandbox.get_info().status}")  # "stopped"

    # Start again (state lost)
    sandbox.start()
    result = sandbox.run_code('print(data)', language="python")
    print(f"Data: {result.stderr}")  # Error - state lost on stop
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    // Create sandbox
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    let info = await sandbox.getInfo();
    console.log(`Created: ${info.status}`);  // "running"

    // Set some state
    await sandbox.runCode('data = [1, 2, 3, 4, 5]', { language: 'python' });

    // Pause
    await sandbox.pause();
    info = await sandbox.getInfo();
    console.log(`After pause: ${info.status}`);  // "paused"

    // Resume (state preserved)
    await sandbox.resume();
    info = await sandbox.getInfo();
    console.log(`After resume: ${info.status}`);  // "running"

    // Verify state preserved
    let result = await sandbox.runCode('print(sum(data))', { language: 'python' });
    console.log(`Sum: ${result.stdout}`);  // "15" - state preserved!

    // Stop
    await sandbox.stop();
    info = await sandbox.getInfo();
    console.log(`After stop: ${info.status}`);  // "stopped"

    // Start again (state lost)
    await sandbox.start();
    result = await sandbox.runCode('print(data)', { language: 'python' });
    console.log(`Data: ${result.stderr}`);  // Error - state lost on stop
    ```
  </Tab>
</Tabs>

## State Transitions

Understanding state transitions helps you manage sandboxes effectively:

```
creating → running → paused → running
                ↓         ↓
             stopped → running
                ↓
            (deleted)
```

<CardGroup cols={2}>
  <Card title="Pause vs Stop" icon="pause">
    **Pause**: Preserves full state (memory, variables, running processes). Fast resume.
    **Stop**: Preserves filesystem only. Runtime state is lost. Requires full restart.
  </Card>

  <Card title="When to Use" icon="lightbulb">
    **Pause**: When you need to temporarily suspend work but keep everything in memory.
    **Stop**: When you want to free resources but keep files for later.
  </Card>
</CardGroup>

## Error Handling

Handle state transition errors:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox
    from hopx_ai.errors import APIError

    sandbox = Sandbox.create(template="code-interpreter")

    try:
        # Try to pause
        sandbox.pause()
    except APIError as e:
        print(f"Failed to pause: {e}")

    try:
        # Try to start (might already be running)
        sandbox.start()
    except APIError as e:
        print(f"Failed to start: {e}")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';
    import { APIError } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    try {
      // Try to pause
      await sandbox.pause();
    } catch (error) {
      if (error instanceof APIError) {
        console.error(`Failed to pause: ${error.message}`);
      }
    }

    try {
      // Try to start (might already be running)
      await sandbox.start();
    } catch (error) {
      if (error instanceof APIError) {
        console.error(`Failed to start: ${error.message}`);
      }
    }
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Use Pause for Temporary Suspension">
    Use `pause()` when you need to temporarily suspend work but want to preserve all state. Resume is fast and preserves everything.
  </Step>

  <Step title="2. Use Stop for Resource Management">
    Use `stop()` when you want to free resources but keep the filesystem. Files are preserved, but runtime state is lost.
  </Step>

  <Step title="3. Check Status Before Operations">
    Always check the sandbox status before performing operations to avoid errors.
  </Step>

  <Step title="4. Handle State Transitions Gracefully">
    Handle errors when transitioning states - a sandbox might already be in the desired state.
  </Step>

  <Step title="5. Clean Up When Done">
    Always call `kill()` when you're completely done with a sandbox to free resources.
  </Step>
</Steps>

## Implementation

* **SDK**: [sandbox.start()](/sdk/python/sandbox#start) - Python SDK method
* **[CLI](/cli/introduction)** - Command-line interface
* **SDK**: [sandbox.stop()](/sdk/python/sandbox#stop) - Python SDK method
* **SDK**: [sandbox.pause()](/sdk/python/sandbox#pause) - Python SDK method
* **SDK**: [sandbox.resume()](/sdk/python/sandbox#resume) - Python SDK method
* **API**: [POST /v1/sandboxes/:id/start](/api/control-plane/start-sandbox) - Control Plane API endpoint
* **API**: [POST /v1/sandboxes/:id/stop](/api/control-plane/stop-sandbox) - Control Plane API endpoint
* **API**: [POST /v1/sandboxes/:id/pause](/api/control-plane/pause-sandbox) - Control Plane API endpoint
* **API**: [POST /v1/sandboxes/:id/resume](/api/control-plane/resume-sandbox) - Control Plane API endpoint

## Related

* **[Creating Sandboxes](/core-concepts/sandboxes/creating)** - Create new sandboxes
* **[Connecting to Sandboxes](/core-concepts/sandboxes/connecting)** - Connect to existing sandboxes
* **[Timeout Management](/core-concepts/sandboxes/timeout)** - Set sandbox timeouts

## Next Steps

* Learn about [Timeout Management](/core-concepts/sandboxes/timeout) to control sandbox lifetime
* Review [Creating Sandboxes](/core-concepts/sandboxes/creating) for creating new sandboxes
* Explore [Listing Sandboxes](/core-concepts/sandboxes/listing) to find sandboxes by status
