---
updatedAt: 2026-02-26T14:31:02.000Z
agentTools:
  projectIndex: https://docs.d-id.com/llms.txt
---

# Events and States

Event subscription and state monitoring for embedded agents

Subscribe to agent events to monitor connection state, agent activity, and errors in real time. Use event callbacks to update your UI, log analytics, or trigger custom behavior.

## Available Events

The API exposes three event types for monitoring agent state.

| EVENT             | PAYLOAD     | DESCRIPTION                                   |
| :---------------- | :---------- | :-------------------------------------------- |
| **connection**    | `{ state }` | Connection state changes throughout lifecycle |
| **agentActivity** | `{ state }` | Agent activity status changes                 |
| **error**         | `{ error }` | Errors and exceptions                         |

## Event Subscription

Use `window.DID_AGENTS_API.events.on()` to subscribe to events. All subscriptions return an unsubscribe function.

### Basic Pattern

```javascript
const api = window.DID_AGENTS_API;

// Subscribe to an event
const unsubscribe = api.events.on("connection", ({ state }) => {
  console.log("Connection state:", state);
});

// Later, clean up
unsubscribe();
```

## connection Event

Tracks the WebRTC connection lifecycle from initialization to closure.

### Connection States

| STATE             | DESCRIPTION                                   |
| :---------------- | :-------------------------------------------- |
| **new**           | Connection initialized, not yet started       |
| **connecting**    | Attempting to establish connection            |
| **connected**     | Successfully connected and ready              |
| **disconnected**  | Connection lost (may reconnect automatically) |
| **disconnecting** | Closing connection gracefully                 |
| **closed**        | Connection closed normally                    |
| **fail**          | Connection failed (check error event)         |
| **completed**     | Connection completed successfully             |

### Example: Complete Connection Handling

```javascript
const api = window.DID_AGENTS_API;

const unsubscribe = api.events.on("connection", ({ state }) => {
  console.log("Connection state:", state);

  switch (state) {
    case "new":
      console.log("Connection initialized");
      break;

    case "connecting":
      console.log("Connecting to agent...");
      showLoadingIndicator();
      break;

    case "connected":
      console.log("Connected successfully!");
      hideLoadingIndicator();
      showAgentInterface();
      break;

    case "disconnected":
      console.log("Connection lost");
      showReconnectingMessage();
      break;

    case "disconnecting":
      console.log("Closing connection...");
      break;

    case "closed":
      console.log("Connection closed");
      hideAgentInterface();
      break;

    case "fail":
      console.error("Connection failed");
      showErrorMessage("Unable to connect to agent");
      break;

    case "completed":
      console.log("Connection completed");
      break;
  }
});
```

## agentActivity Event

Tracks what the agent is currently doing.

### Agent Activity States

| STATE         | DESCRIPTION                                   |
| :------------ | :-------------------------------------------- |
| **IDLE**      | Agent is waiting and ready to interact        |
| **TALKING**   | Agent is currently speaking                   |
| **LOADING**   | Agent is processing (LLM generating response) |
| **BUFFERING** | Agent is buffering audio/video                |

### Example: Activity Monitoring

```javascript
api.events.on("agentActivity", ({ state }) => {
  console.log("Agent activity:", state);

  const statusElement = document.querySelector(".agent-status");

  switch (state) {
    case "IDLE":
      statusElement.textContent = "Ready to chat";
      statusElement.className = "agent-status idle";
      break;

    case "TALKING":
      statusElement.textContent = "Speaking...";
      statusElement.className = "agent-status talking";
      break;

    case "LOADING":
      statusElement.textContent = "Thinking...";
      statusElement.className = "agent-status loading";
      break;

    case "BUFFERING":
      statusElement.textContent = "Buffering...";
      statusElement.className = "agent-status buffering";
      break;
  }
});
```

## Multiple Event Subscriptions

Subscribe to multiple events and manage cleanup.

```javascript
const api = window.DID_AGENTS_API;

// Store unsubscribe functions
const subscriptions = [];

// Connection monitoring
subscriptions.push(
  api.events.on("connection", ({ state }) => {
    updateConnectionStatus(state);
  }),
);

// Activity monitoring
subscriptions.push(
  api.events.on("agentActivity", ({ state }) => {
    updateAgentActivity(state);
  }),
);

// Error handling
subscriptions.push(
  api.events.on("error", ({ error }) => {
    handleError(error);
  }),
);

// Clean up all subscriptions
window.addEventListener("beforeunload", () => {
  subscriptions.forEach((unsubscribe) => unsubscribe());
});
```

## FAQ

<CoolAccordionBox>
  <CoolAccordion title="When should I subscribe to events?">
    Subscribe to events after the API loads, typically in a `window.addEventListener("load", ...)` callback. Events will fire as soon as state changes occur.
  </CoolAccordion>

  <CoolAccordion title="Do I need to unsubscribe from events?">
    Yes, always unsubscribe when you no longer need the event listener to prevent memory leaks. This is especially important for single-page applications. Store the unsubscribe function and call it during cleanup.
  </CoolAccordion>

  <CoolAccordion title="Can I subscribe to the same event multiple times?">
    Yes. Each subscription is independent and receives its own callback. However, this is rarely needed and can lead to duplicate processing. Usually one callback per event type is sufficient.
  </CoolAccordion>

  <CoolAccordion title="How do I distinguish between different error types?">
    Check the `error.code` or `error.type` property in the error event payload. Common codes include `NETWORK_ERROR`, `AUTH_ERROR`, and `TIMEOUT_ERROR`. Log the error object to see all available properties.
  </CoolAccordion>
</CoolAccordionBox>