# The Control Center (Dashboard & SDKs)

> The dashboard and SDK helpers that let you manage your WhatsApp army: scanning QR codes, monitoring system health, and sending API commands from your Python or JavaScript code.

- Repository: rmyndharis/OpenWA
- GitHub: https://github.com/rmyndharis/OpenWA
- Human wiki: https://grok-wiki.com/public/wiki/rmyndharis-openwa-2c9996a09a22
- Complete Markdown: https://grok-wiki.com/public/wiki/rmyndharis-openwa-2c9996a09a22/llms-full.txt

## Source Files

- `dashboard/src/App.tsx`
- `dashboard/src/pages/Sessions.tsx`
- `dashboard/src/pages/Infrastructure.tsx`
- `sdk/README.md`

---

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [dashboard/src/App.tsx](dashboard/src/App.tsx)
- [dashboard/src/pages/Sessions.tsx](dashboard/src/pages/Sessions.tsx)
- [dashboard/src/pages/Infrastructure.tsx](dashboard/src/pages/Infrastructure.tsx)
- [dashboard/src/services/api.ts](dashboard/src/services/api.ts)
- [sdk/README.md](sdk/README.md)
- [sdk/javascript/src/index.ts](sdk/javascript/src/index.ts)
- [sdk/python/openwa/__init__.py](sdk/python/openwa/__init__.py)
</details>

# The Control Center (Dashboard & SDKs)

To manage an army of WhatsApp instances efficiently, you need a single, centralized command post. OpenWA provides this via **The Control Center**: a visual React-based administrative dashboard and a set of lightweight, official SDK client libraries for JavaScript/TypeScript and Python. Together, these tools let you deploy new WhatsApp sessions, scan connection QR codes in real-time, audit system infrastructure logs, and programmatically orchestrate communication flows directly from your own application backend.

Whether you are an administrator monitoring queue performance and memory footprints or a developer embedding WhatsApp messaging triggers into your codebase, the Control Center translates low-level WhatsApp protocol handshakes into a clean, visual workflow and developer-friendly code interfaces.

---

## The Architecture Overview

Think of OpenWA as a system of remote-controlled radios (the WhatsApp sessions) and a Control Center (the dashboard and SDKs). The dashboard and SDKs act as the operator giving commands (like "turn on channel 1" or "send a message") and monitoring the system indicators (such as system memory, connection status, or queue failures). 

This modular layer acts as a unified client surface communicating exclusively over authenticated HTTP REST requests and real-time WebSocket events.

```mermaid
flowchart TD
  subgraph Client ["Client Layer (Command & Control)"]
    direction LR
    UI["React Dashboard (App.tsx)"]
    JSSDK["JS/TS SDK (index.ts)"]
    PySDK["Python SDK (__init__.py)"]
  end

  subgraph API ["Gateway Layer (OpenWA Node.js App)"]
    direction TB
    Auth["API Key Auth (X-API-Key)"]
    SessionMgr["Session Manager"]
    InfraMgr["Infra Config Manager"]
    QueueBull["BullMQ Queues"]
  end

  subgraph Engine ["WhatsApp Session Instances"]
    direction LR
    WAPh1["WhatsApp Phone Session 1"]
    WAPh2["WhatsApp Phone Session 2"]
  end

  subgraph Storage ["Infrastructure & Storage"]
    direction LR
    DB[(SQLite / PostgreSQL)]
    Cache[(Redis Cache)]
    LocalStore[(Local / S3 Media)]
  end

  UI -->|HTTP requests / WebSockets| Auth
  JSSDK -->|HTTP requests| Auth
  PySDK -->|HTTP requests| Auth

  Auth --> SessionMgr
  Auth --> InfraMgr

  SessionMgr -->|Manages| Engine
  SessionMgr -->|Pushes events| QueueBull
  InfraMgr -->|Stores config & migrations| DB
  QueueBull -->|Job caching| Cache
  SessionMgr -->|Stores media uploads| LocalStore
```
Sources: [dashboard/src/App.tsx:96-116](), [dashboard/src/services/api.ts:148-172](), [sdk/javascript/src/index.ts:55-84]()

---

## The Dashboard: Commanding your Army

The React-based dashboard operates as a single-page application built on top of a centralized API client with custom React hooks. 

### 1. Unified Authentication and Routing
Access to the dashboard is secured using dynamic API key checks. Upon entering the admin key, the React client validates it against `/api/auth/validate`, determines the user's role (`admin`, `user`, or `readonly`), and conditionally renders administration views such as API Key Management and Plugin configurations.

Sources: [dashboard/src/App.tsx:31-65](), [dashboard/src/App.tsx:96-116]()

### 2. Live Session Management & QR Synchronization
The **Sessions** panel is where WhatsApp web automation instances are provisioned, monitored, and decommissioned.

- **Status Monitoring**: Sessions transition through various lifecycle stages, including `created`, `idle`, `initializing`, `connecting`, `qr_ready`, `ready`, and `disconnected`.
- **WebSocket Synchronization**: Rather than spamming HTTP endpoints, the dashboard utilizes a custom WebSocket listener hook. Whenever a session connects (`ready`) or disconnects, the server pushes an `onSessionStatus` event, instantly displaying desktop toast notifications and updating the card state.
- **The QR Flow**: If a session is in the `qr_ready` state, the dashboard renders a QR modal that fetches the login QR string from the server. To keep the visual QR code valid (since WhatsApp login codes expire quickly), the dashboard sets up a `5-second polling interval` that fetches and refreshes the QR code until the phone is connected successfully.

```typescript
// dashboard/src/pages/Sessions.tsx:81-91
useEffect(() => {
  if (qrData) {
    currentSessionName.current = qrData.sessionName;
    qrRefreshInterval.current = setInterval(() => {
      fetchQR(qrData.sessionId);
    }, 5000);
  }
  return () => {
    if (qrRefreshInterval.current) clearInterval(qrRefreshInterval.current);
  };
}, [qrData, fetchQR]);
```
Sources: [dashboard/src/pages/Sessions.tsx:12-28](), [dashboard/src/pages/Sessions.tsx:29-43](), [dashboard/src/pages/Sessions.tsx:81-91](), [dashboard/src/pages/Sessions.tsx:431-507]()

---

## System Health & Infrastructure Monitoring

The **Infrastructure** page gives operators full visibility into system resources, performance metrics, and storage strategies, allowing runtime adjustments to the system's operational parameters.

| Subsystem Component | Supported Configurations / Options | Monitoring Metrics Provided |
| :--- | :--- | :--- |
| **Server Engine** | Environment (`production`, `development`), domain routing, public API & dashboard ports, and CORS origin bounds. | Public accessibility check, Node environment state. |
| **Database** | SQLite (zero-config, stored locally) or PostgreSQL (host, port, credentials, pool sizes up to 50, and SSL encryption toggles). | Schema migration status (`Active` / `Pending`), connection status. |
| **Redis Cache** | Toggle switches for enablement, built-in Redis, custom hosts/ports, and authentication passwords. | Connection health (`connected` / `disconnected`). |
| **BullMQ Queues** | Message delivery queues, Webhook event notification queues. | Real-time queue counters broken down by `pending`, `completed`, and `failed` jobs. |
| **Storage Engine** | Local directory path allocation or Amazon S3 bucket storage (bucket name, AWS region, secret/access credentials, custom endpoints). | Active storage strategy type. |

Sources: [dashboard/src/pages/Infrastructure.tsx:96-136](), [dashboard/src/pages/Infrastructure.tsx:701-768](), [dashboard/src/services/api.ts:87-97]()

### Triggering Server Restarts
When crucial configurations (like switching from SQLite to Postgres, or turning on Redis queues) are modified, they must be committed to the server's filesystem (`.env` file). Saving config triggers a safe restart command (`infraApi.saveConfig`), prompting a confirmation modal with an estimated countdown. The dashboard polls the health endpoint `/infra/health` to detect when the gateway is back online and reloads the web application interface.

```typescript
// dashboard/src/pages/Infrastructure.tsx:274-293
const checkServerHealth = async (stopCountdown?: () => void) => {
  let attempts = 0;
  const maxAttempts = 60;

  const check = async () => {
    try {
      await infraApi.healthCheck();
      stopCountdown?.();
      setRestartCountdown(0);
      setRestartStatus('success');
      setTimeout(() => window.location.reload(), 2000);
    } catch {
      attempts++;
      if (attempts < maxAttempts) setTimeout(check, 1000);
      else setRestartStatus('error');
    }
  };

  setTimeout(check, 3000);
};
```
Sources: [dashboard/src/pages/Infrastructure.tsx:211-237](), [dashboard/src/pages/Infrastructure.tsx:274-293](), [dashboard/src/services/api.ts:311-328]()

---

## The SDKs: Remote Control via Code

While the dashboard provides an interactive web user interface, the JavaScript/TypeScript and Python SDKs act as lightweight code gateways to programmatically control your session instances. 

Both SDK client configurations inject the `X-API-Key` header into outgoing network requests, offering direct object abstractions mapped onto the REST endpoints.

### 1. JavaScript / TypeScript Client
The JavaScript SDK is built on top of native `fetch` client protocols, utilizing TypeScript interfaces to enforce strict compilation-time types.

```typescript
// sdk/javascript/src/index.ts:66-82
get sessions() {
  return {
    list: () => this.request<Session[]>('GET', '/api/sessions'),
    get: (id: string) => this.request<Session>('GET', `/api/sessions/${id}`),
    create: (data: { name: string }) => this.request<Session>('POST', '/api/sessions', data),
    start: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/start`),
    stop: (id: string) => this.request<Session>('POST', `/api/sessions/${id}/stop`),
    delete: (id: string) => this.request<void>('DELETE', `/api/sessions/${id}`),
  };
}

get messages() {
  return {
    sendText: (sessionId: string, data: { chatId: string; text: string }) =>
      this.request<MessageResponse>('POST', `/api/sessions/${sessionId}/messages/text`, data),
  };
}
```
Sources: [sdk/javascript/src/index.ts:27-36](), [sdk/javascript/src/index.ts:55-82](), [sdk/README.md:15-27]()

### 2. Python Client
The Python SDK uses `httpx` to implement synchronous HTTP network operations, offering structured dataclasses for config and response payloads.

```python
# sdk/python/openwa/__init__.py:99-115
def list(self) -> list[dict]:
    return self._client._request("GET", "/api/sessions")

def get(self, session_id: str) -> dict:
    return self._client._request("GET", f"/api/sessions/{session_id}")

def create(self, name: str) -> dict:
    return self._client._request("POST", "/api/sessions", {"name": name})

def start(self, session_id: str) -> dict:
    return self._client._request("POST", f"/api/sessions/{session_id}/start")

def stop(self, session_id: str) -> dict:
    return self._client._request("POST", f"/api/sessions/{session_id}/stop")

def delete(self, session_id: str) -> None:
    self._client._request("DELETE", f"/api/sessions/{session_id}")
```
Sources: [sdk/python/openwa/__init__.py:67-92](), [sdk/python/openwa/__init__.py:95-131](), [sdk/README.md:36-48]()

---

## Summary

The combination of OpenWA's React Dashboard and modern client SDKs constitutes a robust Control Center. By handling session lifecycles, dynamic QR code refreshes, real-time WebSocket state synchronizations, and system configurations under a single unified API wrapper, the platform ensures that developers and DevOps teams can scale their automated WhatsApp communications with minimal effort and maximal operational oversight.

Sources: [dashboard/src/pages/Sessions.tsx:439-506](), [sdk/javascript/src/index.ts:112-113](), [sdk/python/openwa/__init__.py:20-22]()
