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

# @enclave-vm/react

> React hooks and components for the EnclaveJS streaming runtime

# @enclave-vm/react

React hooks and components for building interactive code execution UIs with the EnclaveJS streaming runtime.

## Installation

```bash theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
npm install @enclave-vm/react
```

**Peer Dependencies:**

* `react` >= 18.0.0

## Quick Start

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { EnclaveProvider, useEnclaveSession } from '@enclave-vm/react';

function App() {
  return (
    <EnclaveProvider config={{ baseUrl: 'https://api.example.com' }}>
      <CodeEditor />
    </EnclaveProvider>
  );
}

function CodeEditor() {
  const { execute, state, stdout, result, error } = useEnclaveSession();

  return (
    <div>
      <button
        onClick={() => execute('return 42;')}
        disabled={state === 'running'}
      >
        Run
      </button>
      <pre>{stdout}</pre>
      {result?.success && <div>Result: {JSON.stringify(result.value)}</div>}
      {error && <div className="error">{error.message}</div>}
    </div>
  );
}
```

## EnclaveProvider

The provider sets up the EnclaveClient context for your application.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { EnclaveProvider, type EnclaveClientConfig } from '@enclave-vm/react';

const config: EnclaveClientConfig = {
  // Required: Broker URL
  baseUrl: 'https://api.example.com',

  // Optional: Headers sent with every request (e.g., credentials)
  headers: {
    'Authorization': 'Bearer token',
  },

  // Optional: How long to wait for the server (ms)
  timeout: 60000,

  // Optional: Reconnection
  autoReconnect: true,
  maxReconnectAttempts: 3,
  reconnectDelay: 1000,
};

function App() {
  return (
    <EnclaveProvider config={config}>
      <MyApp />
    </EnclaveProvider>
  );
}
```

`config` takes exactly the options of [`EnclaveClient`](https://docs.agentfront.dev/enclave/enclavejs/client#client-configuration): `baseUrl`, `headers`, `timeout`, `autoReconnect`, `maxReconnectAttempts`, `reconnectDelay`, `maxEventLength` and `fetch`. Any other option, such as `encryption`, `auth` or `serverUrl`, throws when the provider renders.

> [!NOTE]
>
> The client does not encrypt. Requests and events travel as plain JSON over HTTP and are protected only by the transport: use an `https:` base URL, and send credentials with `headers`.

### Configuration Changes

The provider builds the client from `config`:

* When a render brings a configuration with other values, such as another `baseUrl` or a renewed token in `headers`, the provider builds a new client from it. The context then hands out that client together with that configuration.
* A render with an equal configuration, such as an object literal written inline, keeps the client.
* A session that was started before the change finishes on the client it was started with.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function App({ token }: { token: string }) {
  return (
    <EnclaveProvider
      config={{
        baseUrl: 'https://api.example.com',
        headers: { 'Authorization': `Bearer ${token}` },
      }}
    >
      <MyApp />
    </EnclaveProvider>
  );
}
```

### Using Your Own Client

Pass a client that you created yourself with the `client` prop. The provider then builds none; `config` is still required, and the context reports it as it is.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { EnclaveClient } from '@enclave-vm/client';
import { EnclaveProvider } from '@enclave-vm/react';

const config = { baseUrl: 'https://api.example.com' };
const client = new EnclaveClient(config);

function App() {
  return (
    <EnclaveProvider config={config} client={client}>
      <MyApp />
    </EnclaveProvider>
  );
}
```

## useEnclaveSession Hook

The main hook for executing code and managing session state.

### Basic Usage

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useEnclaveSession } from '@enclave-vm/react';

function CodeRunner() {
  const {
    execute,      // Function to execute code
    cancel,       // Cancel execution
    reset,        // Reset state
    state,        // Current session state
    isRunning,    // Whether a session is running
    sessionId,    // ID of the latest session
    result,       // SessionResult (when the session has ended)
    error,        // Error (if the session failed)
    stdout,       // Accumulated stdout output
    events,       // Events received
  } = useEnclaveSession();

  return (
    <div>
      <button onClick={() => execute('return 1 + 1')}>
        Run
      </button>
    </div>
  );
}
```

### Session States

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Available states
type SessionState =
  | 'idle'        // No execution in progress
  | 'running'     // Code is executing
  | 'completed'   // Execution finished successfully
  | 'error'       // Execution failed
  | 'cancelled';  // Execution was cancelled
```

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useEnclaveSession } from '@enclave-vm/react';

function StatusIndicator() {
  const { state } = useEnclaveSession();

  switch (state) {
    case 'idle':
      return <span>Ready</span>;
    case 'running':
      return <span>Running...</span>;
    case 'completed':
      return <span>Done!</span>;
    case 'error':
      return <span>Failed</span>;
    case 'cancelled':
      return <span>Cancelled</span>;
  }
}
```

### Options

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useEnclaveSession, type UseEnclaveSessionOptions } from '@enclave-vm/react';

function CodeRunner() {
  const options: UseEnclaveSessionOptions = {
    // Limits requested for every execution
    timeoutMs: 30000,            // Maximum session duration (ms)
    maxToolCalls: 20,
    heartbeatIntervalMs: 15000,

    // Event handlers
    onStart: () => {
      console.log('Execution started');
    },

    onStdout: (chunk) => {
      // Custom stdout handling
    },

    onLog: (level, message, data) => {
      console.log(`[${level}]`, message);
    },

    onToolCall: (callId, toolName, args) => {
      console.log('Tool called:', toolName);
    },

    onToolResultApplied: (callId) => {
      console.log('Tool result applied:', callId);
    },

    onComplete: (result) => {
      console.log('Finished:', result.success);
    },

    onError: (error) => {
      console.error('Error:', error.code, error.message);
    },
  };

  const session = useEnclaveSession(options);

  return <div>{/* ... */}</div>;
}
```

`onComplete` is called with the result of every execution, whether it succeeded, failed or was cancelled. `onError` is called for non-fatal errors that the session reports while it runs, when the execution fails, and with the code `CANCEL_FAILED` when the broker does not confirm a cancellation.

There is also a `sessionId` option. The ID is used for every execution of the hook; without it, each execution gets a generated ID.

### Return Value

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import type { UseEnclaveSessionReturn } from '@enclave-vm/react';

const session: UseEnclaveSessionReturn = useEnclaveSession();

// Execute code
const result = await session.execute(code);

// Current state
session.state;      // SessionState
session.isRunning;  // boolean
session.sessionId;  // SessionId | null

// Output
session.stdout;     // string (accumulated)
session.events;     // StreamEvent[]
session.result;     // SessionResult | null
session.error;      // { code?, message } | null

// Actions
await session.cancel();  // Cancel current execution
session.reset();         // Reset to idle state
```

`execute` resolves with the `SessionResult` of the execution, also when it fails or is cancelled. `result` holds the same object: the returned value is `result.value`, and the client's stats are `result.stats`.

`stdout`, `events`, `result` and `error` are cleared when the next execution starts. `reset()` clears them too, but it does not cancel a running session.

## useEnclaveClient Hook

Access the underlying EnclaveClient directly.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useEnclaveClient } from '@enclave-vm/react';

function CustomComponent() {
  const client = useEnclaveClient();

  // Use client directly for advanced scenarios
  const handleExecute = async () => {
    const session = client.executeStream(code, {
      onStdout: console.log,
    });

    const result = await session.wait();
  };

  return <button onClick={handleExecute}>Execute</button>;
}
```

## useEnclaveContext Hook

Access the full context value including client and configuration.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useEnclaveContext, type EnclaveContextValue } from '@enclave-vm/react';

function DebugComponent() {
  const context: EnclaveContextValue = useEnclaveContext();

  return (
    <div>
      <p>Broker URL: {context.config.baseUrl}</p>
    </div>
  );
}
```

## Examples

### Code Editor with Output

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useState } from 'react';
import { EnclaveProvider, useEnclaveSession } from '@enclave-vm/react';

function CodeEditor() {
  const [code, setCode] = useState('return 42;');
  const { execute, state, stdout, result, error, reset } = useEnclaveSession();

  return (
    <div className="editor">
      <textarea
        value={code}
        onChange={(e) => setCode(e.target.value)}
        disabled={state === 'running'}
      />

      <div className="buttons">
        <button
          onClick={() => execute(code)}
          disabled={state === 'running'}
        >
          {state === 'running' ? 'Running...' : 'Run'}
        </button>
        <button onClick={reset}>Reset</button>
      </div>

      <div className="output">
        <h3>Output</h3>
        <pre>{stdout}</pre>
      </div>

      {result?.success && (
        <div className="result">
          <h3>Result</h3>
          <pre>{JSON.stringify(result.value, null, 2)}</pre>
        </div>
      )}

      {error && (
        <div className="error">
          <h3>Error</h3>
          <pre>{error.message}</pre>
        </div>
      )}
    </div>
  );
}

function App() {
  return (
    <EnclaveProvider config={{ baseUrl: 'https://api.example.com' }}>
      <CodeEditor />
    </EnclaveProvider>
  );
}
```

### With Tool Calls

Tools run on the broker. The hook is told about tool calls; it executes nothing.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function ToolDemo() {
  const { execute, state, stdout, result } = useEnclaveSession({
    onToolCall: (callId, toolName, args) => {
      console.log(`Tool ${toolName} called with:`, args);
    },
  });

  const runWithTool = () => {
    execute(`
      const time = await callTool('getCurrentTime', {});
      return time;
    `);
  };

  return (
    <div>
      <button onClick={runWithTool} disabled={state === 'running'}>
        Get Current Time
      </button>
      <pre>{stdout}</pre>
      {result?.success && <p>Time: {String(result.value)}</p>}
    </div>
  );
}
```

### With Cancellation

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function CancellableExecution() {
  const { execute, state, cancel, stdout } = useEnclaveSession();

  const runLongTask = () => {
    execute(`
      for (let i = 0; i < 100; i++) {
        await callTool('processItem', { id: i });
      }
      return 'done';
    `);
  };

  return (
    <div>
      {state === 'running' ? (
        <button onClick={() => cancel()}>Cancel</button>
      ) : (
        <button onClick={runLongTask}>Start Long Task</button>
      )}
      <pre>{stdout}</pre>
    </div>
  );
}
```

`cancel()` ends the session in the client, where the state becomes `'cancelled'`, and asks the broker to end it. The hook does not cancel a running session when the component unmounts.

### Multiple Sessions

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function MultiSession() {
  const session1 = useEnclaveSession();
  const session2 = useEnclaveSession();

  return (
    <div className="split">
      <div>
        <h3>Session 1</h3>
        <button onClick={() => session1.execute('return 1')}>
          Run
        </button>
        <pre>{session1.stdout}</pre>
      </div>
      <div>
        <h3>Session 2</h3>
        <button onClick={() => session2.execute('return 2')}>
          Run
        </button>
        <pre>{session2.stdout}</pre>
      </div>
    </div>
  );
}
```

## TypeScript Types

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Types of the hooks and the provider
import type {
  SessionState,
  UseEnclaveSessionOptions,
  UseEnclaveSessionReturn,
  EnclaveProviderProps,
  EnclaveContextValue,
} from '@enclave-vm/react';

// Re-exported from @enclave-vm/client
import type {
  EnclaveClient,
  EnclaveClientConfig,
  SessionResult,
  SessionHandle,
  StreamEvent,
  SessionId,
} from '@enclave-vm/react';
```

## Links

* [GitHub](https://github.com/agentfront/enclave/tree/main/libs/react)
* [npm](https://www.npmjs.com/package/@enclave-vm/react)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.