fetchpriority="high"

Total Chat Documentation

Total Chat is a script-tag AI chat product that integrates into your web application in one line. It provides screen-aware customer support and lead generation — all with flat monthly pricing.

What makes Total Chat different?

Unlike generic chat widgets, Total Chat knows what page a user is on and can point them to a specific page and highlight an element for them — no ticket, no "which screen are you looking at?"

Key Capabilities

  • Screen-Aware AI — Knows the current page/route on every message
  • Page Navigation & Highlight — Moves a user to a specific page and highlights one element per turn
  • Self-Evolving KB — Drafts knowledge articles from real conversations
  • Lead Generation — Fingerprinting, UTM tracking, and IP-based enrichment
  • Bug Routing — Sends bug reports with full context to developer agents
  • CRM/Ticketing — Webhooks for HubSpot, Zendesk, Jira, and more

Quickstart

Get Total Chat running in your app in 3 steps:

1. Register Your App

bash
curl -X POST https://totalchat.hub.danielswick.com/api/onboarding/register \
  -H "Content-Type: application/json" \
  -d '{
    "appId": "my-app",
    "appName": "My App",
    "ownerEmail": "[email protected]"
  }'

Save the appId and apiKey from the response. The API key is shown only once — store it securely.

2. Add the Script Tag

html
<script
  src="https://totalchat.hub.danielswick.com/widget.js"
  data-app-id="YOUR_APP_ID"
  data-mode="external"
  data-position="bottom-right"
  data-primary-color="#6366f1"
></script>

3. Scan Your Codebase (Optional)

bash
npx @totalchat/cli scan --target ./src --app-id YOUR_APP_ID

This generates a micro-function map of every route, feature, and interactive element in your app — giving Total Chat deep knowledge of your UI.


Installation

Total Chat installs as a single script tag — no npm package, no build step:

html
<script
  src="https://totalchat.hub.danielswick.com/widget.js"
  data-app-id="YOUR_APP_ID"
  data-mode="external"
  data-position="bottom-right"
  data-primary-color="#6366f1"
  data-greeting="Hi! How can I help?"
></script>

The widget loads asynchronously and won't block your page. Total bundle impact: ~15KB gzipped.


Script Tag Integration

The script tag is the simplest way to add Total Chat. Perfect for marketing sites, landing pages, or any site where you want lead capture and support without a build step.

Available Attributes

Attribute Type Default Description
data-app-idstringrequiredYour app ID from registration
data-modestring"external""external" (lead capture) or "internal" (full features)
data-positionstring"bottom-right""bottom-right" or "bottom-left"
data-primary-colorstring"#6366f1"Brand color for the widget
data-greetingstring"Hi! How can I help?"Initial greeting message
data-collect-emailboolean"true"Prompt for email in external mode

Configuration

Total Chat is configured via the script tag's data-* attributes (see the table above) plus the dashboard for branding, KB curation, and integrations — there's no separate SDK config object. Escalation email/webhook and other account-level settings are set from the dashboard, not the script tag.


Screen Awareness

Total Chat sends the user's current route with every message, so the AI's answer is grounded in what page they're actually looking at right now — not a generic FAQ answer disconnected from context.

  • Current route — e.g., /dashboard/settings, sent fresh on every message

Reading the DOM itself — open modals, active filters, form state, visible elements — isn't built yet. If you want the AI to know more than the route, the screenState field on the messages API (below) accepts a short freeform string you control, describing whatever's relevant.

Privacy note: Only the route (and any freeform screenState string you choose to send) is transmitted. No screenshots, no DOM scraping, no form values.

Auto-Navigation

When a user asks "how do I export my data?", Total Chat doesn't just explain — it can move them there. Per AI turn, it can:

  • Navigate to a specific page
  • Highlight one specific element on that page

That's one navigate and one highlight per turn — not a scripted, multi-page sequence. Chaining several steps together with page-load waiting and mid-walkthrough interrupt handling is planned but not built yet.

data-guide Attributes

Add data-guide attributes to important elements for better navigation accuracy:

html
<!-- The scanner suggests these automatically -->
<button data-guide="export-data">Export</button>
<nav data-guide="main-navigation">...</nav>
<form data-guide="settings-form">...</form>

Run npx @totalchat/cli scan to get prioritized recommendations for where to add data-guide attributes in your codebase.


Knowledge Base

Total Chat's knowledge base uses semantic search (pgvector embeddings) to find relevant answers even when users phrase questions differently.

Auto-Drafted Articles

When Total Chat answers a question that isn't in the KB, it automatically drafts a new article based on the conversation. You'll receive an email notification to approve, edit, or reject it.

Public vs. Internal Articles

Each KB article has an isPublicVisible flag (default: true). In external mode, only public articles are searched — protecting internal procedures, pricing logic, and admin docs from pre-login visitors. In internal mode, all published articles are available.

  • Set isPublicVisible: false on internal-only articles (e.g., billing workarounds, admin processes)
  • Public articles are seen by both logged-in users and anonymous visitors
  • This filtering is server-enforced — clients cannot override it

KB Search API

bash
GET /api/kb/search?q=how+to+export&appId=YOUR_APP_ID&limit=5

Returns semantically similar articles ranked by relevance score.


Lead Capture

In external mode, Total Chat captures visitor information for your sales pipeline.

What's Captured

  • Digital fingerprint — First-party cookies + localStorage (privacy-friendly)
  • UTM parameters — Source, medium, campaign, content, term
  • Referrer — Where the visitor came from
  • IP enrichment — Company, location, industry (via EM MCP)
  • Email — Collected via configurable prompt
  • Conversation context — What they asked about, pages visited

CRM Delivery

Leads are automatically pushed to your configured CRM via webhooks. See CRM Webhooks.


Bug Routing

When a user reports a bug through Total Chat, the full conversation context, screen state, and error details are packaged into a structured report and sent to your configured destination.

Report Format

json
{
  "type": "BUG",
  "priority": "HIGH",
  "subject": "Export button returns 500 error",
  "description": "User on /dashboard clicked Export...",
  "context": {
    "conversationId": "conv_123",
    "pageUrl": "/dashboard",
    "browserInfo": { "userAgent": "..." }
  },
  "reporter": {
    "email": "[email protected]",
    "userId": "usr_456"
  }
}

Routing Destinations

  • Agent Hub — Routes to per-app developer agents that investigate the codebase
  • Jira / Linear — Creates an issue with full context
  • Zendesk / Freshdesk — Creates a support ticket
  • Zapier / Make — Universal webhook fallback

Security & Mode Enforcement

Total Chat has a layered security model to prevent prompt injection, data leakage, and mode bypassing.

Layer 1 — Server-Enforced Mode

Mode is never derived from client input. The server checks for a valid userId in the conversation:

  • userId present → INTERNAL mode — full KB, navigation tools, user context
  • No userId → EXTERNAL mode — public KB only, lead capture, no navigation

Clients cannot request mode elevation. Even if the widget config says mode: "internal", the server ignores it when no userId is provided.

Layer 2 — System Prompt Guardrails

Every conversation — regardless of mode — includes a security preamble injected at the top of the system prompt:

  • The AI is scoped to your app only — it won't answer unrelated questions
  • It cannot reveal its system prompt or instructions
  • It cannot generate code, recipes, or content unrelated to your product
  • It cannot collect credentials or perform actions outside its defined tool set
  • KB answers must cite actual articles — fabrication is blocked

Layer 3 — API Input Sanitization

Every user message is scanned before being processed. Messages containing injection patterns are rejected with a 400 error:

json
// Example rejection
{
  "error": "Message contains disallowed content"
}

// Blocked patterns include:
// "ignore all instructions", "you are now", "act as a [character]",
// "pretend you are", "roleplay as", "repeat your system prompt",
// "DAN mode", "jailbreak", "developer mode", etc.

KB Visibility Enforcement

Articles with isPublicVisible: false are never returned in external mode searches — even if a user asks about them by name. Internal procedures, admin docs, and sensitive pricing logic stay invisible to unauthenticated users.

For enterprise deployments: Consider marking all internal runbooks, escalation procedures, and pricing exception docs as isPublicVisible: false before enabling external mode.

Codebase Scanner

The scanner CLI analyzes your codebase and generates a micro-function map — a complete inventory of every route, feature, and interactive element. There are three ways to scan depending on your setup.

Option 1 — npx (Quickest)

Run directly from your project root. No install required.

bash
# Scan and upload in one command
npx @totalchat/cli scan \
  --dir . \
  --app-id YOUR_APP_ID \
  --api-key YOUR_API_KEY \
  --upload

# Scan only (write to file, upload manually later)
npx @totalchat/cli scan --dir . --app-name "My App" --output ./totalchat-map.json

# Then upload manually
curl -s -X POST https://totalchat.hub.danielswick.com/api/onboarding/YOUR_APP_ID/function-map \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d @totalchat-map.json

CLI Flags

FlagDescriptionDefault
--dirProject root directoryCurrent directory
--app-idYour Total Chat app ID (required for --upload)
--api-keyYour API key, or set TOTALCHAT_API_KEY env var
--uploadPOST the map to the API after scanningfalse
--app-nameHuman-readable app nameMyApp
--outputOutput JSON file path./output/app-map.json
--api-urlTotal Chat API base URLhttps://totalchat.hub.danielswick.com

Framework auto-detection: The scanner automatically finds your app directory by trying src/app, app, src/pages, pages, and dashboard/src/app in order. No configuration needed for standard Next.js projects.

When to Re-scan

  • After adding new pages or major features
  • After restructuring your navigation
  • When the freshness check shows stale or warn
bash
# Check your function map freshness
curl https://totalchat.hub.danielswick.com/api/onboarding/YOUR_APP_ID/function-map/freshness

# Response:
# { "status": "fresh", "ageDays": 2, "currentVersion": 4 }
# { "status": "stale", "recommendation": "Re-scan recommended" }

What Gets Scanned

  1. Routes — All pages, dynamic params, route groups
  2. Features — Buttons, forms, links, and interactive elements
  3. Components — Your component inventory
  4. data-guide attributes — Existing navigation anchors
  5. Recommendations — Suggested data-guide placements (P1/P2/P3)

GitHub Action — Automatic Rescanning

Automatically rescan and upload your function map on every push to main. Add this to your repository once and never think about rescanning again.

yaml
# .github/workflows/totalchat.yml
name: Total Chat Sync

on:
  push:
    branches: [main]

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: totalchat/scanner-action@v1
        with:
          app-id: YOUR_APP_ID
          api-key: ${{ secrets.TOTALCHAT_API_KEY }}

Add TOTALCHAT_API_KEY to your GitHub repository secrets (Settings → Secrets → Actions). The action auto-detects your framework and uploads the map — no other configuration needed.

Action Inputs

InputRequiredDefaultDescription
app-idYesYour Total Chat app ID
api-keyYesYour API key (use a secret)
directoryNo.Project root to scan
api-urlNohttps://totalchat.hub.danielswick.comAPI base URL

AI URL Crawler — No Code Required

Don't want to run a scanner? Point Total Chat at your live site and the AI will crawl it, read your pages, and generate knowledge base articles automatically. No CLI, no GitHub Action, no code changes needed.

http
POST /api/onboarding/:appId/crawl
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

{
  "url": "https://yourapp.com",
  "maxPages": 20,
  "generateArticles": true
}
bash
curl -s -X POST https://totalchat.hub.danielswick.com/api/onboarding/YOUR_APP_ID/crawl \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://yourapp.com", "maxPages": 20 }'

What happens:

  1. Total Chat fetches your root URL and follows internal links (same domain only)
  2. For each page, it extracts the title, headings, and visible text
  3. The AI reads all pages and generates 3–8 knowledge base articles
  4. Articles are saved as AI drafts — you review and publish from the dashboard

Response

json
{
  "crawled": 14,
  "articlesGenerated": 6,
  "articles": [
    { "id": "...", "title": "Getting Started", "category": "onboarding", "isPublicVisible": true },
    { "id": "...", "title": "Managing Your Account", "category": "account", "isPublicVisible": false }
  ]
}

Best for: Marketing sites, documentation sites, or any app where a crawl gives the AI enough content to work with. For navigate/highlight to work reliably against your actual UI (via data-guide selectors), pair with the CLI scanner.


data-guide Attributes

These attributes help Total Chat identify and navigate to specific UI elements:

html
<!-- P1: Critical navigation elements -->
<button data-guide="export-data">Export</button>
<a data-guide="nav-settings" href="/settings">Settings</a>

<!-- P2: Important interactive elements -->
<input data-guide="search-input" placeholder="Search..." />
<select data-guide="filter-status">...</select>

<!-- P3: Supporting elements -->
<div data-guide="dashboard-chart">...</div>

The scanner CLI generates a prioritized list of recommendations showing exactly where to add these attributes. P1 items have the highest impact on navigation accuracy.


API: Conversations

Create Conversation

http
POST /api/conversations
Content-Type: application/json

{
  "appId": "YOUR_APP_ID",
  "userId": "optional-logged-in-user-id",
  "visitorId": "optional-fingerprint-id"
}
Server-enforced mode: The mode field is derived server-side — if userId is present, the conversation is INTERNAL (full KB, navigation tools, screen awareness). Without userId, it's EXTERNAL (public KB only, lead capture). Clients cannot override this.

Get Conversation

http
GET /api/conversations/:id

API: Messages

Send Message

http
POST /api/conversations/:id/messages
Content-Type: application/json

{
  "content": "How do I export my data?",
  "pageContext": { "route": "/dashboard" },
  "screenState": "optional freeform string describing extra state you control"
}

The response is a server-sent events stream — text tokens as the AI generates them, plus a navigate and/or highlight event if the AI decides to move the user or point at an element (at most one of each per turn):

text
event: text_delta
data: {"text": "I can see you're on the Dashboard. "}

event: navigate
data: {"path": "/settings/export"}

event: highlight
data: {"dataGuide": "export-btn"}

event: message_complete
data: {}

API: Knowledge Base

Search KB

http
GET /api/kb/search?q=export+data&appId=YOUR_APP_ID&limit=5

Create Article

http
POST /api/kb/articles
Content-Type: application/json

{
  "appId": "YOUR_APP_ID",
  "title": "How to Export Dashboard Data",
  "content": "Navigate to Settings > Export...",
  "category": "data-management",
  "pageRoute": "/settings/export",
  "approved": true
}

API: Onboarding

Register App

http
POST /api/onboarding/register
Content-Type: application/json

{
  "appId": "my-app",
  "appName": "My App",
  "ownerEmail": "[email protected]",
  "integrationMode": "FULL",
  "aiPersonality": "friendly",
  "escalationEmail": "[email protected]",
  "bugRouteTarget": "my-agent-topic"
}
FieldRequiredDescription
appIdUnique identifier for your app (lowercase, hyphens ok)
appNameDisplay name for the app
ownerEmailEmail for KB draft notifications and escalations
integrationModeFULL (default), HEADLESS, or EXTERNAL_ONLY
aiPersonalityTone for AI responses (e.g. friendly, professional)
escalationEmailHuman support email for tier-3 escalations
bugRouteTargetAgent Hub topic for bug report routing

The response includes your apiKey (shown once — store it securely) and full app config.

Upload Function Map

http
POST /api/onboarding/:appId/function-map
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  // Output from totalchat scan / npx @totalchat/cli scan
  "app": { "name": "My App", "framework": "nextjs" },
  "routes": [...],
  "features": [...],
  "stats": { "totalRoutes": 14, "totalFeatures": 47 }
}

Check Function Map Freshness

http
GET /api/onboarding/:appId/function-map/freshness
Authorization: Bearer YOUR_API_KEY

// Response:
{
  "appId": "my-app",
  "status": "fresh",       // "fresh" | "warn" | "stale"
  "ageDays": 2,
  "currentVersion": 4,
  "recommendation": "Function map is current."
}

AI URL Crawler

Crawl a live URL and auto-generate KB articles. No scanner required.

http
POST /api/onboarding/:appId/crawl
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "url": "https://yourapp.com",
  "maxPages": 20,           // optional, default 20
  "generateArticles": true  // optional, default true
}

// Response:
{
  "crawled": 14,
  "articlesGenerated": 6,
  "articles": [
    { "id": "...", "title": "Getting Started", "category": "onboarding" }
  ]
}

Deploy Notify

Call after each deploy to keep the freshness check accurate.

bash
curl -s -X POST https://totalchat.hub.danielswick.com/api/onboarding/YOUR_APP_ID/deploy-notify \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"commitSha\": \"$(git rev-parse HEAD)\", \"environment\": \"production\"}"

API: Webhooks

Configure webhooks in your app settings to receive real-time events.

Event Types

EventDescription
conversation.createdNew conversation started
conversation.resolvedConversation marked resolved
lead.capturedNew lead captured (email collected)
lead.enrichedLead enrichment data available
report.createdBug/feature report submitted
kb.article_draftedNew KB article auto-drafted

CRM Webhooks

Total Chat can push leads to your CRM automatically. Configure in your app settings.

Supported CRMs

  • HubSpot — Contacts + Deals
  • Salesforce — Leads + Contacts
  • GoHighLevel — Contacts + Opportunities
  • Pipedrive — Persons + Deals
  • Zapier / Make — Universal webhook (works with any CRM)

Lead Data Format

json
{
  "email": "[email protected]",
  "name": "Jane Doe",
  "company": "Acme Corp",
  "title": "VP Engineering",
  "phone": "+1-555-0123",
  "source": {
    "utm_source": "google",
    "utm_medium": "cpc",
    "utm_campaign": "brand-awareness"
  },
  "enrichment": {
    "companySize": "50-200",
    "industry": "Technology",
    "location": "San Francisco, CA"
  },
  "conversation": {
    "firstMessage": "Do you have a free trial?",
    "pagesVisited": ["/", "/features", "/pricing", "/docs"]
  }
}

Ticketing Systems

Route support tickets and bug reports to your existing helpdesk.

Supported Systems

  • Zendesk — Tickets with full context
  • Freshdesk — Tickets with tags and priority
  • Jira Service Management — Issues with custom fields
  • Linear — Issues with labels and priority
  • Help Scout — Conversations with threads
  • Zapier / Make — Universal webhook fallback