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). OnlyPUT /company/:_id/bot-flow-enabled(CompanyController.setBotFlowEnabled, super admin) writes it; the tenantupdate()strips the key (stripBotFlowFlag).- Admin UI: admin company detail → Bot Flow Builder switch.
- Agency-wide (backend
4245f7061, frontend15dae45e): 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). Storesagencies.bot_flow_enabledand bulk-writescompanies.bot_flow_enabledon every client sub-account (notagency_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 vialib/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.vueonly whencompany.bot_flow_enabled === true(the standaloneai-bot-flowsettings menu item was removed). Every owner endpoint returns 403Bot flow builder is not enabled for this accountwhen off. - ms-communication mirrors the flag on its CompanyModel (read-only) to gate the
bot-flow-stepevent andbot_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):
| Field | Notes |
|---|---|
name | default "My bot flow", 1–120 chars |
status | draft | published |
draft / published | Flow JSON (Mixed). The widget runs published; webhook payloads are built ONLY from published. |
published_at | |
webhook_secret_enc / webhook_bearer_enc | SecretCrypto 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(unlessreturn_to_flow),human_handoff,end. - Handles:
outfor start/message/ask_text/send_data/link_button;ask_buttons→opt:<optionId>per option +default(typed answer);condition→yes/no;ai_handoff→outonly whendata.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_handoffdata: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 + path | Purpose |
|---|---|
GET /bot-flows | the flow or null |
POST /bot-flows | create (409 if one exists) |
PUT /bot-flows/:id | save name / draft (structural validation) |
POST /bot-flows/:id/publish · /unpublish | full validation → published copy |
POST /bot-flows/import | Flow JSON or a simple question list → draft (not saved) |
POST /bot-flows/:id/webhook-secret/rotate | returns { secret } once, stored encrypted |
PUT /bot-flows/:id/webhook-bearer | { token }, '' clears |
POST /bot-flows/:id/test-webhook | one signed sample delivery to a send_data node's URL |
GET /bot-flows/:id/submissions?page= | 20 per page |
GET /bot-flows/public/:company_id | public — published flow, webhook_url stripped (sanitizePublicFlow) |
POST /bot-flows/public/:company_id/submissions | public, 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 === trueand awebhook_url. Payload built server-side bybuildPayload(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 todeliveries.
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.tsloadsGET /bot-flows/public/:company_idonly whencompany.bot_flow_enabled; 404/network → normal widget behaviour.runner.tsis the pure engine;botFlowActivemakes typed input go to the runner.- Renders N/total progress, validation re-asks, branching, link buttons, typing loader,
on_buttonstart button. send_data: POSTs the public submission, and fordestinations.host_pagesendswindow.parent.postMessageto the exactallowed_originonly (services/postMessage.ts).- AI steps send a normal widget message; with
suggest_optionsthe message carriesbot_flow_suggest: true. ms-communication appendsBOT_FLOW_SUGGEST_DIRECTIVEto 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 —
POSTreturns 409 on a duplicate (unique index). - Saving a draft never changes what the widget runs; only Publish does. Unpublishing sets status back so
publicShow404s. - 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.
Related
- Chat Agent — what
ai_handoffhands to. - ms-communication service · Widget service