# Webhook-started conversational chatbots with human-in-the-loop (HITL) — Design

- **Status:** approved design (brainstorming), v1 and §11 implemented; §12 (known-limit corrections and pre-branch ports) approved 2026-09-29, ready for implementation planning
- **Date:** 2026-09-15
- **Feature branch (all repos):** `feature/webhook-chatbot-hitl`, created from each repo's default branch
- **Related:** [`../todo/2026-09-14-webhook-chatbot-shared-code-fixes.md`](../todo/2026-09-14-webhook-chatbot-shared-code-fixes.md) (out-of-scope fixes found during design)

| Repo | Base branch | Verified at |
|---|---|---|
| tiledesk-server | `master` | `5d240683` (2.24.2) |
| tiledesk-chatbot (tybot, `tybotRoute/`) | `main` | `ce06bf8e` (2.1.13) |
| design-studio | `master` | `c5972d94` (1.40.14) |
| chat21-ionic | `master` | `a7894025` (3.4.35) |
| tiledesk-dashboard | — | not modified |

All `file:line` references below were verified on these commits.

---

## 1. Problem

Today only **automation** chatbots (`faq_kb.subtype: 'webhook'`) can be started by a webhook. They run
headless (`automation-request-…` ids, tybot `/block` endpoint) and cannot hold a conversation with a human.

We need a **conversational** chatbot (`subtype: 'chatbot'`) that can be started **either** by an end user
through the web widget **or** by an external event through a webhook, and that — once started by the
webhook — can **pause and ask a platform user** (project agent/admin, not an external lead) for
human-in-the-loop feedback in the platform chat, then **resume** with that answer.

Reference use case (AIOps): Grafana alert → webhook → flow enriches and triages → invites an on-call
engineer → asks "Restart checkout-api? [Approve] [Reject]" → engineer answers in the agent chat → flow
remediates or escalates.

### Why the current platform can't do it
- **Agent Handoff removes the bot.** `requestService.routeInternal` replaces the participant list with the
  routed agent (`services/requestService.js:166-240`), so the flow can never resume.
- **The support chat assumes an external requester (lead)** and a bot-owned conversation notifies nobody.
- **Auto-close kills waiting conversations.** On stage both close jobs are enabled with a 20-minute timeout
  (`tiledesk-config`: `CLOSE_*_UNRESPONSIVE_REQUESTS_AFTER_TIMEOUT=1200000`).

## 2. Goals / non-goals

**Goals**
1. Webhook option on the **start block** of a conversational chatbot; the webhook call starts the flow
   exactly like the widget does (start block, same runtime path).
2. A flow action **Invite human** that adds platform user(s) to the conversation **while the bot stays**.
3. Platform users answer in **chat21-ionic**; the flow resumes with their answer (free text or buttons).
4. Conversations waiting for a human are **not auto-closed**.
5. Design Studio support: toggle, URLs, action, and a way to test the webhook start.

**Non-goals (v1)**
- Changes to automation (`subtype: 'webhook'`) behaviour, sync `web_response` for chatbots.
- Deduplication/correlation of repeated webhook calls (every call opens a new conversation).
- A dedicated all-in-one "Ask human" action, a "release human" action, lead mapping from payload.
- Changes to the dashboard Monitor view, push notifications, canned responses / Copilot behaviour.
- The shared-code fixes listed in the TODO file.

## 3. Decisions (from brainstorming)

| # | Decision |
|---|---|
| D1 | HITL surface = **chat21-ionic** (stage runs `chat21/chat21-ionic:3.4.35-rc2` at `/chat/`; dashboard `CHAT_BASE_URL=/chat/`). Monitor stays for context/history. `tiledesk-agent-chat` (`/agent/`) is the agent-runtime UI and is not involved. |
| D2 | Webhook is an option **on the start block**; enabling it creates the webhook endpoint if missing. The call starts the **normal flow as the widget** would (system `/start` → start block). |
| D3 | Requester = **synthetic source lead** per webhook (no external user). |
| D4 | Who answers: **department + explicit override**. Department → **one** available agent. Explicit `members` → **all** named people. |
| D5 | Flow building block: **new "Invite human" action + reuse** Reply V2 / Capture User Reply for the question. |
| D6 | Architecture: **server starts the conversation and performs invites**; tybot only calls the server. |
| D7 | Webhook calls for chatbots are **async only** (`202 {request_id}`). |
| D8 | Waiting conversations are **protected from auto-close** via `workingStatus: 'pending'` until a human answers. |
| D9 | Shared-code fixes (department dropped on create, `hasBot` forced false, tybot `main` lock issues, pre-existing webhook bugs) are **not** part of v1; tracked in the TODO file. |
| D10 | Development starts from each repo's default branch on `feature/webhook-chatbot-hitl`. |
| D11 | **Backward compatibility:** the conversation path is selected by an explicit `webhook.mode === 'conversation'` (set by the start-block toggle), **not** by the bot subtype. Webhooks without `mode` keep today's automation behaviour for every bot subtype (existing chatbot-subtype webhooks, e.g. the AIOps PoC, and test `run-published-webhook` rely on it). |

## 4. Architecture and end-to-end flow

```
Design Studio: start block → "Webhook" toggle ON
  → POST /:projectid/webhooks {chatbot_id, block_id: <start intent_id>, mode: 'conversation'}   (only if none exists)
  → shows production + development URLs

External system ── POST /webhook/:webhook_id  {payload}
  ▼ tiledesk-server
  1. load webhook → mode 'conversation' (bot subtype 'chatbot') → conversation path
     (no mode → existing automation path, unchanged for every bot subtype)
  2. enabled check, rate limit ('webhook' bucket)
  3. upsert source lead  lead_id 'webhook_<webhook_id>'
  4. requestService.create: request_id support-group-<project>-<uuid>
       participants ['bot_<chatbot_id>'] → status ASSIGNED (s_invite_bot_01 does not fire)
       channel {name:'webhook'} (channelOutbound defaults to chat21 → chat21 group created)
       attributes {webhook_id, payload:{...body, webhook_http_method, webhook_query_params}}
       dev: attributes.sourcePage contains '&td_draft=true' → draft bot, quota skipped
  5. set request.department (targeted update; create drops it when participants are passed)
  6. messageService.send('system','Bot',request_id,'/start',id_project,null,{subtype:'info',updateconversation:false})
  7. 202 {success:true, request_id}
  ▼ normal path: botEvent → BotSubscriptionNotifier → tybot /ext → start block
flow … Invite human {department and/or members}
  ▼ tiledesk-server POST /:projectid/requests/:request_id/participants/invite
     pick agent(s) → addParticipant (bot stays) → chat21 group join → email
     workingStatus 'pending' + attributes.hitl_waiting
  ▼ flow: Reply V2 "Restart? [Approve] [Reject]"   (locks, optional no-input timeout)
platform user in chat21-ionic clicks/types
  → message → botEvent → /ext → Reply V2 resumes (lastUserMessage.sender = responder)
  → server resets workingStatus 'open' (human participant message while hitl_waiting)
```

Existing mechanics this relies on (verified):
- Widget start: trigger `s_invite_bot_01` (`pubmodules/trigger/default.js:115-135`) → action
  `request.department.bot.launch` → reroute + system `/start` info message (`pubmodules/trigger/rulesTrigger.js:717-785`, send at `:765-773`).
- `botEvent` passes system messages only for `\start` / `/start`; bot resolved from `participants`
  (`event/botEvent.js:50-56`, `getBotId` `:212`).
- tybot resolves `/start` by intent name `start` (`tybotRoute/engine/TiledeskChatbot.js:135-140`,
  `engine/MongodbBotsDataSource.js:93-101`); `/ext` does not skip info messages (`tybotRoute/index.js:45-237`).
- tybot merges `request.attributes.payload` into flow variables: each key + `payload`
  (`tybotRoute/utils/TiledeskChatbotUtil.js:850-869`).
- Draft routing: `BotSubscriptionNotifier` switches to the draft bot when `request.attributes.sourcePage`
  contains `&td_draft=true` (`services/BotSubscriptionNotifier.js:30-34`); `requestService.create` skips
  quota for `td_draft=true` (`services/requestService.js:583`).
- chat21 group creation gated on `channelOutbound.name === 'chat21'` (`channels/chat21/chat21Handler.js:527-532`);
  participant join → `chat21.groups.join` (`:813-842`); messages carry `attributes.request_channel` (`:329`).

**Distinguishing webhook vs widget start inside the flow:** both enter the start block. Webhook starts
have the `webhook_http_method` (and `payload`) variables set; widget starts don't. Flow designers branch
on `webhook_http_method` (documented in the DS start-block webhook section).

## 5. tiledesk-server

### 5.1 Webhook record and management — `models/webhook.js`, `routes/webhooks.js`
- New optional fields on `WebhookSchema` (`models/webhook.js:5-44`):
  - `mode: String`, enum `['conversation']` — absent = automation (today's behaviour). Only `'conversation'`
    selects the new path (D11).
  - `department_id: String` — department for created conversations (default: project default department).
  - `source_name: String` — display name of the source lead (default: webhook `name`).
- `POST /` (`routes/webhooks.js:67-93`): validate that `chatbot_id` exists in `req.projectid` and is not
  trashed (404 otherwise). Accept `mode`, `department_id`, `source_name`. When `mode === 'conversation'`:
  the bot must be subtype `chatbot` (422 otherwise); if `block_id` is omitted resolve it to the intent named
  `start` (422 if not found); `async` is ignored. Without `mode` the behaviour is unchanged.
- `PUT /:chatbot_id` (`:182-212`) and `PUT /update/:webhook_id` (`:214-245`): also accept `mode`,
  `block_id`, `department_id` and `source_name` (same `mode` validation). Keep using `findOneAndUpdate`
  (do **not** use `.save()` on existing documents — the pre-save hook at `models/webhook.js:51-66` never
  calls `next()` for non-new docs).
- `POST /preload/:webhook_id` (`:95-112`): when `webhook.mode === 'conversation'`, generate
  `support-group-<project>-<uuid>` instead of `automation-request-…` (same Redis key/TTL).
- One webhook per bot remains (unique index `{id_project, chatbot_id}`, `models/webhook.js:47`).

### 5.2 Webhook call — `routes/webhook.js`
- `router.all('/:webhook_id')` (`:263-322`): after the existing checks (404, 422 disabled, 429 rate limit),
  branch on `webhook.mode`:
  - no `mode` → existing `webhookService.run(...)` unchanged (any bot subtype).
  - `mode === 'conversation'` → load the bot (404 if missing/trashed) →
    `webhookConversationService.start(webhook, chatbot, payload, {dev:false})` → `202 {success:true, request_id}`.
- `router.all('/:webhook_id/dev')` (`:324-357`), `mode === 'conversation'` branch only: require the preload (reuse
  `NO_PRELOADED_DEV_REQUEST` → 422), **apply the `enabled` check and rate limit** (the automation dev route
  currently skips both), use the preloaded request id and set draft `sourcePage`. **The preload is single-use:
  the dev call consumes it** (deletes the Redis key right after reading it, before starting the conversation),
  so a second dev call without a fresh preload gets `NO_PRELOADED_DEV_REQUEST` again instead of reusing the
  same `request_id` and failing on the unique index.
- Analytics: emit `webhook.triggered` (prod only) with extra `mode: 'conversation'` and the real
  `request_id` (`pubmodules/analytics-publisher/index.js:386-404` consumer tolerates extra fields).

### 5.3 Conversation starter — new `services/webhookConversationService.js`
`start(webhook, chatbot, payload, { dev, request_id })`:
1. **Lead:** `leadService.createIfNotExistsWithLeadId('webhook_' + webhook.webhook_id, webhook.source_name || webhook.name, undefined, webhook.id_project, 'system', { webhook_id })`
   (signature `services/leadService.js:59`).
2. **Request:** `requestService.create({ request_id: request_id || 'support-group-' + project + '-' + uuid, lead_id, lead, id_project, first_text: '/start', departmentid: webhook.department_id, participants: ['bot_' + webhook.chatbot_id], channel: { name: 'webhook' }, preflight: false, createdBy: 'system', attributes: { webhook_id, payload: { ...payload, webhook_http_method, webhook_query_params }, sourcePage: dev ? 'webhook://' + webhook.webhook_id + '?dev=true&td_draft=true' : undefined } })`.
   The root bot id is used; its `url` points to the published copy (same as the widget). The dev
   `sourcePage` must contain `&td_draft=true` (with the `&`): `BotSubscriptionNotifier` matches
   `indexOf("&td_draft=true")` and `requestService.create` matches `includes("td_draft=true")`.
   If `webhook.department_id` does not exist, `getOperators` rejects → 422 (§5.6).
   MongoDB rejects document keys containing `.` or starting with `$`, which Kubernetes/Grafana-style
   alert labels routinely have (e.g. `app.kubernetes.io/name`); before storage, payload keys are
   rewritten recursively with `sanitizePayloadKeys` — every `.` becomes `_` and a leading `$` becomes
   `_` — and if two keys collapse onto the same sanitized name, the later one wins.
3. **Department (v1 workaround):** `requestService.create` leaves `department` undefined when participants
   are passed (`services/requestService.js:609-627`, saved at `:661`). Resolve the department
   (`webhook.department_id` or the project default) and set `department` on the created request with a
   targeted `Request.findOneAndUpdate` before sending `/start`. The proper fix is TODO item 1.
4. **Start:** `messageService.send('system', 'Bot', request_id, '/start', id_project, null, { subtype: 'info', updateconversation: false })`
   (`services/messageService.js:17`).
5. Return `{ request_id }`. If lead/request creation fails, do not send `/start`.

### 5.4 Invite participants — `POST /:projectid/requests/:request_id/participants/invite`
Route in `routes/request.js` (mounted with `hasRoleOrTypes('agent', ['bot','subscription'])`, `app.js:621`;
bot tokens restricted to their own project by `middleware/has-role.js:43-69`). Logic in a new
`services/participantInviteService.js`.

Body: `{ department_id?: string, members?: string[] }` (ids or emails).

1. Load request by `request_id` + project → 404 if missing; 409 if `status === 1000` (closed); 422 if the
   request's channel is not `webhook` (Invite human is only for webhook-started conversations in v1).
2. Select invitees:
   - **members** given → resolve each to an **active** project user of agent role type (by `id_user` or
     user email); invite **all** resolved. If none resolve → fall back to department.
   - **department** (explicit `department_id`, otherwise `request.department`, otherwise default) →
     `departmentService.getOperators(dept, project, true /* nobot */)` (`services/departmentService.js:186`):
     - routing `assigned` → the single selected operator (round robin / advanced routing apply);
     - routing `pooled` → **one** agent via `getRandomAvailableOperator(available_agents)` (`:604`),
       excluding agents already participants before picking.
3. Invitees already in `request.participants` are reported with `already_participant: true` and count as
   invited (lets a flow "wait again" for the same human before a second question).
4. No invitees → `200 { request_id, invited: [], reason: 'no_available_agents' }`.
5. For each new invitee → `requestService.addParticipantByRequestId(request_id, project, id_user, options)`
   (`services/requestService.js:1722-1830`). The bot stays. Known v1 side effect: `hasBot` becomes `false`
   (`:1768`; TODO item 2) — message delivery is unaffected (`botEvent` resolves the bot from `participants`).
6. **Waiting protection:** set `workingStatus: 'pending'` and `attributes.hitl_waiting: true` on the request,
   emit `request.workingStatus.update` and `request.update`.
7. **Email** each newly added invitee with `emailService.sendNewAssignedRequestNotification(email, request, project)`
   (`services/emailService.js:385`), applying the same per-user/per-project notification opt-outs as
   `sendAgentEmail` (`pubmodules/emailNotification/requestNotification.js:885`; factor the checks into a helper).
   (`addParticipantByRequestId` does not emit `request.participants.update`, so no email is sent today.)
8. Response (always a non-empty JSON body): `200 { request_id, department_id, invited: [{ id_user, fullname, already_participant }] }`.

### 5.5 Waiting-protection reset — `event/messageEvent.js`
Add a listener next to the existing requester rule (`event/messageEvent.js:183-203`) on message creation:
if `request.attributes.hitl_waiting === true` **and** the sender is in `request.participantsAgents` **and**
(`message.attributes.subtype !== 'info'` **or** `message.attributes.action` is set) → set
`workingStatus: 'open'`, unset `attributes.hitl_waiting`, emit `request.workingStatus.update` + `request.update`.

Rationale: both close jobs exclude `workingStatus: 'pending'`
(`pubmodules/scheduler/tasks/closeBotUnresponsiveRequestTask.js:73-77`,
`closeAgentUnresponsiveRequestTask.js:65-69`); the existing reset only reacts to the requester, which in
these conversations is the source lead that never writes. chat21-ionic action buttons with
`show_reply=false` send an info message carrying `attributes.action` (chat21-ionic
`conversation-detail.page.ts:1871-1883`), hence the `action` clause. The routing-queue only refreshes
agent counters on `workingStatus` changes (`pubmodules/routing-queue/listenerQueued.js:296-316`).

### 5.6 Errors
| Case | Response |
|---|---|
| Webhook not found / disabled / rate-limited | 404 / 422 / 429 |
| Bot missing or trashed | 404 |
| `mode: 'conversation'` on a bot that is not subtype `chatbot`, or no `start` block | 422 |
| Configured `department_id` not found | 422 `webhook misconfigured` |
| Request quota exceeded (`requestService.create` throws "Requests limits reached") | 403 |
| Dev call without preload | 422 `NO_PRELOADED_DEV_REQUEST` |
| Lead/request creation failure | 500, `/start` not sent |
| Invite: request missing / closed / foreign bot token | 404 / 409 / 403 |
| Invite: request's channel is not `webhook` | 422 |

## 6. tybot — tiledesk-chatbot `main`

### 6.1 Action JSON (saved by Design Studio)
```json
{
  "_tdActionType": "invite_human",
  "_tdActionId": "<uuid>",
  "departmentId": "<department _id>",
  "members": "mario@acme.it, {{oncall_email}}",
  "trueIntent": "#<intent_id>",
  "falseIntent": "#<intent_id>",
  "trueIntentAttributes": {},
  "falseIntentAttributes": {}
}
```
`departmentId` and `members` are optional; with both empty the server uses the conversation's department.

### 6.2 Registration
- `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js`: `static INVITE_HUMAN = "invite_human";`
- New `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`.
- `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` handlers map (`:250-314`):
  `[Directives.INVITE_HUMAN]: DirInviteHuman`.

### 6.3 `DirInviteHuman` behaviour
Modelled on `DirIfOnlineAgentsV2` (`tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js`: `httpUtils.request`
with `JWT <token>` at `:181-221`, jumps via `DirIntent.intentDirectiveFor` + `callback(true)`), without
copying its bug at `:140`.
1. No `trueIntent` and no `falseIntent` → log error, `callback()`.
2. `requestId` starts with `automation-request-` → set `flowError` = `(Invite human) requires a conversation`,
   jump to `falseIntent`, no HTTP call.
3. Resolve `members`: `TiledeskChatbot.allParametersStatic(tdcache, requestId)` (`engine/TiledeskChatbot.js:571`)
   + `new Filler().fill(members, variables)` (`tiledeskChatbotPlugs/Filler.js:7`); array-valued variables
   expand to items; split on `,` `;` newline; trim; dedupe; drop empties.
4. `POST ${API_ENDPOINT}/${projectId}/requests/${requestId}/participants/invite`
   body `{ department_id: departmentId, members }` (`utils/HttpUtils.js:9-54` supports `json` bodies).
5. Success → set variables `invited_humans` (array) and `invited_humans_count` (number);
   count ≥ 1 → jump `trueIntent`, else `falseIntent`.
6. HTTP error/timeout → flow log error, set `flowError`, jump `falseIntent`.
7. Every jump ends with `callback(true)` (stop the rest of the block).
8. Flow logs: `[Invite Human] Invited: <names> (department <name>)`, `[Invite Human] No human available`,
   `[Invite Human] Error: …`.

### 6.4 Not in the directive
- No waiting: the next block's **Reply V2** (buttons, `noInputIntent`/`noInputTimeout`,
  `DirReplyV2.js:84-116`) or **Capture User Reply** waits.
- Responder identity: `lastUserMessage` (filled by `TiledeskChatbotUtil.lastUserMessageFrom`,
  `utils/TiledeskChatbotUtil.js:663-678`) carries `sender` / `senderFullname`.
- Flow-design rule on `main` (see TODO item 3): a pending lock captures every incoming message, including
  internal jumps, and Capture User Reply does not stop the block. Therefore: **Invite human before the
  question block**, prefer **Reply V2 with buttons**, and put Capture User Reply **last** in its block.

## 7. chat21-ionic — `master`

Conversations are identified by `attributes.request_channel === 'webhook'` (set server-side at
`channels/chat21/chat21Handler.js:329`; copied onto agent messages at chat21-ionic
`conversation-detail.page.ts:1157`).

1. **Buttons stay clickable (required).** `isLastMessage` (`src/chat21-core/utils/utils-message.ts:78-83`)
   compares against the literal last message, so the "X added" info line hides text/action buttons
   (`message-attachment.component.html:5, :26`; rendered via
   `ion-conversation-detail.component.html:207`). Change to "last message that is not an info message".
   Applies to all conversations (also fixes widget-started ones).
2. **Channel icon** for `webhook`: `ion-list-conversations.component.html:111-117`,
   `header-conversation-detail.component.html:50-56`, new svg asset.
3. **Archive confirmation** for `request_channel === 'webhook'` before closing
   (`conversations-list.page.ts:1060-1147`): "This conversation was started by an automated flow. Closing it
   stops the flow. Continue?"
4. **Null guards** on `this.conversation` / `this.conversation.attributes` in `getLeadDetail`
   (`conversation-detail.page.ts:1004-1044`, `:1012`) and `updateLeadInfo` (`:1365-1395`).

Notification: invite → chat21 group join + email; the bot's question after the invite triggers the
existing sound/tab blink (non-info message from another sender, `app.component.ts:1131-1149`).

## 8. design-studio — `master`
Paths: `C = src/app/chatbot-design-studio`, `CV = C/cds-dashboard/cds-canvas`.

### 8.1 Webhook service — `C/services/webhook-service.service.ts`
- `createStartWebhook(chatbot_id, block_id, opts?: { department_id?, source_name? })` → `POST /webhooks/`
  with body `{ chatbot_id, block_id, mode: 'conversation', ...opts }`.
- `updateWebhookSettings(chatbot_id, patch: { enabled?, mode?, block_id?, department_id?, source_name? })` → `PUT /webhooks/:chatbot_id`.
- Do **not** use `deleteWebhook` (`:97`, it stops a dev preload) for the off toggle.

### 8.2 Start block webhook section (subtype `chatbot` only)
- `CV/cds-panel-intent-detail/cds-panel-intent-detail.component.ts`: extend `initializeStart()` (`:100-103`)
  to load the webhook (`getWebhook` `:129-140`, guarding a missing `webhook_id`).
- New start-only HTML section (not under `isWebhook`, which hides "Available to agents" at `:16-37`):
  **Webhook** toggle; production + development URLs with copy/regenerate (reuse `copyText` `:213-235`,
  `onRegenerateWebhook` `:166-182`); department select (`dashboardService.departments`); source name input;
  hint about branching on `webhook_http_method`.
- Toggle state = webhook exists **and** `mode === 'conversation'` **and** `enabled`.
- Toggle ON: no webhook → `createStartWebhook(chatbot_id, startIntent.intent_id)`; webhook exists →
  `updateWebhookSettings({ enabled: true, mode: 'conversation', block_id: startIntent.intent_id })`. If the
  existing webhook had no `mode` (headless automation webhook bound to another block), show a confirmation
  first: "This chatbot already has a webhook that runs a block without a conversation. Switching it will make
  calls start conversations from the start block. Continue?". OFF: `updateWebhookSettings({ enabled: false })`
  (mode kept).
- Leave untouched: lazy auto-create for blocks named `webhook` (`CV/cds-intent/cds-intent.component.ts:265-272`).
- Small webhook badge on the start block header when enabled (`panel-intent-header`, name-based logic `:72-81`).

### 8.3 "Invite human" action (template: `ifonlineagentsv2`)
| Step | Location |
|---|---|
| `TYPE_ACTION.INVITE_HUMAN = 'invite_human'` | `C/utils-actions.ts` enum (`ONLINE_AGENTSV2` at `:33`) |
| `ACTIONS_LIST.INVITE_HUMAN` entry, `chatbot_types: [TYPE_CHATBOT.CHATBOT]`, category, icon, `status:'active'`, doc key | `C/utils-actions.ts` (template entry `:141`). **Enum key and ACTIONS_LIST key must be identical** (`CV/cds-intent/cds-intent.component.ts:751-766`). |
| `ActionInviteHuman` model (`departmentId?`, `members?`, `trueIntent`, `falseIntent`, `*IntentAttributes?`) | `src/app/models/action-model.ts` (template `:78-95`) |
| Factory branch | `C/services/intent.service.ts` `createNewAction` `:951` (template `:1025-1027`) |
| Component `cds-action-invite-human` (copy `CV/actions/list/cds-action-online-agents-v2/cds-action-online-agents.component.*`; drop radio/operating hours; keep department select, `/true` `/false` connectors `:118-119`, `onChangeSelect`/`onResetBlockSelect` `:187-215`) | new folder under `CV/actions/list/` |
| Members field: `cds-textarea` with `setAttributeBtn` (variable picker inserting `{{var}}`) | `CV/base-elements/textarea/textarea.component.ts:11, :29` |
| Module declarations/exports | `CV/actions/list/cds-actions.module.ts` (`:78`, `:120`, `:242`) |
| Block preview switch case | `CV/cds-intent/cds-intent.component.html:212-218` |
| Detail panel switch case | `CV/cds-panel-action-detail/cds-panel-action-detail.component.html:84-91` |
| Connector redraw | `C/services/connector.service.ts:522-548` |
| Icon | `C/services/icon.service.ts:229-232` + `src/assets/images/actions/invite_human.svg` |
| i18n (name, doc recommending "Invite human → question block", labels) | `src/assets/i18n/en.json` (`CDSActionList` `:861`, `NAME` `:862`, `DOC` `:918`); other locales have no `CDSActionList` |

Menu filtering by subtype needs no change (`src/app/utils/project-utils.ts:139-141`,
`CV/cds-panel-elements/cds-panel-elements.component.ts:125`).

### 8.4 Test the webhook start
- New play menu item "Test webhook start" (`C/utils-menu.ts:28-31`), visible for chatbots with the webhook enabled.
- Start: `preloadWebhook(webhook_id)` → `support-group-…` `request_id`; show dev URL box (widen
  `cds-header.component.html:110-121`); `getToken` (`cds-header.component.ts:519-537`) → `logService.starterLog`;
  open **only** the logs panel for that `request_id` (do not go through the widget path at
  `CV/cds-canvas.component.ts:1538-1544`; set `mesage_request_id`, `cds-canvas.component.html:107-112`);
  highlight the start block (`CV/cds-intent/cds-intent.component.ts:196-201` currently only `webhook`).
- Close: `stopWebhook()` (`cds-header.component.ts:539-548`); extend the `isWebhook` guard at `:417`.

## 9. Testing

### 9.1 tiledesk-server (mocha + chai-http; `npm test` starts MongoDB; Redis for the rate limiter)
- New `test/webhookConversationRoute.js`: `mode:'conversation'` webhook create (block_id resolved from `start`;
  missing/foreign bot 404; non-chatbot bot 422); **backward compatibility: a chatbot-subtype webhook without
  `mode` still returns the automation response**; PUT settings (mode, block_id, department_id, source_name);
  run → 202 + request (participants `bot_<id>`, channel `webhook`, department, `attributes.payload`,
  `webhook_id`) + lead `webhook_<id>` + system `/start` info message; disabled 422; rate limit 429; dev without
  preload 422; dev with preload → preloaded `support-group-…` id + draft; dev enforces enabled + rate limit.
  Existing automation tests unchanged.
- New `test/inviteParticipantsRoute.js`: members (all valid invited, unknown ignored, fallback to department);
  assigned → one; pooled → one; none → `invited: []` + reason; already participant flag; bot stays;
  `workingStatus 'pending'` + `hitl_waiting`; closed 409; foreign-project bot token 403.
- Waiting reset: human participant text → `open` + marker removed; info without action → unchanged;
  info with `attributes.action` → `open`; requester rule unchanged; close-task queries exclude `pending`.

### 9.2 tybot (`tybotRoute`, mocha; in-process tilebot on 10001 + mock Tiledesk API on 10002 + bot fixture,
as in `test/conversation-replyv2_button_match_test.js`)
New `test/conversation-invite_human_bot.js` + `test/conversation-invite_human_test.js`:
invited → trueIntent (mock receives filled `members` and `department_id`); `invited: []` → falseIntent;
HTTP 500 → falseIntent + `flowError`; `automation-request-…` → falseIntent, no HTTP call; HITL round trip:
Invite → Reply V2 buttons → agent message "Approve" → approve block with `lastUserMessage.sender` = agent id.

### 9.3 design-studio (`ng test`; CI does not run tests — run locally, plus `ng build`)
Specs: `webhook-service.service.spec.ts` (HTTP shape of new methods via `HttpTestingController`);
invite-human component (connectors, department selection); start panel toggle (create vs `enabled` update,
never `deleteWebhook`). `strictTemplates` is off, so template bindings need manual review.

### 9.4 chat21-ionic (`ng test`)
New `src/chat21-core/utils/utils-message.spec.ts`: `isLastMessage` ignores trailing info messages.
Manual: `webhook` icon; archive confirmation only for `request_channel === 'webhook'`.

### 9.5 End-to-end acceptance (local stack, or stage when deployment is decided)
| # | Scenario | Expected |
|---|---|---|
| A | AIOps happy path: `curl` prod URL with Grafana-like payload; flow start → branch `webhook_http_method` → enrich → Invite human (SRE) → Reply V2 [Approve][Reject] | 202 `request_id`; agent emailed; conversation in chat21-ionic with webhook icon; still open after > 20 min; Approve resumes the flow; `workingStatus` back to `open` |
| B | Same bot from the widget | Start block runs as before; `webhook_http_method` not set |
| C | No available agent in department | "No human available" branch |
| D | DS "Test webhook start" (dev URL) | Draft bot runs; logs panel shows the run; close stops preload |
| E | Existing automation webhook | Unchanged, including sync `web_response` |
| F | Disabled webhook / rate limit | 422 / 429 |

## 10. Known limitations (v1)
- `hasBot` becomes `false` after an invite (TODO 2): affects `hasBot` consumers (analytics "with bot", which
  close job would apply once the conversation is not `pending`), not message delivery.
- The `request.create` event/websocket CREATE is published before the department is set (TODO 1 workaround).
- Every webhook call opens a new conversation; no dedup.
- A conversation nobody answers is never auto-closed while `pending`; the flow's no-input timeout must
  escalate/close.
- A second question later in the flow needs **Invite human** again right before it to restore protection.
- Payload keys become flow variables and can overwrite same-named variables (same as automation webhooks).
- tybot `main` lock/Capture User Reply behaviour (TODO 3) constrains flow design (§6.4).
- chat21-ionic `request_channel` on the list item comes from the latest conversation snapshot attributes;
  a message without `request_channel` could reset the list icon (the detail page re-reads it from the request).
- Invite human is rejected (422) in conversations not started by a webhook; tybot takes the "no human
  available" branch with `flowError`.

---

## 11. Participant removal and reassignment (v2 extension, 2026-09-29)

Status: approved in brainstorming on 2026-09-29; extends §5–§9. Repo bases: the feature branches after merging
the default branches on 2026-09-29 (tiledesk-server 2.26.0, tiledesk-chatbot 2.2.0, design-studio 1.40.15,
chat21-ionic 3.4.35).

### 11.1 Goal and decisions
Goal: a chatbot started by a webhook interacts with a back-office operator, and people leave the conversation
cleanly at the right moment, without leaving the flow stuck.

Decisions (user, 2026-09-29):
1. **The flow removes humans** once it has what it needed, with a new `remove_human` action whose scope is
   either *only the humans this flow invited* or *all human participants*.
2. **Operators can leave** a webhook conversation from chat21-ionic; leaving counts as a removal.
3. **If the human the flow needs leaves or is removed, the server reassigns automatically** to another
   available agent of the same department. If nobody is available, **the flow is told**: it jumps to the
   "No human available" branch of the `invite_human` action that brought the human in, with a specific
   `flowError`.
4. **The bot is never removed automatically.** Full ownership ("pure human handoff") uses the existing
   **Remove current bot** action (`removecurrentbot`) after `invite_human`— today reachable in Design Studio only as the `\removecurrentbot` text directive in a Reply (there is no dedicated editor action yet); pairing is what `invite_human`
   already does. Deliberate removal of the bot by a person (dashboard, API) stays allowed.
5. **Webhook-only boundary:** every flow-driven conversation enters through the webhook conversation start
   (web interfaces, schedulers and integrations are callers of it), so invite, remove, reassignment and Leave
   apply only to conversations with `request.channel.name === 'webhook'`. Widget conversations are untouched.
6. **All new REST APIs are project scoped:** under `/:projectid/...`, behind the existing authentication and
   role middleware; every read and write filters on `id_project` (conversations, departments, project users);
   a conversation of another project answers 404.
7. **Start points** (several start types per chatbot: web, scheduled, integration apps such as Google mail)
   are a **separate sub-project** with its own design. This extension only prepares for it with
   `attributes.start_type` (§11.2).

Approach: the server owns removal handling (one listener for every removal path, agent picking next to the
existing invite logic); tybot only calls endpoints and receives the fallback jump.

### 11.2 Conversation data (`request.attributes`)
| Field | Written by | Meaning |
|---|---|---|
| `start_type` | conversation start (§5.3) | how the flow was started; always `'webhook'` in this version, reserved for start points |
| `hitl_waiting` | invite (§5.4), unchanged | a question is waiting for a human; cleared by the reply listener (§5.5) |
| `hitl_invited` | invite, reassignment | user ids invited by the flow that are still participants |
| `hitl_department_id` | invite | the resolved department used to pick agents (explicit, conversation or default) |
| `hitl_fallback` | invite, only when ≥1 human invited and the action has a "No human available" branch | `{ intent: "#<blockId>" }`, where the flow resumes when no human can be found |
| `hitl_left` | removal listener | user ids that left or were removed by someone other than the flow while the flow was waiting for a human; never picked again automatically for this conversation (department invites and replacements) |

`hitl_invited` includes invitees reported as `already_participant`. The reply listener (§5.5) clears only
`hitl_waiting`: the flow still "holds" its humans until it removes them.

### 11.3 API (tiledesk-server)
1. **Invite** — `POST /:projectid/requests/:request_id/participants/invite` gains an optional
   `fallback_intent` (string, `#<blockId>`; 422 if not a string). When at least one human is invited the server
   stores `hitl_invited` (union with the existing list), `hitl_department_id` and, if given, `hitl_fallback`.
   Response unchanged.
2. **Remove (new)** — `POST /:projectid/requests/:request_id/participants/remove`, same router and middleware
   as invite (`app.js:621`, `hasRoleOrTypes('agent', ['bot','subscription'])`).
   - Body: `{ scope: 'invited' | 'all_humans' }` (default `'invited'`; any other value → 422).
   - 404 unknown conversation (in this project), 409 closed, 422 channel not `webhook`.
   - First clears `hitl_waiting`, `hitl_invited`, `hitl_fallback` (atomic update filtered by `request_id` +
     `id_project`), sets `workingStatus: 'open'` if it was `'pending'`, then removes each human in scope with
     `requestService.removeParticipantByRequestId` (so chat21 group, activity and events behave as a normal
     removal). The bot is never removed by this endpoint.
   - Scope `invited` = the `hitl_invited` list read before clearing, intersected with current participants;
     `all_humans` = every participant not prefixed `bot_`.
   - Response `200 { request_id, removed: [{ id_user, fullname }] }`; an empty list is not an error.
3. **Generic removal** — `DELETE /:projectid/requests/:request_id/participants/:participantid` keeps its API;
   chat21-ionic Leave and the dashboard use it. Its new behaviour comes from the listener (§11.4). Removing the
   bot through it stays allowed.

### 11.4 Removal listener (new, e.g. `services/hitlParticipantListener.js`)
Subscribes to `request.participants.leave` (payload `{ member, request, actor, source }`,
`services/requestService.js`) and `request.participants.update` (`{ beforeRequest, removedParticipants,
addedParticipants }`), queue variants when `requestEvent.queueEnabled`. Acts only on webhook conversations that
are not closed.

**A human left** (`member` not prefixed `bot_`):
1. Atomic `findOneAndUpdate({ request_id, id_project, 'attributes.hitl_invited': member },
   { $pull: { 'attributes.hitl_invited': member }, $addToSet: { 'attributes.hitl_left': member } }, { new: true })`.
   No match → stop (the human was not invited by the flow, or the flow's remove endpoint already released it).
2. `hitl_invited` still non-empty → stop.
3. Reassignment is attempted whether or not `hitl_fallback` is set. (Amended by §12.2.1: only while `hitl_waiting === true`; otherwise the leave just releases the human.)
4. **Reassign**: pick one available agent of `hitl_department_id` with the invite service's picker
   (§5.4 step 2), excluding `hitl_left` and current participants.
   - **Found** → add as participant, email as an invite, `$addToSet` into `hitl_invited`; `hitl_waiting` and
     `workingStatus` are left as they are (a pending question stays pending).
   - **Not found** → clear `hitl_waiting`, `hitl_invited`, `hitl_fallback`, set `workingStatus: 'open'`, emit
     `request.workingStatus.update` + `request.update`; then, only when `hitl_fallback` is set (otherwise only the
     waiting state is cleared), send a system info message to the conversation with
     `attributes.action = '#<blockId>{"flowError":"(Invite human) The invited human left and no replacement is available"}'`
     (tybot's explicit-action syntax, `TiledeskChatbotUtil.parseIntent`; the text must contain no `'`, which
     tybot rewrites to `"`). A send failure is logged; the conversation stays open and not waiting, so the
     auto-close jobs can end it.
     The message is sent with sender `system` and `attributes.hitl_fallback: true`; `event/botEvent.js` forwards
     system messages to the bot only for `/start` today, so it must also forward a system message whose
     `attributes.hitl_fallback === true` and that carries `attributes.action` (no other system message changes).

**Dashboard "replace participants"** (`participants.update` with added humans): the added humans are
`$addToSet` into `hitl_invited`, removed ones go through steps 1–2 only (no automatic pick, no fallback).

**The bot left**: clear `hitl_waiting`, `hitl_invited`, `hitl_fallback`, set `workingStatus: 'open'`; no message
to the bot. The remaining humans own the conversation.

Concurrency: step 1 is atomic, so when two invited humans leave together only the last one out reaches step 4.
A reply just before leaving clears only `hitl_waiting`; reassignment still runs (intended).

### 11.5 tybot (tiledesk-chatbot)
- **`invite_human`** sends `fallback_intent: falseIntent` (as `#<blockId>`) in the invite body when the action
  has a `falseIntent`. Nothing else changes.
- **New `remove_human`** directive (`Directives.REMOVE_HUMAN = 'remove_human'`), action JSON:
  `{ _tdActionType: 'remove_human', scope: 'invited' | 'all_humans' (default 'invited'), trueIntent?, falseIntent?,
  trueIntentAttributes?, falseIntentAttributes? }`.
  - Calls `POST /:projectid/requests/:request_id/participants/remove` with the bot token and the same timeout
    as `invite_human` (`INVITE_TIMEOUT_MS`, 30 s).
  - Sets `removed_humans` (array of `{ id_user, fullname }`) and `removed_humans_count`.
  - Success (also when nobody was removed) → `trueIntent`; HTTP error → `falseIntent` with
    `flowError = "(Remove human) An error occurred: " + <server error text or message>`; automation request id →
    `falseIntent` with `flowError = "(Remove human) requires a conversation"`. With no branch configured the
    block continues with the next action.
  - Logs only the error summary (`{ message, status, data }`), never the raw HTTP error (same rule as §6.3).
- **Fallback jump**: no engine change — a message with `attributes.action` unlocks the locked intent and runs the
  named block with its parameters (`engine/TiledeskChatbot.js`, explicit action path).
- The lock/Capture User Reply fix (TODO item 3) is planned alongside as a separate change.

### 11.6 chat21-ionic
- **Leave conversation**: an icon button on the conversation list item (visible on desktop and mobile; the archive button next to it is hidden on desktop since upstream 6460bede), only for `isWebhookConversation(conversation)` and not archived conversations.
- Confirmation alert: "You will leave this conversation. If a flow invited you, it will look for another operator or continue without you. Continue?" with Cancel / Leave; new keys in all 15 locale files.
- `TiledeskService.removeParticipant(requestId, userId, projectId)` → `DELETE /:projectid/requests/:requestId/participants/:userId`
  with the logged-in user's id and token; on error a toast shows the server reason. The conversation leaves the
  list when chat21 removes the member from the group.
- Archive (close) is unchanged.

### 11.7 design-studio
- **"Remove human" action**, same pattern as "Invite human" (§8.3): `ActionRemoveHuman` (`scope`, `trueIntent`,
  `falseIntent`, `trueIntentAttributes?`, `falseIntentAttributes?`), `TYPE_ACTION.REMOVE_HUMAN = 'remove_human'`
  and `ACTIONS_LIST.REMOVE_HUMAN` (subtype `chatbot`, Most used), factory branch, component + spec, module,
  both switch cases, connector redraw, icon `person_remove`, `en.json`.
- Panel: scope select ("Only humans invited by this flow" default, "All human participants"), outputs
  "Removed" and "Error". Preview shows the scope and both connectors.
- Help texts: Invite human — "If the invited human leaves, another available agent is invited; if nobody is
  available, the flow continues from No human available."; Remove human — "Removes human participants from the conversation while the chatbot keeps running: only the humans this flow invited, or all of them. Place it at the end of the part of the flow that needs a human: until they are removed, invited humans who leave are replaced automatically. The Removed output is also taken when there was nobody to remove. Available only in conversations started by a webhook. To hand the conversation over completely to the invited humans, remove the bot instead with a Reply whose text is \removecurrentbot."

### 11.8 Testing
- **tiledesk-server** (mocha, test MongoDB + Redis): invite stores `fallback_intent`/`hitl_invited`/
  `hitl_department_id` only when someone is invited, `start_type` set at start; remove endpoint scopes, bot kept,
  fields cleared, no reassignment, 404/409/422, other-project conversation → 404; listener: reassign to another
  agent (excluding `hitl_left`), no agent → fallback message with the exact `action`, other invited human remains
  → no-op, non-invited human → no-op, dashboard replace with an added human → no pick, bot removed → state
  cleared, concurrent leaves → one reassignment; existing webhook/invite/HITL suites still pass.
- **tybot**: `remove_human` unit (scope, variables, error summary without token, automation) and conversation
  tests (removed → trueIntent, error → falseIntent with reason, `invite_human` sends `fallback_intent`, the
  fallback `action` message unlocks a paused Reply V2 and lands in the fallback block with `flowError`).
- **chat21-ionic**: Leave visible only for open webhook conversations; `removeParticipant` URL; locale JSON valid;
  build.
- **design-studio**: `remove_human` component spec; build.
- **End-to-end** (extends §9.5 scenario A), local stack with a department of agents A and B:
  1. webhook → flow invites A; A answers with a button; flow continues;
  2. flow invites again; A leaves from chat21-ionic → B invited automatically, answers, flow continues;
  3. flow `remove_human` scope `invited` → B removed, bot finishes;
  4. department with only A: A leaves → flow jumps to "No human available" with the new `flowError`;
  5. full ownership: `invite_human` then `removecurrentbot` → A owns the conversation, no longer pending.

### 11.9 Limitations
- Reassignment picks from the invite's department only; explicit members are not re-invited individually.
- Without a "No human available" branch on `invite_human`, a failed reassignment only clears the waiting state
  (the flow is not notified).
- Only the latest invite's fallback block is kept.
- `hitl_left` grows for the life of the conversation; a human who left is never picked again automatically
  (a flow can still invite them explicitly by member).
- When the server's fallback message resumes the flow, its text becomes the flow's `lastUserText` (and `lastUserMessage.sender` is `system`, and it is appended to the transcript); AI Prompt / Ask KB actions in the fallback block that default to `{{lastUserText}}` receive that sentence.
- The server-driven fallback jump carries only `flowError`; the `invite_human` action's `falseIntentAttributes` are not applied on that path.
- An internal jump into the waiting action's own block is still consumed as its answer (lock ownership compares the action id, and the jumped-to block contains that same action).

---

## 12. Known-limit corrections and pre-branch ports (2026-09-29)

Status: approved in brainstorming on 2026-09-29; amends §11.4 (12.2.1) and adds pre-branch ports. Feature
branches at the start: tiledesk-server `c23e22ff`, tiledesk-chatbot `7d3e1a67`, chat21-ionic `15d4f61d`,
design-studio `9b9b80c2`.

### 12.1 Decisions (user, 2026-09-29)
1. **Replace only while the flow is waiting.** A departed invited human is replaced (or the flow is sent to its
   fallback) only while the conversation waits for a human answer (`hitl_waiting === true`). Otherwise the
   departure just releases that human. This supersedes §11.4 step 3 ("Reassignment is attempted whether or not
   `hitl_fallback` is set" stays true, but only while waiting).
2. **Pre-branch ports for all four repos.** Feature branches are merged separately into each repo's default
   branch and its pre branch, so each repo gets a second local branch `feature/webhook-chatbot-hitl-PRE`, built
   from the pre branch by cherry-picking the feature commits. Pre branches: tiledesk-server `master-COLLAUDO`,
   tiledesk-chatbot `main_pre`, chat21-ionic `master-PRE`, design-studio `master-pre`.
3. **Disk space is limited:** no new git worktrees; ports are done one repo at a time in the existing checkout.
4. All the other known limits listed in 12.2–12.3 are corrected (no decision needed).

### 12.2 tiledesk-server corrections
1. **Replace only while waiting** (`services/hitlParticipantListener.js`). When the last invited human leaves:
   - `hitl_waiting === true` → unchanged §11.4 behaviour (replacement from `hitl_department_id`, else clear the
     waiting state and send the fallback if `hitl_fallback` is set);
   - otherwise → the leaver is only pulled from `hitl_invited` (NOT added to `hitl_left`: it did not abandon a
     pending question); when `hitl_invited` becomes empty, both `hitl_invited` and `hitl_fallback` are unset (the
     flow's hold is released and tracking ends); no replacement, no message, no status change.
   The decision reads `hitl_waiting` from the step-1 document (atomic with the leave), never from the event
   payload.
2. **Atomic participant removal** (`services/requestService.js` `removeParticipantByRequestId`). Replace the
   load–modify–save with:
   - one `findOneAndUpdate` filtered by `request_id`, `id_project` and `participants: member`, doing `$pull` on
     `participants` and on `participantsBots` (bot member, without the `bot_` prefix) or `participantsAgents`
     (human member), plus `$set` of `attributes.abandoned_by_project_users.<project_user_id>` (timestamp) for a
     human member, and the `hasBot = false` change for a bot member as today; no match → resolve as the current
     "already not found" branch does (no events);
   - then, unless the request is closed, a second update setting `status` to assigned (participants remain) or
     unassigned (none left), filtered on the resulting participant count so a concurrent change is not
     overwritten;
   - the emitted events (`request.update`, `request.update.comment`, `request.updated`,
     `request.participants.leave`) and their payload shapes stay identical, built from the updated, populated
     document.
   The TODO entry "Concurrent participant removals can lose one removal" is marked done.
3. **`clearWaiting` in one write per attempt** (`hitlParticipantListener.js`): two conditional updates, no
   aggregation-pipeline update. Attempt A matches `workingStatus: 'pending'` and, in one write, unsets
   `hitl_waiting`/`hitl_invited`/`hitl_fallback` and sets `workingStatus: 'open'`; attempt B (only when A did not
   match) only unsets the three attributes. `request.workingStatus.update` is emitted only from A. The residual
   gap needs a manual status change or an invite racing a bot removal, when no flow remains.
4. **Replacement vs the flow's Remove human**: after `addParticipantByRequestId` for a replacement, the listener
   re-reads `hitl_invited` atomically; if the replacement is no longer in it (the flow released its humans in the
   meantime), the listener removes the replacement again via `removeParticipantByRequestId` and does not treat
   that removal as a HITL leave (it is not in `hitl_invited`, so §11.4 step 1 already ignores it).

### 12.3 tybot corrections
1. **No token in logs** (`tybotRoute/utils/HttpUtils.js` `request`, TODO item 6). The error handler logs only
   `{ message, code, status, url (without query string), data (response body) }`; it never logs the raw error,
   `error.response`, `error.config` or `error.request`. The callback still receives the original error.
2. **A lock belongs to the action that set it** (`DirCaptureUserReply`, `DirReplyV2.lockUnlock`). "Reply path"
   only when the locked action id equals the action's own `_tdActionId`; a different locked action id means the
   action was reached by an internal jump: it runs as a first pass (asks its question and takes over the lock).
3. **Capture User Reply without block info** logs an error and stops the block (`callback(true)`) instead of
   continuing past the question.
4. **The no-input timer only fires for the action that owns the lock** (`DirReplyV2`). After the existing
   `USER_INPUT === timeout_id` check the timer also requires `currentLockedAction === action._tdActionId`;
   otherwise it logs at debug and does nothing (no unlock, no jump). A Reply V2 without `intent_info.intent_name`
   logs an error and stops the block without locking.
5. **Logger-level redaction** (`tybotRoute/utils/winston.js`, TODO item 7). Every transport runs a redaction
   format before `simple()`: values of keys `authorization|token|x-api-key|apikey|api_key|gptkey|password|secret`
   become `[REDACTED]`, and `JWT <token>` / `Bearer <token>` in any string, message included, become
   `JWT [REDACTED]` / `Bearer [REDACTED]`. It works on copies (callers' objects are not mutated), is depth-limited
   and cycle-safe, and also covers Error objects (message, stack, `config`, `response`).
6. **Async `/block` error** (`tybotRoute/index.js`). On a `/ext` failure the async branch logs
   `HttpUtils.errorSummary(err, url)` and answers `500 { success: false, error: <message> }`; the raw error (which
   carries the bot token) is neither logged nor returned, so tiledesk-server forwarding the body is safe.

### 12.4 Pre-branch ports
Per repo, one at a time, in the existing checkout:
1. `git switch -c feature/webhook-chatbot-hitl-PRE origin/<pre branch>`; clean install from that branch's lockfile
   into the existing `node_modules` (tiledesk-server `npm ci`; tiledesk-chatbot `npm ci` at the repo root;
   chat21-ionic `npm ci --ignore-scripts` with Node 14; design-studio `npm ci` with Node 16).
2. Cherry-pick, in order, every non-merge commit of the feature branch since it left the default branch (v1, v2
   and the §12.2/§12.3 corrections), skipping the "Merge origin/<default> into feature/…" commits. Docs commits
   exist only in tiledesk-server and are kept.
3. Conflicts: keep the pre branch's code and add the feature's change; never drop pre-branch behaviour to make the
   change fit. Each resolution is recorded in the plan ledger.
4. tybot: `main_pre` sends internal jumps through `/exec` (`DirIntent` `tilebotService.executeBlock`) instead of
   `/ext`; the lock fix (§11.5 / TODO item 3) and §12.3.2 are re-verified there with the same tests and adapted if
   the behaviour differs; the adaptation is recorded.
5. Tests: the feature suites, then a full-suite comparison against the pre branch (no failing test title only on
   the `-PRE` branch, apart from the known port-10002 cascade in tybot with each file green alone); builds for
   chat21-ionic and design-studio. Build outputs (`www/`, `dist/`) are deleted after the check.
6. Switch back to `feature/webhook-chatbot-hitl` and reinstall from its lockfile, so the checkout is left exactly as
   before. The user is told when each repo is back on its normal branch.
Nothing is pushed; each repo ends with two local branches (default-based and `-PRE`).

### 12.5 Testing
- tiledesk-server: new listener tests for "not waiting → release, no replacement, fallback cleared when the last
  invited human leaves"; `clearWaiting` status event only on change; replacement released when the flow removed its
  humans concurrently; `removeParticipantByRequestId` concurrency (two removals of different members at once →
  both removed; a removal concurrent with a HITL write → the HITL fields survive), plus every existing
  request/participant/HITL suite; full-suite comparison with `master`.
- tybot: HttpUtils (closed port and timeout: captured logs never contain the Authorization value; callback gets
  the error); lock ownership (waiting on question A, an internal jump reaches question B → B is asked and the next
  user text answers B, A is not consumed); Capture without block info stops; Capture / Reply V2 (buttons,
  no-input) / lock / invite / remove suites; full-suite comparison with `main`.
- chat21-ionic and design-studio: no code change on the default-based branches; their `-PRE` ports are tested per
  12.4.
- End-to-end (§11.8) remains pending (needs a running chat21 stack or stage).

## 13. End-to-end corrections (2026-09-30)

### 13.1 Invite waits for the chat21 join

- The live run showed the flow's next message reaching the chat21 group ~30 ms before the invited human was added
  (the join ran asynchronously after the invite answered), so the human missed it (2 of 4 invites).
- When the conversation's `channelOutbound.name` is `chat21`, `POST /:projectid/requests/:request_id/participants/invite`
  now answers only after chat21 has settled (joined or failed) the join of every newly added member. Members that were
  already participants trigger no join and are not waited for; other outbound channels are unchanged.
- The wait is bounded by `HITL_CHAT21_JOIN_TIMEOUT_MS` (default 5000). On timeout or join error the invite still answers
  200 as before and logs a warn line. `chat21Handler` registers each join in `chat21JoinTracker` (keyed by group and
  member); the `group.join` / `group.join.error` events are unchanged.
