xai-chatbotv2.php

A PHP/HTML file that renders and powers the “Howie!” AI chat widget. It verifies user sessions, outputs the chat UI, and initializes the front‐end ChatManager to communicate with the backend via WebSocket and REST APIs.


🚀 Purpose

  • Embed an AI chat interface as a fixed, responsive widget
  • Authenticate users via PHP sessions
  • Bootstrap JavaScript logic for messaging, file upload, screenshots, and screenshare

🔐 Session & Authentication

Ensures only logged‐in users access the chat:

<?php
if (empty($_SESSION['user_id'])) {
    die("Unauthorized access");
}

— terminates execution if no valid user_id exists.


⚙️ Initial Configuration

Fetches session data and outputs JavaScript config:

$user_id       = htmlspecialchars($_SESSION['user_id'], ENT_QUOTES, 'UTF-8');
$customer_email= htmlspecialchars($_SESSION['Customer_email'], ENT_QUOTES, 'UTF-8');
$customer_id   = htmlspecialchars($_SESSION['Customer_ID'], ENT_QUOTES, 'UTF-8');
$company_code  = htmlspecialchars($_SESSION['company_code'], ENT_QUOTES, 'UTF-8');
var config = {
  apiUrl: 'https://trynew.techlogistics.com:2053',
  wsUrl:  'wss://trynew.techlogistics.com:2053',
  userId:      <?php echo json_encode($user_id); ?>,
  customerEmail: <?php echo json_encode($customer_email); ?>,
  customerId:    <?php echo json_encode($customer_id); ?>,
  locationCode:  <?php echo json_encode($company_code); ?>,
  defaultTraining:'Intro/hi/hello/wussup/hey/howie/Howie'
};

— readies endpoints and user context.


🖥️ Chat UI Structure

The HTML skeleton consists of:

  • #chatContainer: fixed, flex‐column widget
  • .chat-header: title, connection status, retry/close buttons
  • #chatMessages: scrollable message list
  • #typingIndicator: live “typing…” UI
  • #chatInput: textarea, send button, file/screen/share controls
  • Action buttons: attach file, screenshot, live assistance, screenshare
<div id="chatContainer">
  <div class="chat-header">…</div>
  <div id="chatMessages"></div>
  <div id="typingIndicator"></div>
  <div id="chatInput">…</div>
</div>

🎨 Styling Highlights

A modern, mobile‐friendly look:

Selector Description
.message.user Blue bubble for user messages
.message.bot White bubble for AI responses
.message.agent Yellow bubble for human agents
.message.system Centered, italicized system notes
#chatContainer Gradient background, rounded corners
Media query (320–425px wide) Shrinks widget for smartphones

All styles defined inline in <style> block.


📦 ChatManager Class

Central JS controller managing:

  • WebSocket lifecycle: connect, heartbeat, reconnect
  • REST calls: send message, fetch history, upload files
  • UI rendering: displayMessage, typing indicator
  • State persistence: localStorage for chatId/training
  • Screenshare via WebRTC (RTCPeerConnection)

Key Methods

  • loadSetup() / saveSetup()
  • connectWebSocket()
  • displayMessage(data)
  • sendMessage(msg, sender, needsAssistance, originalName, screenshot)
  • uploadFile(file)
  • fetchMessages()
  • initializeChat()
  • stopScreenshare()
  • debounce(func, wait) / retryFetch(url, options, retries, delay)
ChatManager.prototype.sendMessage = function(message, sender = 'user', needsAssistance = false) {
  // sanitize, prepare payload, POST to /api/chat  
  fetch(config.apiUrl + '/api/chat', { ... })
    .then(...)
    .catch(...);
};

🔄 WebSocket Flow

  1. onopen: reset retries, update status, start heartbeat
  2. onmessage: handle type values:
    • message: render new chat message
    • typing / processing: show typing indicator
    • system: show system notification
    • answer / candidate: handle WebRTC signaling
  3. onclose: schedule reconnect with exponential backoff
  4. onerror: log and notify user

🧹 Message Rendering & Sanitization

  • Parses markdown-style bold (**bold**)
  • Converts newlines to <br>
  • Uses DOMPurify to sanitize HTML, allowing safe links and tables
  • Embeds file links with icons via getFileIcon(ext)
const sanitizedMessage = DOMPurify.sanitize(formattedMessage, { USE_PROFILES: { html: true } });

📎 File Upload & 📸 Screenshot

  • File attachment: <input type="file"> → uploadFile(file)
  • Screenshot: captureScreenshot() uses html2canvas on parent page
  • Share Screen: RTCPeerConnection tracks and streams display
  • Human Assistance: toggles action buttons and flags needsAssistance=true

🔗 Embedding & Integration

This chat widget is injected into the page via iframe in xai.php:

<iframe
  src="/xai-chatbotv2.php"
  width="100%" height="100%"
  frameborder="0"
  sandbox="allow-same-origin allow-scripts allow-popups allow-downloads">
</iframe>

📊 Chat Flow Sequence

sequenceDiagram
  participant User
  participant UI as ChatManager
  participant REST as /api/chat
  participant WS  as WebSocket

  User->>UI: Enter text & click send
  UI->>REST: POST /api/chat { message, userId, ... }
  REST-->>UI: { chatId, ... }
  UI->>WS: WebSocket send message
  WS-->>UI: { type: "message", sender:"bot", message: "Hello!" }
  UI->>UI: displayMessage(data)

🧩 Dependencies

  • jQuery 3.6.0
  • html2canvas 1.4.1
  • toastr.js for notifications
  • DOMPurify 2.4.0 for sanitization
  • WebRTC APIs for screenshare

End of Documentation