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

# Web SDK events

> Every event the Hamsa Web SDK sends and what it carries: the call, the agent's state, live transcripts, the microphone, the connection, analytics, page tools and data messages.

Listen with `agent.on(name, handler)`, and stop with `agent.off(name, handler)`. Add your listeners before you call `start()`, so you don't miss the first events. The SDK keeps them from call to call, so add them once.

## Show a live transcript

In a voice call, `messageReceived` sends the agent's and the visitor's words as they're spoken. One sentence arrives several times while it grows, with the same `id`, and `isFinal` is `true` on the last time:

```javascript theme={null}
const lines = new Map();

agent.on("messageReceived", ({ id, role, text, isFinal }) => {
  let line = lines.get(id);
  if (!line) {
    line = document.createElement("p");
    line.className = role; // "agent" or "user"
    transcript.append(line);
    lines.set(id, line);
  }
  line.textContent = text;
  line.classList.toggle("partial", !isFinal);
});
```

`answerReceived` (the agent) and `transcriptionReceived` (the visitor) send the same words as plain text. They fire for the partial text too, and don't say when it's final, so use `messageReceived` for a transcript.

## All events

### The call

| Event | Handler receives | When |
| - | - | - |
| `start` | nothing | The connection is up, just before the call starts. |
| `callStarted` | `{ jobId }` | The call has started. `jobId` is the call's ID. |
| `callEnded` | nothing | The call ended, whoever ended it. After `end()` it can fire twice. |
| `closed` | nothing | Right after `callEnded`, when the connection is closed. |
| `callPaused` | nothing | After `pause()`. |
| `callResumed` | nothing | After `resume()`. |
| `error` | `Error` or `HamsaApiError` | Something went wrong. See [If a call fails to start](https://docs.tryhamsa.com/developers/sdks/web-sdk/start-calls.md#if-a-call-fails-to-start). |
| `info` | a string | A note from the SDK. |

### The agent

| Event | Handler receives | When |
| - | - | - |
| `agentStateChanged` | `idle`, `initializing`, `listening`, `thinking` or `speaking` | The agent's state changes. See [Show what the agent is doing](https://docs.tryhamsa.com/developers/sdks/web-sdk/during-a-call.md#show-what-the-agent-is-doing). |
| `speaking` | nothing | The agent starts talking. |
| `listening` | nothing | The agent starts listening. |

### The conversation

| Event | Handler receives | When |
| - | - | - |
| `messageReceived` | `{ id, role, text, isFinal, timestamp }` | Words from the agent or the visitor, in a voice call or a chat. |
| `chatMessageReceived` | `{ id, role, text, isFinal, timestamp }` | A message from the agent in a [chat](https://docs.tryhamsa.com/developers/sdks/web-sdk/chat.md). Never in a voice call. |
| `answerReceived` | the text | The agent's words in a voice call, partial or final. |
| `transcriptionReceived` | the text | The visitor's words in a voice call, partial or final. |
| `messageSent` | the text | `sendMessage()` sent the visitor's chat message. |
| `dtmfSent` | the digit | `sendDTMF()` sent a keypad digit. |

### Microphone and audio

| Event | Handler receives | When |
| - | - | - |
| `micMuted` | nothing | The microphone was muted. |
| `micUnmuted` | nothing | The microphone was unmuted. |
| `audioPlaybackChanged` | `true` or `false` | Whether the browser lets the page play the agent. `false` means the browser blocked audio: start calls from a click or a tap. |
| `trackSubscribed` | `{ track, publication, participant, trackStats? }` | The agent's audio (or video) reached the page. `track` is a LiveKit track. |
| `trackUnsubscribed` | `{ track, publication, participant }` | That track stopped. |
| `localTrackPublished` | `{ track, publication }` | The visitor's microphone is being sent. |

### The connection

| Event | Handler receives | When |
| - | - | - |
| `connectionStateChanged` | LiveKit's connection state, such as `connected` or `reconnecting` | The connection changes state. |
| `connectionQualityChanged` | `{ quality, participant, metrics }` | The network's quality changes: `excellent`, `good`, `poor`, `lost` or `unknown`. |
| `reconnecting` | nothing | The connection dropped and the SDK is trying again. |
| `reconnected` | nothing | The connection is back. |
| `participantConnected` | a LiveKit participant | Someone joined the call, such as the agent. |
| `participantDisconnected` | a LiveKit participant | Someone left. This doesn't mean the call ended: wait for `callEnded`. |

### Analytics

| Event | Handler receives | When |
| - | - | - |
| `analyticsUpdated` | the same object as `getCallAnalytics()` | Every 5 seconds during a call. |

### Page tools

| Event | Handler receives | When |
| - | - | - |
| `toolsRegistered` | the tools | Your [page tools](https://docs.tryhamsa.com/agents/tools/web-tools.md) are ready for the agent. |
| `rpcError` | the function's name, the error | One of your page tools failed. |

### Data messages

| Event | Handler receives | When |
| - | - | - |
| `dataReceived` | the message (parsed from JSON), the sender's identity | The agent sent a data message. |
| `customEvent` | the message's `event`, its `content` or `data`, `{ timestamp, participant, rawMessage }` | A data message that isn't a transcript or an answer. |

Hamsa agents send their call logs as data messages, so these fire during most calls. What's in them isn't a stable interface: don't build on their content.

## Warn about a bad connection

```javascript theme={null}
agent.on("connectionQualityChanged", ({ quality }) => {
  networkWarning.hidden = quality !== "poor" && quality !== "lost";
});

agent.on("reconnecting", () => (status.textContent = "Reconnecting…"));
agent.on("reconnected", () => (status.textContent = "Connected"));
```

## Read call statistics

During a call you can read these at any time. They return `null` (or an empty list) when there's no call.

| Method | Returns |
| - | - |
| `getConnectionStats()` | `quality`, `connectionAttempts`, `reconnectionAttempts`, `connectionEstablishedTime` (ms), `isConnected` |
| `getAudioLevels()` | `userAudioLevel`, `agentAudioLevel` (0 to 1), `userSpeakingTime`, `agentSpeakingTime` (ms), `audioDropouts`, `echoCancellationActive`, and more |
| `getPerformanceMetrics()` | `responseTime`, `averageResponseTime`, `callDuration`, `connectionEstablishedTime` (ms), `reconnectionCount` |
| `getParticipants()` | who is in the call: `identity`, `sid`, `connectionTime`, `metadata` |
| `getTrackStats()` | `totalTracks`, `activeTracks`, `audioElements`, `trackDetails` |
| `getCallAnalytics()` | all of the above in one object (`connectionStats`, `audioMetrics`, `performanceMetrics`, `participants`, `trackStats`, `callStats`, `metadata`) |

```javascript theme={null}
agent.on("analyticsUpdated", ({ performanceMetrics, connectionStats }) => {
  duration.textContent = `${Math.round(performanceMetrics.callDuration / 1000)} s`;
  quality.textContent = connectionStats.quality;
});
```

## Related

> [card] [During a call](https://docs.tryhamsa.com/developers/sdks/web-sdk/during-a-call.md)
>
> End, pause, mute, volume and keypad digits.

> [card] [Reference](https://docs.tryhamsa.com/developers/sdks/web-sdk/reference.md)
>
> Every option and method, with types.


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