> ## 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.

# Streaming UI

> Build real-time code execution interfaces with streaming output

Build real-time interfaces that show code execution as it happens.

The client talks to an [`@enclave-vm/broker`](https://docs.agentfront.dev/enclave/enclavejs/broker) over HTTP. Tools run on the broker; the client is told about each tool call and gets the result of the script. The examples below assume a broker at `http://localhost:3001` with the tools `users:list` and `users:process` registered.

## Basic Streaming

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

const client = new EnclaveClient({
  baseUrl: 'http://localhost:3001',
});

const code = `
  const users = await callTool('users:list', {});

  for (const user of users) {
    await callTool('users:process', { userId: user.id });
  }

  return users.length;
`;

// Execute; the handlers are called as the events arrive
const result = await client.execute(code, {
  onToolCall: (callId, toolName, args) => {
    console.log('[Tool]', toolName, args);
  },
  onToolResultApplied: (callId) => {
    console.log('[Tool done]', callId);
  },
  onError: (code, message) => {
    console.error('[Error]', code, message);
  },
});

if (result.success) {
  console.log('[Result]', result.value);
} else {
  console.error('[Failed]', result.error?.code, result.error?.message);
}
```

`execute()` resolves with the result; a session that fails is not a rejected promise. `executeStream()` returns a handle at once (`sessionId`, `wait()`, `cancel()`, `getEvents()`, `isActive()`), and `onEvent` receives every event.

> [!NOTE]
>
> The broker emits no `stdout` events, and a script cannot use `console` in the broker's sandbox unless the broker is configured for it. Show progress with the tool-call events, as below. To stream console output, see [Streaming with your own endpoint](#streaming-with-your-own-endpoint).

## React Streaming Hook

`@enclave-vm/react` has a ready-made hook, `useEnclaveSession` (see [@enclave-vm/react](https://docs.agentfront.dev/enclave/enclavejs/react.md)). This one is built on the client directly, to show what such a hook does:

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

interface StreamState {
  status: 'idle' | 'running' | 'completed' | 'error';
  output: string[];
  toolCalls: ToolCall[];
  result: unknown;
  error: string | null;
}

interface ToolCall {
  id: string;
  tool: string;
  args: unknown;
  status: 'pending' | 'completed';
}

export function useStreaming(client: EnclaveClient) {
  const [state, setState] = useState<StreamState>({
    status: 'idle',
    output: [],
    toolCalls: [],
    result: null,
    error: null,
  });

  const execute = useCallback(async (code: string) => {
    setState({
      status: 'running',
      output: [],
      toolCalls: [],
      result: null,
      error: null,
    });

    const result = await client.execute(code, {
      onToolCall: (callId, toolName, args) => {
        setState(prev => ({
          ...prev,
          output: [...prev.output, `> ${toolName}`],
          toolCalls: [...prev.toolCalls, { id: callId, tool: toolName, args, status: 'pending' }],
        }));
      },
      onToolResultApplied: (callId) => {
        setState(prev => ({
          ...prev,
          toolCalls: prev.toolCalls.map(tc =>
            tc.id === callId ? { ...tc, status: 'completed' } : tc
          ),
        }));
      },
      // Called for stdout events, when the server sends them
      onStdout: (chunk) => {
        setState(prev => ({ ...prev, output: [...prev.output, chunk] }));
      },
    });

    // A failed session resolves with success: false; execute() does not reject
    setState(prev =>
      result.success
        ? { ...prev, status: 'completed', result: result.value }
        : { ...prev, status: 'error', error: result.error?.message ?? 'Execution failed' }
    );
  }, [client]);

  return { ...state, execute };
}
```

## Streaming Console Component

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import React, { useRef, useEffect } from 'react';

interface StreamingConsoleProps {
  output: string[];
  autoScroll?: boolean;
}

export function StreamingConsole({ output, autoScroll = true }: StreamingConsoleProps) {
  const consoleRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (autoScroll && consoleRef.current) {
      consoleRef.current.scrollTop = consoleRef.current.scrollHeight;
    }
  }, [output, autoScroll]);

  return (
    <div
      ref={consoleRef}
      style={{
        fontFamily: 'monospace',
        backgroundColor: '#1e1e1e',
        color: '#d4d4d4',
        padding: '1rem',
        borderRadius: '4px',
        height: '300px',
        overflowY: 'auto',
      }}
    >
      {output.length === 0 ? (
        <span style={{ color: '#666' }}>Waiting for output...</span>
      ) : (
        output.map((line, i) => (
          <div key={i} style={{ whiteSpace: 'pre-wrap' }}>
            {line}
          </div>
        ))
      )}
    </div>
  );
}
```

## Tool Call Timeline

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import React from 'react';

interface ToolCall {
  id: string;
  tool: string;
  args: unknown;
  status: 'pending' | 'completed';
}

interface ToolTimelineProps {
  toolCalls: ToolCall[];
}

export function ToolTimeline({ toolCalls }: ToolTimelineProps) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      {toolCalls.map((call, i) => (
        <div
          key={call.id}
          style={{
            display: 'flex',
            alignItems: 'center',
            padding: '8px 12px',
            backgroundColor: '#f5f5f5',
            borderRadius: '4px',
            borderLeft: `4px solid ${
              call.status === 'completed' ? '#22c55e' : '#f59e0b'
            }`,
          }}
        >
          <span style={{ marginRight: '8px', fontSize: '14px' }}>
            {call.status === 'completed' ? '✓' : '...'}
          </span>
          <span style={{ fontWeight: 600, marginRight: '8px' }}>
            {call.tool}
          </span>
          <span style={{ color: '#666', fontSize: '12px' }}>
            {JSON.stringify(call.args)}
          </span>
        </div>
      ))}
    </div>
  );
}
```

## Complete Streaming UI

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import React, { useState } from 'react';
import { EnclaveClient } from '@enclave-vm/client';
import { useStreaming } from './hooks/useStreaming';
import { StreamingConsole } from './components/StreamingConsole';
import { ToolTimeline } from './components/ToolTimeline';

const client = new EnclaveClient({
  baseUrl: 'http://localhost:3001',
});

export function CodeExecutor() {
  const [code, setCode] = useState(`
const users = await callTool('users:list', { limit: 5 });

for (const user of users) {
  await callTool('users:process', { userId: user.id });
}

return { count: users.length };
`);

  const { status, output, toolCalls, result, error, execute } = useStreaming(client);

  return (
    <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
      <h1>Code Executor</h1>

      {/* Code Input */}
      <div style={{ marginBottom: '1rem' }}>
        <textarea
          value={code}
          onChange={(e) => setCode(e.target.value)}
          style={{
            width: '100%',
            height: '200px',
            fontFamily: 'monospace',
            padding: '1rem',
          }}
          disabled={status === 'running'}
        />
      </div>

      {/* Execute Button */}
      <button
        onClick={() => execute(code)}
        disabled={status === 'running'}
        style={{
          padding: '0.5rem 1rem',
          backgroundColor: status === 'running' ? '#ccc' : '#0070f3',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: status === 'running' ? 'not-allowed' : 'pointer',
          marginBottom: '1rem',
        }}
      >
        {status === 'running' ? 'Running...' : 'Execute'}
      </button>

      {/* Status */}
      <div style={{ marginBottom: '1rem' }}>
        Status: <strong>{status}</strong>
      </div>

      {/* Output Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
        {/* Activity log */}
        <div>
          <h3>Activity</h3>
          <StreamingConsole output={output} />
        </div>

        {/* Tool Calls */}
        <div>
          <h3>Tool Calls</h3>
          <ToolTimeline toolCalls={toolCalls} />
        </div>
      </div>

      {/* Result */}
      {result !== null && (
        <div style={{ marginTop: '1rem' }}>
          <h3>Result</h3>
          <pre style={{
            backgroundColor: '#f5f5f5',
            padding: '1rem',
            borderRadius: '4px',
            overflow: 'auto',
          }}>
            {JSON.stringify(result, null, 2)}
          </pre>
        </div>
      )}

      {/* Error */}
      {error && (
        <div style={{
          marginTop: '1rem',
          padding: '1rem',
          backgroundColor: '#fee2e2',
          color: '#dc2626',
          borderRadius: '4px',
        }}>
          <strong>Error:</strong> {error}
        </div>
      )}
    </div>
  );
}
```

## Streaming with your own endpoint

Without the broker, an endpoint of your own can stream what a script does with `@enclave-vm/core` directly. This one uses Server-Sent Events and the `consoleHandler` option, which hands the script's console lines to the host:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Server
import express from 'express';
import { Enclave } from '@enclave-vm/core';

const app = express();
app.use(express.json());

app.post('/execute', async (req, res) => {
  // Set SSE headers
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const enclave = new Enclave({
    toolHandler: async (name, args) => {
      // Send tool call event
      res.write(`event: tool_call\ndata: ${JSON.stringify({ tool: name, args })}\n\n`);
      const result = await executeTool(name, args);
      res.write(`event: tool_result\ndata: ${JSON.stringify({ tool: name })}\n\n`);
      return result;
    },
    // With a consoleHandler a script may use console at every security level
    consoleHandler: (level, message) => {
      res.write(`event: stdout\ndata: ${JSON.stringify({ level, data: message })}\n\n`);
    },
  });

  try {
    // run() does not reject for a failing script: the failure is in the result
    const result = await enclave.run(req.body.code);
    res.write(`event: final\ndata: ${JSON.stringify(result)}\n\n`);
  } finally {
    res.end();
    enclave.dispose();
  }
});
```

This endpoint runs whatever code it is sent: put your authentication in front of it, and bound the size of the request body.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Client
async function executeWithSSE(code: string) {
  const response = await fetch('/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code }),
  });

  if (!response.body) {
    throw new Error('Response body is null');
  }
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  let buffer = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n\n');
    buffer = lines.pop() || '';

    for (const chunk of lines) {
      if (chunk.startsWith('event:')) {
        const [eventLine, dataLine] = chunk.split('\n');
        const event = eventLine.replace('event: ', '');
        const data = JSON.parse(dataLine.replace('data: ', ''));
        handleEvent(event, data);
      }
    }
  }
}
```

## Progress Indicators

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ProgressProps {
  status: 'idle' | 'running' | 'completed' | 'error';
  toolCallCount: number;
  duration?: number;
}

export function ExecutionProgress({ status, toolCallCount, duration }: ProgressProps) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: '16px',
      padding: '12px',
      backgroundColor: '#f5f5f5',
      borderRadius: '8px',
    }}>
      {/* Status Indicator */}
      <div style={{
        width: '12px',
        height: '12px',
        borderRadius: '50%',
        backgroundColor: {
          idle: '#9ca3af',
          running: '#f59e0b',
          completed: '#22c55e',
          error: '#ef4444',
        }[status],
        animation: status === 'running' ? 'pulse 1s infinite' : 'none',
      }} />

      {/* Status Text */}
      <span style={{ fontWeight: 500 }}>
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </span>

      {/* Tool Calls */}
      {toolCallCount > 0 && (
        <span style={{ color: '#666' }}>
          {toolCallCount} tool call{toolCallCount !== 1 ? 's' : ''}
        </span>
      )}

      {/* Duration */}
      {duration !== undefined && (
        <span style={{ color: '#666' }}>
          {duration}ms
        </span>
      )}
    </div>
  );
}
```

## Next Steps

* [React Code Editor Guide](https://docs.agentfront.dev/enclave/guides/react-code-editor.md) - Full implementation
* [@enclave-vm/react](https://docs.agentfront.dev/enclave/enclavejs/react.md) - React SDK
* [Multi-Tenant](https://docs.agentfront.dev/enclave/examples/multi-tenant.md) - Per-user isolation


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