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

# Manage Ambient Session

> Learn how to manage an ambient session lifecycle within your application while using the Suki Headless Web SDK

<Callout title="Updates" color="orange" icon="bell">
  **Updated**

  The `useAmbientSession` hook now returns a `sessionType` property. This helps you determine whether the session is an online or offline session.
</Callout>

<div className="quick-summary-wrapper">
  <div className="quick-summary-header">
    <span className="quick-summary-icon" aria-hidden="true" />

    <span className="quick-summary-title">Quick summary</span>
  </div>

  <div className="quick-summary-content">
    The `useAmbientSession` hook controls your audio recording workflow. Use it after creating a session with `useAmbient` to manage recording, pausing, and submitting audio.

    <br />

    <br />

    The hook provides methods to `start`, `pause`, `resume`, `cancel`, and `submit` recordings. It returns session status so you can update your UI and provides real-time audio data through callbacks for building visualizations.
  </div>

  <div className="quick-summary-footer">
    <span className="quick-summary-footer-icon" aria-hidden="true" />

    <span className="quick-summary-footer-text">Last updated:</span>
    <span className="quick-summary-footer-date">June 2026</span>
  </div>
</div>

The **`useAmbientSession`** hook allows you to control the ambient recording workflow after you have an **`ambientSessionId`**. It exposes **`start`**, **`pause`**, **`resume`**, **`cancel`**, and **`submit`**, optional **`setSessionContext`**, session status, **`sessionType`** (online or offline), and optional real-time audio chunks for visualizations.

### Configuration

Pass the **`ambientSessionId`** you received from **`useAmbient`** after **`session.isSuccess`** is `true` (refer to [Create Ambient Session](/headless-web-sdk/guides/hooks/ambient-hook)). Run the hook under **`PlatformClientProvider`**.
Refer to [Platform client and provider](/headless-web-sdk/api-reference/platform-client) for more information.

### Common use cases

<Steps>
  <Step title="Control the recording lifecycle" icon="play">
    Use the recording control methods to match the behavior of your application's recording experience:

    * **`start()`** to begin recording
    * **`pause()`** to temporarily stop audio capture
    * **`resume()`** to continue a paused recording
    * **`cancel()`** to discard the current session
    * **`submit()`** to finalize and submit the recording for processing
  </Step>

  <Step title="Attach clinical context to a session" icon="clipboard">
    Use **`setSessionContext()`** to associate patient, provider, and visit metadata with the active session.

    Call **`setSessionContext()`** after **`start()`** and before **`submit()`** to ensure the metadata is included with the session. For supported fields and examples, refer to [Session context](#session-context) below.
  </Step>

  <Step title="Support online and offline session flows" icon="signal">
    Read **`sessionType`** to determine how the session is running:

    * **`"online"`** for real-time workflows
    * **`"offline"`** for deferred or asynchronous processing workflows

    Use this value to conditionally render UI, messaging, or workflow behavior.
  </Step>

  <Step title="Process audio waveform data" icon="waveform">
    Use **`onAudioChunkAvailable`** to receive streamed audio chunks during recording. Audio data is returned as batched **`Int16Array`** chunks.

    Optionally configure **`config.audioBatchSize`** to control the batch size and frequency of audio chunk delivery.
  </Step>

  <Step title="Build responsive session status UI" icon="display">
    Use the returned session state values to drive UI behavior throughout the recording workflow:

    * **`sessionStatus`** for displaying the current session state
    * **`isFetching`** for loading indicators and disabled states
    * **`ambientSessionId`** for identifying and tracking the active session

    These values can be used to update labels, spinners, buttons, and workflow transitions in real time.
  </Step>
</Steps>

## useAmbientSession hook

### Usage

Call **`useAmbientSession`** with an object that includes **`ambientSessionId`** and optional **`config`** and **`onAudioChunkAvailable`**.

```tsx theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
const {
  start,
  pause,
  resume,
  cancel,
  submit,
  setSessionContext,
  sessionStatus,
  isFetching,
  sessionType, // [!code ++] New in v0.2.2
  ambientSessionId,
  config,
  onAudioChunkAvailable,
} = useAmbientSession({...});
```

### Returns

The hook returns control methods, session status, **`sessionType`**, and related fields. Parameter and return shapes are documented under [Configuration](#configuration) and [What it returns](#what-it-returns).

### How recording works

1. **Pass the session ID:** Provide the **`ambientSessionId`** from **`useAmbient`**.
2. **Configure options:** Optionally set **`config.audioBatchSize`** and **`onAudioChunkAvailable`** for real-time audio batches.
3. **Use the controls:** Call **`start`**, **`pause`**, **`resume`**, **`cancel`**, and **`submit`** to move through the lifecycle your UI needs.

```mermaid actions={false} theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
flowchart TD
    A[Start recording] --> B[Recording active]
    B --> C{Pause or Submit?}
    C -->|Pause| D[Paused]
    C -->|Submit| E[Submitting]
    D -->|Resume| B
    E --> F[Complete]
    C -->|Cancel| G[Session cancelled]
    
    style A fill:#FFF394,stroke:#D4A017,color:#000000
    style B fill:#FFF394,stroke:#D4A017,color:#000000
    style E fill:#FFF394,stroke:#D4A017,color:#000000
    style F fill:#FFF394,stroke:#D4A017,color:#000000
    style D fill:#e3e0e0,stroke:#8b8a8a,color:#000000
    style G fill:#e3e0e0,stroke:#8b8a8a,color:#000000
```

## Configuration

Configure the hook with these parameters:

<ResponseField name="ambientSessionId" type="string" required>
  Pass the unique session identifier you received from the `useAmbient` hook. This links the recording to the session you created.
</ResponseField>

<ResponseField name="config.audioBatchSize" type="number">
  **Optional**: Configure the audio batch size for the `onAudioChunkAvailable` callback.
</ResponseField>

<ResponseField name="onAudioChunkAvailable" type="function (audioChunk: Array<Int16Array>) => void">
  **Optional**: Provide a callback function that receives audio chunks as they become available. The SDK calls this function whenever a batch of audio data is ready. Use this to draw real-time waveforms, visualizers, or other audio visualizations in your UI.
</ResponseField>

```tsx theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
type UseAmbientSessionParams = {
  ambientSessionId: string;
  config?: {
    audioBatchSize?: number
  };
  onAudioChunkAvailable?: (audioChunk: Array<Int16Array>) => void;
}
```

## What it returns

The hook returns control methods and status information you use to manage recording and update your UI.

### Actions (methods)

Use these methods to control the recording workflow:

<ResponseField name="start" type="function: () => Promise<void>">
  Call this to begin recording audio. Call this when the user clicks a "Start Recording" button.
</ResponseField>

<ResponseField name="pause" type="function: () => Promise<void>">
  Call this to pause recording temporarily. Resume later with `resume()`. Call this when the user clicks a "Pause" button.
</ResponseField>

<ResponseField name="resume" type="function: () => Promise<void>">
  Call this to resume a paused recording. Call this when the user clicks a "Resume" button.
</ResponseField>

<ResponseField name="cancel" type="function: () => Promise<void>">
  Call this to stop recording and cancel the session. Call this when the user clicks a "Cancel" or "Discard" button.
</ResponseField>

<ResponseField name="submit" type="function: () => Promise<void>">
  Call this to finish recording and submit the session for note generation. Call this when the user clicks a "Finish" or "Submit" button.
</ResponseField>

<ResponseField name="setSessionContext" type="function: (context: SessionContext) => Promise<Response>">
  Call this to send patient, provider, and visit metadata to Suki. The function sends context information that helps Suki generate more accurate clinical notes. Call this after `start()` but before `submit()` for best results.
</ResponseField>

```tsx theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
type UseAmbientSessionReturn = {
  start: () => Promise<void>;
  pause: () => Promise<void>;
  resume: () => Promise<void>;
  cancel: () => Promise<void>;
  submit: () => Promise<void>;
  setSessionContext: (sessionContext: SessionContext) => Promise<SessionContextResponse>;
  sessionStatus: 
    | "created"
    | "submitted"
    | "completed"
    | "cancelled";
  sessionType: "online" | "offline";
};
```

### State (data)

Use these values to control your UI and show the current session state:

<ResponseField name="sessionStatus" type="AmbientSessionStatus">
  Check this value to display the current session state in your UI. Common values: `"created"` (session ready to start), `"submitted"` (recording finished, processing), `"completed"` (note generated), and `"cancelled"` (session cancelled). Use this to show status messages, enable/disable buttons, or change UI states based on the session status.
</ResponseField>

<ResponseField name="isFetching" type="boolean">
  Check this flag to show a loading state while syncing session information. When `true`, the SDK is currently fetching session status from Suki's backend. Display a loading indicator or disable actions while this is `true`.
</ResponseField>

<ResponseField name="sessionType" type="'online' | 'offline'">
  Use this value to determine whether the session is an online or offline session.
</ResponseField>

### Session context

The `setSessionContext` method lets you send patient, provider, and visit information to Suki. This context helps Suki's AI generate more accurate and relevant clinical notes.

#### What is session context?

Session context is metadata about the patient visit that improves note quality. Include:

* **Patient details**: Date of birth, sex
* **Provider information**: Specialty, role
* **Visit information**: Visit type, encounter type, reason for visit, chief complaint
* **Clinical sections**: [LOINC codes](/documentation/note-sections) for specific sections you want in the note
* **Diagnoses**: Pre-existing or current diagnoses with codes and descriptions

#### When to use it

Call `setSessionContext` after calling `start()` but before calling `submit()`. Providing context early helps the AI understand the clinical scenario and generate better notes.

#### Session context structure

```tsx theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
type SessionContext = {
  patient?: {
    dob: string;
    sex: string;
  };
  provider?: {
    specialty: string;
    role?: string;
  };
  visit?: {
    visit_type?: string;
    encounter_type?: string;
    reason_for_visit?: string;
    chief_complaint?: string;
  };
  sections?: Array<{ loinc: string }>;
  diagnoses?: {
    values: Array<{
      codes: Array<{
        code: string;
        description: string;
        type: string;
      }>;
      diagnosisNote: string;
    }>;
  };
};
```

#### Response type

```tsx theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
type SessionContextResponse = Record<string, never>;
```

The `setSessionContext` method returns an empty object when successful. If an error occurs, it throws a `ContextUpdateFailed` error. See the [Error handling guide](/headless-web-sdk/guides/error-handling#context-update-errors-contextupdatefailed) for details.

## Code example

This example shows how to build a recording interface with Start, Pause, Resume, and Submit controls. The UI updates based on `sessionStatus` to show the appropriate buttons at each stage.

```tsx React expandable theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
import { useAmbientSession } from '@suki-sdk/platform-react';

export const Recorder = ({ sessionId }) => {
  const {
    start,
    pause,
    resume,
    submit,
    sessionStatus,
    sessionType, // [!code ++] New in v0.2.2
    setSessionContext
  } = useAmbientSession({
    ambientSessionId: sessionId,
    onAudioChunkAvailable: (chunk) => {
      // Optional: Pass chunk to a waveform visualizer
      drawWaveform(chunk);
    }
  });

  // Set context immediately after starting for better note quality
  const handleStart = async () => {
    await start();
    // Send patient and visit context to improve note generation
    await setSessionContext({
      patient: {
        dob: '1980-01-15',
        sex: 'M'
      },
      provider: {
        specialty: 'Cardiology',
        role: 'Attending Physician'
      },
      visit: {
        visit_type: 'Follow-up',
        encounter_type: 'Office Visit',
        reason_for_visit: 'Chest pain evaluation',
        chief_complaint: 'Chest pain'
      }
    });
  };

  return (
    <div className="recorder-controls">
      <h3>Status: {sessionStatus}</h3>
      {sessionType === 'offline' && ( // [!code ++:2] added in v0.2.2
        <p className="offline-indicator">Session will sync when online</p>
      )}

      <div className="button-group">
        {/* Start Button */}
        {sessionStatus === 'created' && (
          <button onClick={handleStart}>Start Recording</button>
        )}

        {/* Pause/Resume Toggles - Add your own state tracking for recording/paused */}
        <button onClick={pause}>Pause</button>
        <button onClick={resume}>Resume</button>

        {/* Finalize Button */}
        <button onClick={submit}>
          Finish & Submit
        </button>
      </div>
    </div>
  );
};
```

<Tip>
  Always call `setSessionContext` to provide patient and encounter details. This context helps the AI understand the clinical scenario and generates significantly higher quality clinical notes.
</Tip>

## Next steps

<Icon icon="file-lines" iconType="solid" /> Learn production pause and submit patterns in [Session integration patterns](/headless-web-sdk/guides/integration-patterns).

<Icon icon="file-lines" iconType="solid" /> Learn how to handle errors in the [Error handling guide](/headless-web-sdk/guides/error-handling).
