Skip to main content

Bot Flow Builder

Audience: Sales · Management · QA · Support · Engineering · Where in app: Settings → AI Agents → Chat Agent → Bot Flow tab (/settings/ai/agents?agent=chat-agent&tab=botflow; the old /settings/ai/bot-flow route redirects there) · Gate: companies.bot_flow_enabled (super-admin only)

The Bot Flow Builder (shipped 2026-10-05, "contract v1") lets a tenant draw the questions the chat widget asks, branch on answers, mix in AI answers, and deliver the collected variables to their own site (postMessage) or a webhook. It replaces the legacy chatbot flow chart — ChatBotModel / /chat-bots routes still exist in the backend but the old views/settings/chatbot/FlowChart page is no longer routed.

Gate​

  • companies.bot_flow_enabled (Boolean, default false). Only PUT /company/:_id/bot-flow-enabled (CompanyController.setBotFlowEnabled, super admin) writes it; the tenant update() strips the key (stripBotFlowFlag).
  • Admin UI: admin company detail → Bot Flow Builder switch.
  • Agency-wide (backend 4245f7061, frontend 15dae45e): admin agency detail → Bot Flow Builder ("Allow the Bot Flow Builder for every sub-account of this agency") → PUT /agencies/admin/:agency_id/bot-flow-enabled { enabled } (AgencyController.adminSetBotFlow, super admin). Stores agencies.bot_flow_enabled and bulk-writes companies.bot_flow_enabled on every client sub-account (not agency_self_account, not playgrounds) — turning it off also switches off sub-accounts enabled one by one; flows are kept. New sub-accounts inherit the switch via lib/agencySubAccountFlags.inheritAgencyFlags (Add Client, attach, signup page, Platform API). The flag stays per company — that is what backend, ms-comm and the widget check.
  • The dashboard shows the Bot Flow tab in ChatAgent/index.vue only when company.bot_flow_enabled === true (the standalone ai-bot-flow settings menu item was removed). Every owner endpoint returns 403 Bot flow builder is not enabled for this account when off.
  • ms-communication mirrors the flag on its CompanyModel (read-only) to gate the bot-flow-step event and bot_flow_suggest. The widget only fetches the flow when the flag is true.

Data model​

bot_flows (BotFlowModel, audit plugin) — one per company (company_id unique):

FieldNotes
namedefault "My bot flow", 1–120 chars
statusdraft | published
draft / publishedFlow JSON (Mixed). The widget runs published; webhook payloads are built ONLY from published.
published_at
webhook_secret_enc / webhook_bearer_encSecretCrypto AES-256-GCM blobs, select: false; responses only expose has_webhook_secret / has_webhook_bearer.

bot_flow_submissions (BotFlowSubmissionModel) — flow_id, company_id, user_session_id, data (only variables the published flow defines, strings ≤ 2000), status (completed | partial), send_node_id, page_url, deliveries[] ({ destination, delivery_id, attempt, status, ok, error, at }), ip_hash (sha256 of IP, select: false). Index { company_id: 1, created_at: -1 }.

user_sessions.bot_flow_data — { last_node_id, updated_at }, written by ms-communication on each step.

Flow JSON (v1)​

backend/app/lib/botFlow/constants.js is the authority; the dashboard (flowSchema.js) and widget (services/botFlow/validators.ts) enforce the same numbers.

  • { version: 1, settings, nodes[], edges[] }. Limits: 300 nodes, 600 edges, 500 KB JSON, text 2000, labels 120.
  • Node types: start, message, ask_text, ask_buttons, condition, send_data, link_button, ai_handoff, human_handoff, end. Terminal: ai_handoff (unless return_to_flow), human_handoff, end.
  • Handles: out for start/message/ask_text/send_data/link_button; ask_buttons → opt:<optionId> per option + default (typed answer); condition → yes/no; ai_handoff → out only when data.return_to_flow === true.
  • Validations: text, email, phone, number, address. Operators: equals, not_equals, contains, gt, lt, is_empty, is_not_empty.
  • Settings defaults: { show_progress: true, trigger: 'on_open' | 'on_button', start_button_label: 'Get started', ai_fallback: false }.
  • ai_handoff data: return_to_flow, suggest_options (AI follow-up buttons), answer (owner-written fixed reply instead of the AI).

validateFlow.js runs structural checks on save (PUT) and full checks on publish: one start, unique variables, every output connected exactly once, every node reachable from start, send_data mapping only references defined variables, link_button URL http(s). Errors are { node_id, field, message }; the page jumps to the first broken node.

API​

Routes in backend/app/routes/botFlowRoutes.js (separate from legacy chatBotRoutes). Owner routes use passport; company resolved owner / member / agency-staff (agency_self_account) like AiAgentAuthenticationController.

Method + pathPurpose
GET /bot-flowsthe flow or null
POST /bot-flowscreate (409 if one exists)
PUT /bot-flows/:idsave name / draft (structural validation)
POST /bot-flows/:id/publish · /unpublishfull validation → published copy
POST /bot-flows/importFlow JSON or a simple question list → draft (not saved)
POST /bot-flows/:id/webhook-secret/rotatereturns { secret } once, stored encrypted
PUT /bot-flows/:id/webhook-bearer{ token }, '' clears
POST /bot-flows/:id/test-webhookone signed sample delivery to a send_data node's URL
GET /bot-flows/:id/submissions?page=20 per page
GET /bot-flows/public/:company_idpublic — published flow, webhook_url stripped (sanitizePublicFlow)
POST /bot-flows/public/:company_id/submissionspublic, rate limited — see below

Public submit requires flow_id = the published flow, a user_session_id that is a real user_sessions row of that company, status completed/partial, collected object. Values for undefined variables are dropped. botFlowRateLimiter (Redis if available, else memory): 30/min per IP, 10/min per user_session_id.

Webhook delivery (lib/botFlow/webhookDelivery.js)​

  • Fired async after a submission when the send node has destinations.webhook === true and a webhook_url. Payload built server-side by buildPayload(mapping, data, system) from the PUBLISHED mapping — the client payload is never trusted.
  • SSRF guard: https only; host resolved and every address must be public (private, CGNAT, loopback, link-local/metadata, NAT64, 6to4, Teredo, ULA… blocked); the connection is pinned to the vetted IP via a custom lookup (no DNS rebind); redirects are failures.
  • Headers: User-Agent: KnockKnock-BotFlow/1, X-KK-Signature: sha256=<HMAC-SHA256(secret, timestamp + "." + rawBody)> when a secret is set, Authorization: Bearer … when a bearer is set; timestamp + signature fresh per attempt.
  • 10 s timeout, 3 attempts (backoff 1 s, 4 s), response read capped at 64 KB. Every attempt is $pushed to deliveries.

Payload shape (buildPayload, mirrored in the widget and dashboard): { type: envelope_type || 'knockknock:bot_flow_submit', data: { [wrapper_key || 'mapped']: {…rows + static}, conversationId?, submittedAt?, pageUrl?, flowName? } }. mapping.nested deep-sets dotted keys; __proto__/prototype/constructor segments are refused.

Widget runtime (widget/src/services/botFlow/)​

  • widgetController.ts loads GET /bot-flows/public/:company_id only when company.bot_flow_enabled; 404/network → normal widget behaviour. runner.ts is the pure engine; botFlowActive makes typed input go to the runner.
  • Renders N/total progress, validation re-asks, branching, link buttons, typing loader, on_button start button.
  • send_data: POSTs the public submission, and for destinations.host_page sends window.parent.postMessage to the exact allowed_origin only (services/postMessage.ts).
  • AI steps send a normal widget message; with suggest_options the message carries bot_flow_suggest: true. ms-communication appends BOT_FLOW_SUGGEST_DIRECTIVE to the system prompt so the AI ends with [[options: A | B | C]]; the widget parses it (optionsMarker.ts, regex tightened 2026-10-06) and ms-comm strips it (stripBotFlowOptions) before saving the reply.
  • ai_fallback: a typed side question gets one AI reply, then the question repeats.

Transcript (ms-communication bot-flow-step)​

app/helpers/BotFlowStepHelper.js. The widget emits bot-flow-step { user_session_id, company_id, node_id, bot_text?, answer? } for every prompt/answer. The helper validates ids, refuses a socket writing into another session (session_mismatch), checks the session belongs to the company and bot_flow_enabled, then persists bot_text as sender chatbot and answer as the visitor through saveChatMessage, broadcasts message to the session room (excluding the sender) and new-session-message to the company room, and sets bot_flow_data. Never calls the AI, never charges credits.

Dashboard (frontend/src/views/settings/ai/botFlow/)​

Pinia store store/botFlow.js; Vue Flow canvas (BotFlowCanvas.vue), palette, NodeInspector.vue, PayloadEditor.vue, TestPanel.vue (client-side flowRunner.js, AI steps simulated, no network submit), SubmissionsTab.vue, ImportDialog.vue. Templates (templates.js): Blank, Copilot bot (recommended), Lead intake (10 questions). Undo/redo, auto-layout, JSON import/export.

Gotchas​

  • One flow per company — POST returns 409 on a duplicate (unique index).
  • Saving a draft never changes what the widget runs; only Publish does. Unpublishing sets status back so publicShow 404s.
  • Webhook URLs are never sent to the browser; the public flow is sanitised.
  • Tests: backend/test/bot-flow.spec.js, ms-communication/test/bot-flow-step.test.js, widget/src/services/botFlow/__tests__/botFlow.test.ts, frontend/.../botFlow/botFlow.test.js.