# Webhook-started chatbot conversations + HITL invite — tiledesk-server Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Let a webhook with `mode: 'conversation'` start a normal chatbot conversation (like the widget), and let a flow invite platform users into that conversation while the bot stays, protected from auto-close until a human answers.

**Architecture:** The public webhook route branches on `webhook.mode`: without it the existing automation path runs untouched; with `'conversation'` a new `webhookConversationService` creates a source lead + `support-group-…` request with the bot as participant and sends the system `/start` message. A new `participantInviteService` (exposed as `POST /:projectid/requests/:request_id/participants/invite`) picks agents (explicit members or one agent from a department), adds them next to the bot, marks the request `workingStatus: 'pending'` + `attributes.hitl_waiting`, and emails them. A `messageEvent` listener resets the request to `open` when an invited human answers.

**Tech Stack:** Node.js (CommonJS), Express, Mongoose, mocha + chai + chai-http, winston.

**Spec:** `docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` (sections 3, 4, 5, 9.1, 10).

## Global Constraints

- Repo `tiledesk-server`, branch `feature/webhook-chatbot-hitl` (created from `origin/master` `5d240683`, upstream intentionally unset — never push to `master`).
- Backward compatibility (spec D11): a webhook **without** `mode` must behave exactly as today for every bot subtype. `test/webhookRoute.js` must pass **unchanged**.
- Do **not** modify `requestService.create` or `requestService.addParticipantByRequestId` (spec D9; TODO items 1–2). Work around them as specified.
- Do not use `.save()` on existing `Webhook` documents (pre-save hook never calls `next()` for non-new docs); use `findOneAndUpdate`.
- Whenever a service changes a request, emit `request.update` with a **populated** request (`lead`, `department`, `participatingBots`, `participatingAgents`, `requester.id_user`) — `pubmodules/cache/mongoose-cachegoose-fn.js:391-403` writes that object into the request cache read by `event/messageEvent.js`.
- Conversation mode value: exactly `'conversation'`. Channel name for created conversations: exactly `'webhook'`. Lead id: `'webhook_' + webhook_id`. Request id: `'support-group-' + id_project + '-' + UIDGenerator.generate()`.
- Invite response is always a non-empty JSON body (tybot `HttpUtils` treats an empty 2xx body as an error).
- `webhook.triggered` analytics payload shape is **not** changed (the consumer schema is unverified); only the request id is passed through the existing `payload.preloaded_request_id` field.
- Commit messages end with `Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>`.

### How to run tests (every task)
Prerequisites: Redis reachable at `CACHE_REDIS_HOST`/`CACHE_REDIS_PORT` (default `localhost:6379`; the webhook rate limiter needs it), Node deps installed.

```bash
cd /Users/nicocardone/Desktop/DEV/TILEDESK/tiledesk-server
npx mongodb-runner start          # once per session (same as npm "pretest")
npx mocha <test file(s)> --exit
npx mongodb-runner stop           # at the end of the session
```

---

## File Structure

| File | Status | Responsibility |
|---|---|---|
| `models/webhook.js` | Modify | add `mode`, `department_id`, `source_name` fields |
| `services/webhookSettingsValidator.js` | Create | find the webhook's chatbot; validate/normalize `mode`, `block_id`, `department_id`, `source_name` |
| `routes/webhooks.js` | Modify | use the validator in `POST /`, `PUT /:chatbot_id`, `PUT /update/:webhook_id`; conversation-mode request id in `POST /preload/:webhook_id` |
| `services/webhookConversationService.js` | Create | create source lead + request + department + `/start` message |
| `routes/webhook.js` | Modify | branch prod and dev routes on `webhook.mode` |
| `services/participantInviteService.js` | Create | resolve invitees, add participants, pending marker, invite email |
| `routes/request.js` | Modify | `POST /:requestid/participants/invite` |
| `event/messageEvent.js` | Modify | reset `pending` → `open` when an invited human answers |
| `test/webhookConversationTestUtils.js` | Create | shared test helpers (`waitFor`, `setupProjectWithBot`) — not a mocha test file (no `describe`) |
| `test/webhookConversationRoute.js` | Create | HTTP tests for webhook settings + conversation start |
| `test/webhookConversationService.js` | Create | service tests for the conversation starter |
| `test/inviteParticipantsRoute.js` | Create | HTTP tests for the invite endpoint |
| `test/hitlWaitingReset.js` | Create | tests for the waiting-protection reset |

---

### Task 1: Webhook model fields + settings validation in webhook management routes

**Files:**
- Modify: `models/webhook.js:37-42`
- Create: `services/webhookSettingsValidator.js`
- Modify: `routes/webhooks.js` (imports at top, `POST /` `:67-93`, `POST /preload/:webhook_id` `:95-112`, `PUT /:chatbot_id` `:182-212`, `PUT /update/:webhook_id` `:214-245`)
- Create: `test/webhookConversationTestUtils.js`
- Create: `test/webhookConversationRoute.js`

**Interfaces:**
- Consumes: none.
- Produces:
  - `Webhook` fields `mode?: 'conversation'`, `department_id?: string|null`, `source_name?: string`.
  - `webhookSettingsValidator.CONVERSATION_MODE === 'conversation'`
  - `webhookSettingsValidator.findChatbot(id_project: string, chatbot_id: string): Promise<Object|null>` (lean faq_kb, not trashed)
  - `webhookSettingsValidator.validate(id_project: string, chatbot: Object, body: Object): Promise<{ok: true, fields: Object} | {ok: false, status: number, message: string}>`
  - test helpers (`test/webhookConversationTestUtils.js`): `PWD`, `uniqueEmail(prefix): string`, `waitFor(fn, {timeout, interval}): Promise<any>`, `setupProjectWithBot(server, {subtype?, waitStart = true}): Promise<{email, pwd, user, project, chatbot_id, startIntent}>`.

- [ ] **Step 1: Create the shared test helpers**

Create `test/webhookConversationTestUtils.js`:

```js
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);

const userService = require('../services/userService');
const projectService = require('../services/projectService');
const Faq = require('../models/faq');

const PWD = 'pwd';

async function waitFor(fn, { timeout = 5000, interval = 100 } = {}) {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    const value = await fn();
    if (value) {
      return value;
    }
    await new Promise((resolve) => setTimeout(resolve, interval));
  }
  throw new Error('waitFor timeout after ' + timeout + 'ms');
}

function uniqueEmail(prefix) {
  return prefix + '-' + Date.now() + '-' + Math.floor(Math.random() * 100000) + '@email.com';
}

/**
 * Creates a user, a project and a tilebot chatbot through the API.
 * The blank template's intents are saved asynchronously by faqService, so the
 * start intent is awaited when waitStart is true.
 */
async function setupProjectWithBot(server, { subtype, waitStart = true } = {}) {
  const email = uniqueEmail('test-webhook-conv');
  const user = await userService.signup(email, PWD, 'Test Firstname', 'Test lastname');
  const project = await projectService.create('test-webhook-conversation', user._id);

  const body = { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' };
  if (subtype) {
    body.subtype = subtype;
  }
  const res = await chai.request(server).post('/' + project._id + '/faq_kb').auth(email, PWD).send(body);
  if (res.status !== 200) {
    throw new Error('Chatbot creation failed with status ' + res.status);
  }
  const chatbot_id = res.body._id;

  let startIntent = null;
  if (waitStart) {
    startIntent = await waitFor(() => Faq.findOne({ id_faq_kb: chatbot_id, intent_display_name: 'start' }).lean().exec());
  }

  return { email, pwd: PWD, user, project, chatbot_id, startIntent };
}

module.exports = { PWD, waitFor, uniqueEmail, setupProjectWithBot };
```

- [ ] **Step 2: Write the failing tests for webhook settings**

Create `test/webhookConversationRoute.js`:

```js
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';
process.env.LOG_LEVEL = 'error';
process.env.BUCKET_WH_CAPACITY = 2;

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../app');
const expect = chai.expect;
chai.use(chaiHttp);

const departmentService = require('../services/departmentService');
const { setupProjectWithBot } = require('./webhookConversationTestUtils');

describe('WebhookConversationRoute - settings', function () {

  this.timeout(20000);

  it('creates a conversation webhook bound to the start block when block_id is omitted', async () => {
    const { email, pwd, project, chatbot_id, startIntent } = await setupProjectWithBot(server);
    const defaultDepartment = await departmentService.getDefaultDepartment(project._id);

    const res = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, mode: 'conversation', source_name: 'Grafana alerts', department_id: defaultDepartment.id });

    expect(res).to.have.status(200);
    expect(res.body.mode).to.equal('conversation');
    expect(res.body.block_id).to.equal(startIntent.intent_id);
    expect(res.body.source_name).to.equal('Grafana alerts');
    expect(res.body.department_id).to.equal(defaultDepartment.id);
    expect(res.body.webhook_id).to.have.length(32);
  });

  it('rejects conversation mode for a bot that is not subtype chatbot', async () => {
    const { email, pwd, project, chatbot_id } = await setupProjectWithBot(server, { subtype: 'webhook', waitStart: false });

    const res = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, block_id: 'any-block', mode: 'conversation' });

    expect(res).to.have.status(422);
    expect(res.body.success).to.equal(false);
  });

  it('rejects an unknown department', async () => {
    const { email, pwd, project, chatbot_id } = await setupProjectWithBot(server);

    const res = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, mode: 'conversation', department_id: '5f0000000000000000000000' });

    expect(res).to.have.status(422);
  });

  it('returns 404 when the chatbot does not exist', async () => {
    const { email, pwd, project } = await setupProjectWithBot(server, { waitStart: false });

    const resUnknown = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: '5f0000000000000000000000', block_id: 'any-block' });
    expect(resUnknown).to.have.status(404);

    const resInvalid = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: 'not-an-object-id', block_id: 'any-block' });
    expect(resInvalid).to.have.status(404);
  });

  it('switches an existing automation webhook to conversation mode with PUT', async () => {
    const { email, pwd, project, chatbot_id, startIntent } = await setupProjectWithBot(server);

    const created = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, block_id: 'legacy-block' });
    expect(created).to.have.status(200);
    expect(created.body.mode).to.equal(undefined);

    const res = await chai.request(server)
      .put('/' + project._id + '/webhooks/' + chatbot_id)
      .auth(email, pwd)
      .send({ mode: 'conversation', enabled: true, source_name: 'On-call alerts' });

    expect(res).to.have.status(200);
    expect(res.body.mode).to.equal('conversation');
    expect(res.body.block_id).to.equal(startIntent.intent_id);
    expect(res.body.source_name).to.equal('On-call alerts');
    expect(res.body.enabled).to.equal(true);
  });

  it('updates settings by webhook_id with PUT /update/:webhook_id', async () => {
    const { email, pwd, project, chatbot_id } = await setupProjectWithBot(server);

    const created = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, mode: 'conversation' });
    expect(created).to.have.status(200);

    const res = await chai.request(server)
      .put('/' + project._id + '/webhooks/update/' + created.body.webhook_id)
      .auth(email, pwd)
      .send({ source_name: 'Renamed source', enabled: false });

    expect(res).to.have.status(200);
    expect(res.body.source_name).to.equal('Renamed source');
    expect(res.body.enabled).to.equal(false);
    expect(res.body.mode).to.equal('conversation');
  });

  it('preload returns a support-group request id for conversation webhooks', async () => {
    const { email, pwd, project, chatbot_id } = await setupProjectWithBot(server);

    const created = await chai.request(server)
      .post('/' + project._id + '/webhooks/')
      .auth(email, pwd)
      .send({ chatbot_id: chatbot_id, mode: 'conversation' });

    const res = await chai.request(server)
      .post('/' + project._id + '/webhooks/preload/' + created.body.webhook_id)
      .auth(email, pwd);

    expect(res).to.have.status(200);
    expect(res.body.request_id.startsWith('support-group-' + project._id + '-')).to.equal(true);
    expect(res.body.request_id.split('-')).to.have.length(4);
  });
});
```

- [ ] **Step 3: Run the tests to verify they fail**

Run: `npx mocha test/webhookConversationRoute.js --exit`
Expected: FAIL — e.g. `expected undefined to equal 'conversation'` (mode not persisted), `expected 500 to equal 422`, `expected 200 to equal 404`.

- [ ] **Step 4: Add the model fields**

In `models/webhook.js`, replace the `enabled` field block (lines 37-41) with:

```js
  enabled: {
    type: Boolean,
    required: true,
    default: true
  },
  mode: {
    type: String,
    enum: ['conversation'],
    required: false
  },
  department_id: {
    type: String,
    required: false
  },
  source_name: {
    type: String,
    required: false
  }
```

- [ ] **Step 5: Create the settings validator**

Create `services/webhookSettingsValidator.js`:

```js
const mongoose = require('mongoose');
const Faq_kb = require('../models/faq_kb');
const Faq = require('../models/faq');
const Department = require('../models/department');
const chatbotTypes = require('../models/chatbotTypes');

const CONVERSATION_MODE = 'conversation';
const START_INTENT_NAME = 'start';

class WebhookSettingsValidator {

  constructor() {
    this.CONVERSATION_MODE = CONVERSATION_MODE;
  }

  async findChatbot(id_project, chatbot_id) {
    if (!chatbot_id || !mongoose.Types.ObjectId.isValid(chatbot_id)) {
      return null;
    }
    return Faq_kb.findOne({ _id: chatbot_id, id_project: id_project, trashed: { $in: [null, false] } }).lean().exec();
  }

  /**
   * Validates the conversation-related fields of a webhook create/update body.
   * Only the keys present in body are returned in fields.
   * @returns {Promise<{ok: true, fields: Object} | {ok: false, status: number, message: string}>}
   */
  async validate(id_project, chatbot, body) {
    const fields = {};

    if (body.hasOwnProperty('mode')) {
      if (body.mode !== CONVERSATION_MODE) {
        return { ok: false, status: 422, message: "Invalid webhook mode " + body.mode };
      }
      const subtype = chatbot.subtype || chatbotTypes.CHATBOT;
      if (subtype !== chatbotTypes.CHATBOT) {
        return { ok: false, status: 422, message: "Conversation mode requires a chatbot with subtype " + chatbotTypes.CHATBOT };
      }
      fields.mode = CONVERSATION_MODE;

      if (body.block_id) {
        fields.block_id = body.block_id;
      } else {
        const startIntent = await Faq.findOne({ id_faq_kb: chatbot._id.toString(), intent_display_name: START_INTENT_NAME }).lean().exec();
        if (!startIntent) {
          return { ok: false, status: 422, message: "Start block not found for chatbot " + chatbot._id };
        }
        fields.block_id = startIntent.intent_id;
      }
    } else if (body.block_id) {
      fields.block_id = body.block_id;
    }

    if (body.hasOwnProperty('department_id')) {
      if (body.department_id) {
        if (!mongoose.Types.ObjectId.isValid(body.department_id)) {
          return { ok: false, status: 422, message: "Department not found with id " + body.department_id };
        }
        const department = await Department.findOne({ _id: body.department_id, id_project: id_project }).lean().exec();
        if (!department) {
          return { ok: false, status: 422, message: "Department not found with id " + body.department_id };
        }
        fields.department_id = body.department_id;
      } else {
        fields.department_id = null;
      }
    }

    if (body.hasOwnProperty('source_name')) {
      fields.source_name = body.source_name;
    }

    return { ok: true, fields: fields };
  }
}

module.exports = new WebhookSettingsValidator();
```

- [ ] **Step 6: Use the validator in `routes/webhooks.js`**

Add after `var ObjectId = require('mongoose').Types.ObjectId;` (line 8):

```js
const webhookSettingsValidator = require('../services/webhookSettingsValidator');
const UIDGenerator = require('../utils/UIDGenerator');

const SETTINGS_KEYS = ['mode', 'block_id', 'department_id', 'source_name'];

function hasSettings(body) {
  return SETTINGS_KEYS.some((key) => body.hasOwnProperty(key));
}

/**
 * Loads the chatbot and validates the settings of body.
 * @returns {Promise<{ok: true, fields: Object} | {ok: false, status: number, message: string}>}
 */
async function validateSettings(id_project, chatbot_id, body) {
  const chatbot = await webhookSettingsValidator.findChatbot(id_project, chatbot_id);
  if (!chatbot) {
    return { ok: false, status: 404, message: "Chatbot not found with id " + chatbot_id };
  }
  return webhookSettingsValidator.validate(id_project, chatbot, body);
}
```

Replace the whole `router.post('/', ...)` handler (lines 67-93) with:

```js
router.post('/', async (req, res) => {

  let id_project = req.projectid;
  let chatbot_id = req.body.chatbot_id || req.body.id_faq_kb;

  let validation;
  try {
    validation = await validateSettings(id_project, chatbot_id, req.body);
  } catch (err) {
    winston.error("Error validating new webhook ", err);
    return res.status(500).send({ success: false, error: "Error validating webhook for chatbot " + chatbot_id });
  }

  if (!validation.ok) {
    winston.verbose("Invalid webhook for chatbot " + chatbot_id + ": " + validation.message);
    return res.status(validation.status).send({ success: false, error: validation.message });
  }

  let webhook = new Webhook(Object.assign({
    id_project: id_project,
    name: "webhook-" + this.webhook_id,
    chatbot_id: chatbot_id,
    block_id: req.body.block_id,
    copilot: req.body.copilot,
    async: req.body.async
  }, validation.fields));

  webhook.save((err, savedWebhook) => {
    if (err) {
      if (err.code === 11000) {
        winston.verbose("Webhook already exists for chatbot " + webhook.chatbot_id);
        return res.status(403).send({ success: false, message: "Webhook already exists for chatbot " + webhook.chatbot_id });
      } 
      winston.error("Error saving new webhook ", err);
      return res.status(500).send({ success: false, error: err });
    }

    res.status(200).send(savedWebhook);
  })

})
```

Replace the body of `router.post('/preload/:webhook_id', ...)` (lines 95-112) with:

```js
router.post('/preload/:webhook_id', async (req, res) => {

  let id_project = req.projectid;
  let webhook_id = req.params.webhook_id;
  let redis_client = req.app.get('redis_client');

  let webhook;
  try {
    webhook = await Webhook.findOne({ id_project: id_project, webhook_id: webhook_id }).lean().exec();
  } catch (err) {
    winston.error("Error finding webhook for preload ", err);
    return res.status(500).send({ success: false, message: "Unable to start development webhook" });
  }

  let request_id;
  if (webhook && webhook.mode === webhookSettingsValidator.CONVERSATION_MODE) {
    request_id = "support-group-" + id_project + "-" + UIDGenerator.generate();
  } else {
    request_id = "automation-request-" + id_project + "-" + new ObjectId() + "-" + webhook_id;
  }

  try {
    let key = "logs:webhook:" + id_project + ":" + webhook_id;
    let value = JSON.stringify({ request_id: request_id });
    redis_client.set(key, value, { EX: 900 });
    res.status(200).send({ success: true, message: "Webhook preloaded successfully", request_id: request_id });
  } catch(err) {
    winston.error("Error adding key in cache ", err);
    res.status(500).send({ success: false, message: "Unable to start development webhook" })
  }

})
```

In `router.put("/:chatbot_id", ...)`, insert immediately before `let updatedWebhook = await Webhook.findOneAndUpdate(` (line 201):

```js
  if (hasSettings(req.body)) {
    let validation;
    try {
      validation = await validateSettings(id_project, chatbot_id, req.body);
    } catch (err) {
      winston.error("Error validating webhook update ", err);
      return res.status(500).send({ success: false, error: "Error validating webhook for chatbot " + chatbot_id });
    }
    if (!validation.ok) {
      return res.status(validation.status).send({ success: false, error: validation.message });
    }
    Object.assign(update, validation.fields);
  }
```

In `router.put('/update/:webhook_id', ...)`, insert immediately before `let updatedWebhook = await Webhook.findOneAndUpdate(` (line 233):

```js
  if (hasSettings(req.body)) {
    let existing;
    try {
      existing = await Webhook.findOne({ id_project: id_project, webhook_id: webhook_id }).lean().exec();
    } catch (err) {
      winston.error("Error finding webhook for update ", err);
      return res.status(500).send({ success: false, error: "Error updating webhook with id " + webhook_id });
    }
    if (!existing) {
      return res.status(404).send({ success: false, error: "Webhook not found with id " + webhook_id });
    }
    let validation;
    try {
      validation = await validateSettings(id_project, existing.chatbot_id, req.body);
    } catch (err) {
      winston.error("Error validating webhook update ", err);
      return res.status(500).send({ success: false, error: "Error validating webhook with id " + webhook_id });
    }
    if (!validation.ok) {
      return res.status(validation.status).send({ success: false, error: validation.message });
    }
    Object.assign(update, validation.fields);
  }
```

- [ ] **Step 7: Run the new tests to verify they pass**

Run: `npx mocha test/webhookConversationRoute.js --exit`
Expected: PASS (7 passing).

- [ ] **Step 8: Run the existing webhook tests (backward compatibility)**

Run: `npx mocha test/webhookRoute.js --exit`
Expected: PASS, same number of passing tests as on `master` (run `git stash; npx mocha test/webhookRoute.js --exit; git stash pop` first if you need the baseline count).

- [ ] **Step 9: Commit**

```bash
git add models/webhook.js services/webhookSettingsValidator.js routes/webhooks.js test/webhookConversationTestUtils.js test/webhookConversationRoute.js
git commit -m "feat(webhooks): add conversation mode, department and source settings

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 2: Conversation starter service

**Files:**
- Create: `services/webhookConversationService.js`
- Create: `test/webhookConversationService.js`

**Interfaces:**
- Consumes: `Webhook` fields from Task 1 (`mode`, `department_id`, `source_name`).
- Produces:
  - `webhookConversationService.SOURCE_CHANNEL === 'webhook'`
  - `webhookConversationService.newRequestId(id_project: string): string`
  - `webhookConversationService.start(webhook: Object, chatbot: Object, payload: Object, options?: {dev?: boolean, request_id?: string}): Promise<{request_id: string, request: Object}>`
  - Errors thrown carry `err.status` (`422` misconfigured department, `403` quota exceeded); other errors have no `status`.

- [ ] **Step 1: Write the failing service tests**

Create `test/webhookConversationService.js`:

```js
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';
process.env.LOG_LEVEL = 'error';

const chai = require('chai');
const expect = chai.expect;
const config = require('../config/database');
const mongoose = require('mongoose');

mongoose.connect(config.databasetest);
require('../services/mongoose-cache-fn')(mongoose);

const userService = require('../services/userService');
const projectService = require('../services/projectService');
const faqService = require('../services/faqService');
const departmentService = require('../services/departmentService');
const webhookConversationService = require('../services/webhookConversationService');
const Request = require('../models/request');
const Message = require('../models/message');
const Lead = require('../models/lead');
const { Webhook } = require('../models/webhook');
const { waitFor, uniqueEmail, PWD } = require('./webhookConversationTestUtils');

async function setup(webhookFields = {}) {
  const user = await userService.signup(uniqueEmail('test-webhook-conv-service'), PWD, 'Test', 'User');
  const project = await projectService.create('test-webhook-conversation-service', user._id);
  const chatbot = await faqService.create(project._id, user._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
  const webhook = await new Webhook(Object.assign({
    id_project: project._id.toString(),
    chatbot_id: chatbot._id.toString(),
    block_id: 'start-intent-id',
    mode: 'conversation',
    source_name: 'Grafana alerts'
  }, webhookFields)).save();
  return { user, project, chatbot, webhook };
}

describe('WebhookConversationService', function () {

  this.timeout(20000);

  it('creates a lead, a bot-assigned request in the default department and a /start message', async () => {
    const { project, chatbot, webhook } = await setup();
    const defaultDepartment = await departmentService.getDefaultDepartment(project._id);

    const result = await webhookConversationService.start(webhook, chatbot, { alert: 'KubePodCrashLooping', webhook_http_method: 'POST' }, {});

    expect(result.request_id.startsWith('support-group-' + project._id + '-')).to.equal(true);

    const request = await Request.findOne({ request_id: result.request_id, id_project: project._id.toString() }).lean().exec();
    expect(request.participants).to.deep.equal(['bot_' + chatbot._id.toString()]);
    expect(request.participantsBots).to.deep.equal([chatbot._id.toString()]);
    expect(request.hasBot).to.equal(true);
    expect(request.status).to.equal(200);
    expect(request.channel.name).to.equal('webhook');
    expect(request.department.toString()).to.equal(defaultDepartment.id);
    expect(request.first_text).to.equal('/start');
    expect(request.attributes.webhook_id).to.equal(webhook.webhook_id);
    expect(request.attributes.payload.alert).to.equal('KubePodCrashLooping');
    expect(request.draft).to.not.equal(true);

    const lead = await Lead.findById(request.lead).lean().exec();
    expect(lead.lead_id).to.equal('webhook_' + webhook.webhook_id);
    expect(lead.fullname).to.equal('Grafana alerts');

    const startMessage = await waitFor(() => Message.findOne({ recipient: result.request_id, text: '/start' }).lean().exec());
    expect(startMessage.sender).to.equal('system');
    expect(startMessage.attributes.subtype).to.equal('info');
  });

  it('uses the configured department and the given request id in dev mode', async () => {
    const { user, project } = await setup();
    const department = await departmentService.create('SRE', project._id, 'assigned', user._id);
    const chatbotInProject = await faqService.create(project._id, user._id, { name: 'hitl-bot-2', type: 'tilebot', language: 'en', template: 'blank' });
    const devWebhook = await new Webhook({
      id_project: project._id.toString(),
      chatbot_id: chatbotInProject._id.toString(),
      block_id: 'start-intent-id',
      mode: 'conversation',
      department_id: department._id.toString()
    }).save();
    const request_id = webhookConversationService.newRequestId(project._id.toString());

    const result = await webhookConversationService.start(devWebhook, chatbotInProject, { alert: 'dev' }, { dev: true, request_id: request_id });

    expect(result.request_id).to.equal(request_id);
    const request = await Request.findOne({ request_id: request_id }).lean().exec();
    expect(request.department.toString()).to.equal(department._id.toString());
    expect(request.draft).to.equal(true);
    expect(request.attributes.sourcePage).to.include('&td_draft=true');
  });

  it('rejects with status 422 when the configured department does not exist', async () => {
    const { chatbot, webhook } = await setup({ department_id: '5f0000000000000000000000' });

    let error;
    try {
      await webhookConversationService.start(webhook, chatbot, {}, {});
    } catch (err) {
      error = err;
    }
    expect(error).to.exist;
    expect(error.status).to.equal(422);
  });
});
```

- [ ] **Step 2: Run the tests to verify they fail**

Run: `npx mocha test/webhookConversationService.js --exit`
Expected: FAIL with `Cannot find module '../services/webhookConversationService'`.

- [ ] **Step 3: Implement the service**

Create `services/webhookConversationService.js`:

```js
const Request = require('../models/request');
const Department = require('../models/department');
const leadService = require('./leadService');
const requestService = require('./requestService');
const messageService = require('./messageService');
const requestEvent = require('../event/requestEvent');
const UIDGenerator = require('../utils/UIDGenerator');
const winston = require('../config/winston');

const SOURCE_CHANNEL = 'webhook';
const START_TEXT = '/start';

class WebhookConversationError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

class WebhookConversationService {

  constructor() {
    this.SOURCE_CHANNEL = SOURCE_CHANNEL;
  }

  newRequestId(id_project) {
    return 'support-group-' + id_project + '-' + UIDGenerator.generate();
  }

  async resolveDepartment(id_project, department_id) {
    let department;
    if (department_id) {
      department = await Department.findOne({ _id: department_id, id_project: id_project }).lean().exec();
      if (!department) {
        throw new WebhookConversationError(422, 'Webhook misconfigured: department not found with id ' + department_id);
      }
      return department;
    }
    department = await Department.findOne({ id_project: id_project, default: true }).lean().exec();
    if (!department) {
      throw new WebhookConversationError(422, 'Webhook misconfigured: default department not found for project ' + id_project);
    }
    return department;
  }

  /**
   * Starts a chatbot conversation the same way the widget does: request with the bot as
   * participant, then the system /start info message that botEvent forwards to the bot.
   */
  async start(webhook, chatbot, payload, options = {}) {
    const id_project = webhook.id_project.toString();
    const request_id = options.request_id || this.newRequestId(id_project);
    const department = await this.resolveDepartment(id_project, webhook.department_id);

    const lead = await leadService.createIfNotExistsWithLeadId(
      'webhook_' + webhook.webhook_id,
      webhook.source_name || webhook.name || 'Webhook',
      undefined,
      id_project,
      'system',
      { webhook_id: webhook.webhook_id }
    );

    const attributes = { webhook_id: webhook.webhook_id, payload: payload || {} };
    let sourcePage;
    if (options.dev === true) {
      // BotSubscriptionNotifier matches "&td_draft=true", requestService.create matches "td_draft=true"
      sourcePage = 'webhook://' + webhook.webhook_id + '?dev=true&td_draft=true';
      attributes.sourcePage = sourcePage;
    }

    try {
      await requestService.create({
        request_id: request_id,
        lead_id: lead._id,
        lead: lead,
        id_project: id_project,
        first_text: START_TEXT,
        departmentid: department._id.toString(),
        participants: ['bot_' + chatbot._id.toString()],
        channel: { name: SOURCE_CHANNEL },
        sourcePage: sourcePage,
        preflight: false,
        createdBy: 'system',
        attributes: attributes
      });
    } catch (err) {
      if (err && err.message && err.message.startsWith('Requests limits reached')) {
        throw new WebhookConversationError(403, 'Requests quota exceeded for project ' + id_project);
      }
      throw err;
    }

    // requestService.create drops the department when participants are passed (see TODO item 1)
    const updatedRequest = await Request.findOneAndUpdate(
      { request_id: request_id, id_project: id_project },
      { $set: { department: department._id, 'snapshot.department': department } },
      { new: true }
    )
      .populate('lead')
      .populate('department')
      .populate('participatingBots')
      .populate('participatingAgents')
      .populate({ path: 'requester', populate: { path: 'id_user' } })
      .exec();
    requestEvent.emit('request.update', updatedRequest);

    await messageService.send('system', 'Bot', request_id, START_TEXT, id_project, null, { subtype: 'info', updateconversation: false });

    winston.verbose('(WebhookConversationService) conversation ' + request_id + ' started from webhook ' + webhook.webhook_id);
    return { request_id: request_id, request: updatedRequest };
  }
}

const webhookConversationService = new WebhookConversationService();
webhookConversationService.WebhookConversationError = WebhookConversationError;

module.exports = webhookConversationService;
```

- [ ] **Step 4: Run the tests to verify they pass**

Run: `npx mocha test/webhookConversationService.js --exit`
Expected: PASS (3 passing).

- [ ] **Step 5: Commit**

```bash
git add services/webhookConversationService.js test/webhookConversationService.js
git commit -m "feat(webhooks): start chatbot conversations from conversation-mode webhooks

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 3: Branch the public webhook routes on `mode`

**Files:**
- Modify: `routes/webhook.js` (imports `:1-13`, `router.all('/:webhook_id')` `:263-322`, `router.all('/:webhook_id/dev')` `:324-357`)
- Modify: `test/webhookConversationRoute.js` (append a `describe`)

**Interfaces:**
- Consumes: `webhookSettingsValidator.CONVERSATION_MODE`, `webhookSettingsValidator.findChatbot` (Task 1); `webhookConversationService.start` (Task 2).
- Produces: `POST|GET /webhook/:webhook_id` and `/webhook/:webhook_id/dev` return `202 {success: true, request_id}` for `mode: 'conversation'`; errors `{success: false, error}` with 404/422/429/403/500.

- [ ] **Step 1: Write the failing route tests**

Append to `test/webhookConversationRoute.js`:

```js
const Request = require('../models/request');
const Message = require('../models/message');
const { waitFor } = require('./webhookConversationTestUtils');

async function createWebhook(ctx, body) {
  const res = await chai.request(server)
    .post('/' + ctx.project._id + '/webhooks/')
    .auth(ctx.email, ctx.pwd)
    .send(Object.assign({ chatbot_id: ctx.chatbot_id }, body));
  expect(res).to.have.status(200);
  return res.body;
}

describe('WebhookConversationRoute - run', function () {

  this.timeout(20000);

  it('keeps the automation behaviour for a chatbot webhook without mode', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { block_id: 'legacy-block' });

    const res = await chai.request(server).post('/webhook/' + webhook.webhook_id).send({ alert: 'legacy' });

    expect(res).to.have.status(200);
    expect(res.body.success).to.equal(true);
    expect(res.body.message).to.equal('Webhook disabled in test mode');
  });

  it('starts a conversation for a conversation-mode webhook', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation', source_name: 'Grafana alerts' });

    const res = await chai.request(server)
      .post('/webhook/' + webhook.webhook_id + '?env=prod')
      .send({ alert: 'KubePodCrashLooping' });

    expect(res).to.have.status(202);
    expect(res.body.success).to.equal(true);
    expect(res.body.request_id.startsWith('support-group-' + ctx.project._id + '-')).to.equal(true);

    const request = await Request.findOne({ request_id: res.body.request_id }).lean().exec();
    expect(request.participants).to.deep.equal(['bot_' + ctx.chatbot_id]);
    expect(request.channel.name).to.equal('webhook');
    expect(request.attributes.payload.alert).to.equal('KubePodCrashLooping');
    expect(request.attributes.payload.webhook_http_method).to.equal('POST');
    expect(request.attributes.payload.webhook_query_params.env).to.equal('prod');

    await waitFor(() => Message.findOne({ recipient: res.body.request_id, text: '/start' }).lean().exec());
  });

  it('returns 422 for a disabled conversation webhook', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation' });
    await chai.request(server).put('/' + ctx.project._id + '/webhooks/' + ctx.chatbot_id).auth(ctx.email, ctx.pwd).send({ enabled: false });

    const res = await chai.request(server).post('/webhook/' + webhook.webhook_id).send({});
    expect(res).to.have.status(422);
  });

  it('returns 422 on the dev route without preload', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation' });

    const res = await chai.request(server).post('/webhook/' + webhook.webhook_id + '/dev').send({});
    expect(res).to.have.status(422);
    expect(res.body.code).to.equal(13001);
  });

  it('starts a draft conversation with the preloaded request id on the dev route', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation' });
    const preload = await chai.request(server).post('/' + ctx.project._id + '/webhooks/preload/' + webhook.webhook_id).auth(ctx.email, ctx.pwd);
    expect(preload).to.have.status(200);
    await new Promise((resolve) => setTimeout(resolve, 200)); // preload writes to Redis without awaiting

    const res = await chai.request(server).post('/webhook/' + webhook.webhook_id + '/dev').send({ alert: 'dev' });

    expect(res).to.have.status(202);
    expect(res.body.request_id).to.equal(preload.body.request_id);
    const request = await Request.findOne({ request_id: res.body.request_id }).lean().exec();
    expect(request.draft).to.equal(true);
  });

  it('returns 422 on the dev route for a disabled conversation webhook', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation' });
    await chai.request(server).post('/' + ctx.project._id + '/webhooks/preload/' + webhook.webhook_id).auth(ctx.email, ctx.pwd);
    await chai.request(server).put('/' + ctx.project._id + '/webhooks/' + ctx.chatbot_id).auth(ctx.email, ctx.pwd).send({ enabled: false });

    const res = await chai.request(server).post('/webhook/' + webhook.webhook_id + '/dev').send({});
    expect(res).to.have.status(422);
  });

  it('rate limits conversation webhooks', async () => {
    const ctx = await setupProjectWithBot(server);
    const webhook = await createWebhook(ctx, { mode: 'conversation' });

    // The bucket capacity is read once when the app is first required (2 if this file loads
    // the app, 10 by default if another test file loaded it first): call until limited.
    const statuses = [];
    for (let i = 0; i < 15 && !statuses.includes(429); i++) {
      const res = await chai.request(server).post('/webhook/' + webhook.webhook_id).send({ i: i });
      statuses.push(res.status);
    }
    expect(statuses).to.include(429);
    expect(statuses.filter((s) => s !== 429 && s !== 202)).to.deep.equal([]);
  });
});
```

- [ ] **Step 2: Run the tests to verify they fail**

Run: `npx mocha test/webhookConversationRoute.js --exit`
Expected: the 7 settings tests PASS; in "run", `keeps the automation behaviour…` PASSES and the others FAIL (e.g. `expected 200 to equal 202`, `expected 200 to equal 422`).

- [ ] **Step 3: Implement the branch in `routes/webhook.js`**

Add after `const default_embedding = require('../config/kb/embedding');` (line 13):

```js
const webhookSettingsValidator = require('../services/webhookSettingsValidator');
const webhookConversationService = require('../services/webhookConversationService');

async function startConversation(res, webhook, payload, options) {
  let chatbot;
  try {
    chatbot = await webhookSettingsValidator.findChatbot(webhook.id_project, webhook.chatbot_id);
  } catch (err) {
    winston.error("Error finding chatbot for webhook conversation ", err);
    return res.status(500).send({ success: false, error: "Error finding chatbot " + webhook.chatbot_id });
  }
  if (!chatbot) {
    return res.status(404).send({ success: false, error: "Chatbot not found with id " + webhook.chatbot_id });
  }

  try {
    const result = await webhookConversationService.start(webhook, chatbot, payload, options);
    if (options.dev !== true) {
      webhookEvent.emit("webhook.triggered", { webhook: webhook, payload: { preloaded_request_id: result.request_id } });
    }
    return res.status(202).send({ success: true, request_id: result.request_id });
  } catch (err) {
    if (!err.status) {
      winston.error("Error starting webhook conversation for webhook " + webhook.webhook_id, err);
    }
    return res.status(err.status || 500).send({ success: false, error: err.status ? err.message : "Error starting conversation" });
  }
}
```

In `router.all('/:webhook_id', ...)`, insert immediately before `payload.request_id = "automation-request-" + webhook.id_project + "-" + new ObjectId() + "-" + webhook_id;`:

```js
  if (webhook.mode === webhookSettingsValidator.CONVERSATION_MODE) {
    return startConversation(res, webhook, payload, { dev: false });
  }
```

In `router.all('/:webhook_id/dev', ...)`, insert immediately before `let redis_client = req.app.get('redis_client');`:

```js
  if (webhook.mode === webhookSettingsValidator.CONVERSATION_MODE) {
    if (!webhook.enabled) {
      return res.status(422).send({ success: false, error: "Webhook " + webhook_id + " is currently turned off" });
    }

    const rate_manager = req.app.get("rate_manager");
    const allowed = await rate_manager.canExecute(webhook.id_project, null, 'webhook');
    if (!allowed) {
      return res.status(429).send({ message: "Rate limit exceeded" });
    }

    let preloaded;
    try {
      preloaded = await req.app.get('redis_client').get("logs:webhook:" + webhook.id_project + ":" + webhook.webhook_id);
    } catch (err) {
      winston.error("Error reading preloaded development request ", err);
      return res.status(500).send({ success: false, error: "Unable to read development request" });
    }
    if (!preloaded) {
      return res.status(422).send({ success: false, message: "Development webhook is currently turned off", code: errorCodes.WEBHOOK.ERRORS.NO_PRELOADED_DEV_REQUEST });
    }

    return startConversation(res, webhook, payload, { dev: true, request_id: JSON.parse(preloaded).request_id });
  }
```

- [ ] **Step 4: Run the tests to verify they pass**

Run: `npx mocha test/webhookConversationRoute.js --exit`
Expected: PASS (14 passing).

- [ ] **Step 5: Run backward-compatibility suites**

Run: `npx mocha test/webhookRoute.js test/webhookConversationService.js --exit`
Expected: PASS.

- [ ] **Step 6: Commit**

```bash
git add routes/webhook.js test/webhookConversationRoute.js
git commit -m "feat(webhooks): start conversations from conversation-mode webhook calls

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 4: Invite participants service and endpoint

**Files:**
- Create: `services/participantInviteService.js`
- Modify: `routes/request.js` (imports near line 36; new route right after `router.post('/:requestid/participants', ...)` which ends at `:423`)
- Create: `test/inviteParticipantsRoute.js`

**Interfaces:**
- Consumes: none from earlier tasks (works on any request).
- Produces:
  - `participantInviteService.invite(id_project: string, request_id: string, {department_id?: string, members?: string[]}): Promise<{request_id: string, department_id: string|null, invited: Array<{id_user: string, fullname: string, already_participant: boolean}>, reason?: 'no_available_agents'}>`; errors carry `err.status` (404, 409, 422).
  - Request marker after a successful invite: `workingStatus === 'pending'`, `attributes.hitl_waiting === true`.
  - HTTP `POST /:projectid/requests/:requestid/participants/invite` → `200` with the object above, or `{success: false, error}` with the error status.

- [ ] **Step 1: Write the failing tests**

Create `test/inviteParticipantsRoute.js`:

```js
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';
process.env.LOG_LEVEL = 'error';

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../app');
const expect = chai.expect;
chai.use(chaiHttp);

const userService = require('../services/userService');
const projectService = require('../services/projectService');
const departmentService = require('../services/departmentService');
const faqService = require('../services/faqService');
const requestService = require('../services/requestService');
const Project_user = require('../models/project_user');
const Request = require('../models/request');
const RoleConstants = require('../models/roleConstants');
const { uniqueEmail, PWD } = require('./webhookConversationTestUtils');

async function addAgent(project, owner, { available = true } = {}) {
  const email = uniqueEmail('test-invite-agent');
  const agent = await userService.signup(email, PWD, 'Agent', 'Smith');
  await new Project_user({
    id_project: project._id.toString(),
    id_user: agent._id.toString(),
    role: RoleConstants.AGENT,
    roleType: RoleConstants.TYPE_AGENTS,
    user_available: available,
    createdBy: owner._id.toString(),
    updatedBy: owner._id.toString()
  }).save();
  return { agent, email };
}

async function setup({ ownerAvailable = true } = {}) {
  const ownerEmail = uniqueEmail('test-invite-owner');
  const owner = await userService.signup(ownerEmail, PWD, 'Owner', 'User');
  const project = await projectService.create('test-invite-participants', owner._id);
  if (!ownerAvailable) {
    await Project_user.findOneAndUpdate({ id_project: project._id, id_user: owner._id }, { user_available: false }).exec();
  }
  const chatbot = await faqService.create(project._id, owner._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
  const request = await requestService.create({
    request_id: 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000),
    id_project: project._id.toString(),
    first_text: '/start',
    participants: ['bot_' + chatbot._id.toString()],
    channel: { name: 'webhook' },
    preflight: false,
    createdBy: 'system'
  });
  return { owner, ownerEmail, project, chatbot, request };
}

function invite(ctx, body, auth) {
  const req = chai.request(server).post('/' + ctx.project._id + '/requests/' + ctx.request.request_id + '/participants/invite');
  if (auth && auth.jwt) {
    req.set('Authorization', 'JWT ' + auth.jwt);
  } else {
    req.auth(ctx.ownerEmail, PWD);
  }
  return req.send(body);
}

describe('InviteParticipantsRoute', function () {

  this.timeout(20000);

  it('invites all named members that are active agents and keeps the bot', async () => {
    const ctx = await setup();
    const a1 = await addAgent(ctx.project, ctx.owner);
    const a2 = await addAgent(ctx.project, ctx.owner, { available: false });

    const res = await invite(ctx, { members: [a1.email, a2.agent._id.toString(), 'unknown@email.com'] });

    expect(res).to.have.status(200);
    expect(res.body.invited.map((i) => i.id_user).sort()).to.deep.equal([a1.agent._id.toString(), a2.agent._id.toString()].sort());
    expect(res.body.invited.every((i) => i.already_participant === false)).to.equal(true);

    const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
    expect(request.participants).to.include('bot_' + ctx.chatbot._id.toString());
    expect(request.participants).to.include(a1.agent._id.toString());
    expect(request.participants).to.include(a2.agent._id.toString());
    expect(request.workingStatus).to.equal('pending');
    expect(request.attributes.hitl_waiting).to.equal(true);
  });

  it('falls back to the department when no member resolves', async () => {
    const ctx = await setup();

    const res = await invite(ctx, { members: ['nobody@email.com'] });

    expect(res).to.have.status(200);
    expect(res.body.invited).to.have.length(1);
    expect(res.body.invited[0].id_user).to.equal(ctx.owner._id.toString());
  });

  it('invites exactly one available agent from a pooled department', async () => {
    const ctx = await setup({ ownerAvailable: false });
    const pooled = await departmentService.create('SRE pooled', ctx.project._id, 'pooled', ctx.owner._id);
    const a1 = await addAgent(ctx.project, ctx.owner);
    const a2 = await addAgent(ctx.project, ctx.owner);

    const res = await invite(ctx, { department_id: pooled._id.toString() });

    expect(res).to.have.status(200);
    expect(res.body.invited).to.have.length(1);
    expect([a1.agent._id.toString(), a2.agent._id.toString()]).to.include(res.body.invited[0].id_user);
    expect(res.body.department_id).to.equal(pooled._id.toString());
  });

  it('invites the operator selected by an assigned department', async () => {
    const ctx = await setup();

    const res = await invite(ctx, {});

    expect(res).to.have.status(200);
    expect(res.body.invited).to.have.length(1);
    expect(res.body.invited[0].id_user).to.equal(ctx.owner._id.toString());
  });

  it('returns an empty invite list with a reason when nobody is available', async () => {
    const ctx = await setup({ ownerAvailable: false });

    const res = await invite(ctx, {});

    expect(res).to.have.status(200);
    expect(res.body.invited).to.deep.equal([]);
    expect(res.body.reason).to.equal('no_available_agents');
    const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
    expect(request.workingStatus).to.not.equal('pending');
  });

  it('reports members that are already participants', async () => {
    const ctx = await setup();
    const a1 = await addAgent(ctx.project, ctx.owner);
    await invite(ctx, { members: [a1.email] });

    const res = await invite(ctx, { members: [a1.email] });

    expect(res).to.have.status(200);
    expect(res.body.invited).to.have.length(1);
    expect(res.body.invited[0].already_participant).to.equal(true);
  });

  it('returns 409 for a closed request and 404 for an unknown request', async () => {
    const ctx = await setup();
    await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { status: 1000 } }).exec();

    const closed = await invite(ctx, {});
    expect(closed).to.have.status(409);

    const unknown = await chai.request(server)
      .post('/' + ctx.project._id + '/requests/support-group-unknown/participants/invite')
      .auth(ctx.ownerEmail, PWD)
      .send({});
    expect(unknown).to.have.status(404);
  });

  it('accepts the bot token of the same project and rejects a bot token of another project', async () => {
    const ctx = await setup();
    const other = await setup();

    const ownJwt = await chai.request(server).get('/' + ctx.project._id + '/faq_kb/' + ctx.chatbot._id + '/jwt').auth(ctx.ownerEmail, PWD);
    const otherJwt = await chai.request(server).get('/' + other.project._id + '/faq_kb/' + other.chatbot._id + '/jwt').auth(other.ownerEmail, PWD);

    const allowed = await invite(ctx, {}, { jwt: ownJwt.body.jwt });
    expect(allowed).to.have.status(200);

    const denied = await invite(ctx, {}, { jwt: otherJwt.body.jwt });
    expect(denied).to.have.status(403);
  });
});
```

- [ ] **Step 2: Run the tests to verify they fail**

Run: `npx mocha test/inviteParticipantsRoute.js --exit`
Expected: FAIL — requests to `/participants/invite` return 404 (route not found).

- [ ] **Step 3: Implement the service**

Create `services/participantInviteService.js`:

```js
const mongoose = require('mongoose');
const Request = require('../models/request');
const Project = require('../models/project');
const Project_user = require('../models/project_user');
const User = require('../models/user');
const Department = require('../models/department');
const RequestConstants = require('../models/requestConstants');
const RoleConstants = require('../models/roleConstants');
const requestService = require('./requestService');
const departmentService = require('./departmentService');
const emailService = require('./emailService');
const requestEvent = require('../event/requestEvent');
const winston = require('../config/winston');

const PENDING = 'pending';

class InviteError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

function toId(value) {
  return value && value.toString();
}

class ParticipantInviteService {

  async invite(id_project, request_id, { department_id, members } = {}) {
    const request = await Request.findOne({ request_id: request_id, id_project: id_project }).exec();
    if (!request) {
      throw new InviteError(404, 'Request not found with id ' + request_id);
    }
    if (request.status === RequestConstants.CLOSED) {
      throw new InviteError(409, 'Request ' + request_id + ' is closed');
    }

    const participants = (request.participants || []).map(toId);
    let invitees = await this.resolveMembers(id_project, members);
    let resolvedDepartmentId = null;

    if (invitees.length === 0) {
      const department = await this.resolveDepartment(id_project, department_id || toId(request.department));
      resolvedDepartmentId = toId(department._id);
      invitees = await this.pickFromDepartment(id_project, department, request, participants);
    }

    if (invitees.length === 0) {
      return { request_id: request_id, department_id: resolvedDepartmentId, invited: [], reason: 'no_available_agents' };
    }

    const invited = [];
    const newlyAdded = [];
    for (const id_user of invitees) {
      const already_participant = participants.includes(id_user);
      if (!already_participant) {
        await requestService.addParticipantByRequestId(request_id, id_project, id_user);
        newlyAdded.push(id_user);
      }
      invited.push({ id_user: id_user, fullname: await this.fullnameOf(id_user), already_participant: already_participant });
    }

    const updatedRequest = await this.markWaiting(request_id, id_project);
    this.notifyInvited(id_project, updatedRequest, newlyAdded);

    return { request_id: request_id, department_id: resolvedDepartmentId, invited: invited };
  }

  /** Resolves ids or emails to active agent-type project users of the project. */
  async resolveMembers(id_project, members) {
    if (!Array.isArray(members) || members.length === 0) {
      return [];
    }
    const ids = [];
    for (const member of members) {
      if (!member || typeof member !== 'string') {
        continue;
      }
      let id_user = null;
      if (mongoose.Types.ObjectId.isValid(member)) {
        id_user = member;
      } else {
        const user = await User.findOne({ email: member.trim().toLowerCase(), status: 100 }).lean().exec();
        id_user = user ? toId(user._id) : null;
      }
      if (!id_user) {
        continue;
      }
      const project_user = await Project_user.findOne({ id_project: id_project, id_user: id_user, roleType: RoleConstants.TYPE_AGENTS, status: 'active' }).lean().exec();
      if (project_user && !ids.includes(id_user)) {
        ids.push(id_user);
      }
    }
    return ids;
  }

  async resolveDepartment(id_project, department_id) {
    let department;
    if (department_id) {
      if (!mongoose.Types.ObjectId.isValid(department_id)) {
        throw new InviteError(422, 'Department not found with id ' + department_id);
      }
      department = await Department.findOne({ _id: department_id, id_project: id_project }).lean().exec();
      if (!department) {
        throw new InviteError(422, 'Department not found with id ' + department_id);
      }
      return department;
    }
    department = await Department.findOne({ id_project: id_project, default: true }).lean().exec();
    if (!department) {
      throw new InviteError(422, 'Default department not found for project ' + id_project);
    }
    return department;
  }

  /** One agent: the operator selected by assigned routing, or one random available agent for pooled routing. */
  async pickFromDepartment(id_project, department, request, participants) {
    const result = await departmentService.getOperators(toId(department._id), id_project, true, undefined, { request: request });

    const operators = (result.operators || []).map((op) => toId(op.id_user)).filter(Boolean);
    const freeOperators = operators.filter((id_user) => !participants.includes(id_user));
    if (freeOperators.length > 0) {
      return [freeOperators[0]];
    }
    if (operators.length > 0) {
      // the selected operator is already in the conversation: count it as invited
      return [operators[0]];
    }

    const available = (result.available_agents || []).filter((pu) => !participants.includes(toId(pu.id_user)));
    const picked = departmentService.getRandomAvailableOperator(available);
    return (picked || []).map((op) => toId(op.id_user));
  }

  async fullnameOf(id_user) {
    const user = await User.findById(id_user).lean().exec();
    if (!user) {
      return '';
    }
    return ((user.firstname || '') + ' ' + (user.lastname || '')).trim();
  }

  async markWaiting(request_id, id_project) {
    const updatedRequest = await Request.findOneAndUpdate(
      { request_id: request_id, id_project: id_project },
      { $set: { workingStatus: PENDING, 'attributes.hitl_waiting': true } },
      { new: true }
    )
      .populate('lead')
      .populate('department')
      .populate('participatingBots')
      .populate('participatingAgents')
      .populate({ path: 'requester', populate: { path: 'id_user' } })
      .exec();
    requestEvent.emit('request.workingStatus.update', { request: updatedRequest });
    requestEvent.emit('request.update', updatedRequest);
    return updatedRequest;
  }

  /** Same opt-outs as requestNotification.sendAgentEmail (assigned branch). Fire and forget. */
  notifyInvited(id_project, request, userIds) {
    if (!userIds || userIds.length === 0) {
      return;
    }
    setImmediate(async () => {
      try {
        const project = await Project.findOne({ _id: id_project, status: 100 }).select('+settings').exec();
        if (!project) {
          return;
        }
        const conversationSettings = project.settings && project.settings.email && project.settings.email.notification && project.settings.email.notification.conversation;
        if (conversationSettings && (conversationSettings.blocked === true || conversationSettings.assigned === false)) {
          return;
        }
        for (const id_user of userIds) {
          const project_user = await Project_user.findOne({ id_user: id_user, id_project: id_project, status: 'active' }).lean().exec();
          const userSettings = project_user && project_user.settings && project_user.settings.email && project_user.settings.email.notification && project_user.settings.email.notification.conversation;
          if (!project_user || (userSettings && userSettings.assigned && userSettings.assigned.toyou === false)) {
            continue;
          }
          const user = await User.findOne({ _id: id_user, status: 100 }).lean().exec();
          if (user) {
            emailService.sendNewAssignedRequestNotification(user.email, request, project);
          }
        }
      } catch (err) {
        winston.error('(ParticipantInviteService) error sending invite emails', err);
      }
    });
  }
}

const participantInviteService = new ParticipantInviteService();
participantInviteService.InviteError = InviteError;

module.exports = participantInviteService;
```

- [ ] **Step 4: Add the route**

In `routes/request.js`, add after `const faq_kb = require('../models/faq_kb');` (line 36):

```js
const participantInviteService = require('../services/participantInviteService');
```

Insert right after the `router.post('/:requestid/participants', ...)` handler (after its closing `});` at line 423):

```js
router.post('/:requestid/participants/invite', async (req, res) => {

  const body = req.body || {};
  let members = body.members;
  if (members !== undefined && !Array.isArray(members)) {
    return res.status(422).send({ success: false, error: "members must be an array" });
  }

  try {
    const result = await participantInviteService.invite(req.projectid, req.params.requestid, {
      department_id: body.department_id,
      members: members
    });
    return res.status(200).send(result);
  } catch (err) {
    if (!err.status) {
      winston.error("Error inviting participants to request " + req.params.requestid, err);
    }
    return res.status(err.status || 500).send({ success: false, error: err.status ? err.message : "Error inviting participants" });
  }
});
```

- [ ] **Step 5: Run the tests to verify they pass**

Run: `npx mocha test/inviteParticipantsRoute.js --exit`
Expected: PASS (8 passing).

- [ ] **Step 6: Run the request suites for regressions**

Run: `npx mocha test/requestRoute.js test/requestService.js --exit`
Expected: PASS (same results as on `master`).

- [ ] **Step 7: Commit**

```bash
git add services/participantInviteService.js routes/request.js test/inviteParticipantsRoute.js
git commit -m "feat(requests): invite platform users into a conversation while the bot stays

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 5: Reset the waiting protection when an invited human answers

**Files:**
- Modify: `event/messageEvent.js` (add a listener after the existing `message.create.from.requester` listener, which ends at `:203`)
- Create: `test/hitlWaitingReset.js`

**Interfaces:**
- Consumes: request marker from Task 4 (`workingStatus: 'pending'`, `attributes.hitl_waiting: true`); `participantInviteService.invite` (Task 4) in tests.
- Produces: on `message.create`, a waiting request goes back to `workingStatus: 'open'` and loses `attributes.hitl_waiting` when the sender is in `participantsAgents` and the message is not an info message (or is an info message carrying `attributes.action`).

- [ ] **Step 1: Write the failing tests**

Create `test/hitlWaitingReset.js`:

```js
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';
process.env.LOG_LEVEL = 'error';

const chai = require('chai');
const expect = chai.expect;
const config = require('../config/database');
const mongoose = require('mongoose');

mongoose.connect(config.databasetest);
require('../services/mongoose-cache-fn')(mongoose);

const userService = require('../services/userService');
const projectService = require('../services/projectService');
const faqService = require('../services/faqService');
const requestService = require('../services/requestService');
const messageService = require('../services/messageService');
const participantInviteService = require('../services/participantInviteService');
const Request = require('../models/request');
const { uniqueEmail, PWD } = require('./webhookConversationTestUtils');

async function waitingConversation() {
  const owner = await userService.signup(uniqueEmail('test-hitl-reset'), PWD, 'Owner', 'User');
  const project = await projectService.create('test-hitl-reset', owner._id);
  const chatbot = await faqService.create(project._id, owner._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
  const request_id = 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000);
  await requestService.create({
    request_id: request_id,
    id_project: project._id.toString(),
    first_text: '/start',
    participants: ['bot_' + chatbot._id.toString()],
    channel: { name: 'webhook' },
    preflight: false,
    createdBy: 'system'
  });
  await participantInviteService.invite(project._id.toString(), request_id, { members: [owner._id.toString()] });
  return { owner, project, chatbot, request_id };
}

async function statusAfter(request_id, ms = 700) {
  await new Promise((resolve) => setTimeout(resolve, ms));
  return Request.findOne({ request_id: request_id }).lean().exec();
}

describe('HITL waiting reset', function () {

  this.timeout(20000);

  it('reopens the conversation when the invited human writes', async () => {
    const ctx = await waitingConversation();

    await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Approve', ctx.project._id.toString(), ctx.owner._id.toString(), {});

    const request = await statusAfter(ctx.request_id);
    expect(request.workingStatus).to.equal('open');
    expect(request.attributes.hitl_waiting).to.equal(undefined);
  });

  it('reopens the conversation on an info message carrying an action (button click)', async () => {
    const ctx = await waitingConversation();

    await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Approve', ctx.project._id.toString(), ctx.owner._id.toString(), { subtype: 'info', action: 'approve_block' });

    const request = await statusAfter(ctx.request_id);
    expect(request.workingStatus).to.equal('open');
  });

  it('stays pending for bot messages and plain info messages', async () => {
    const ctx = await waitingConversation();

    await messageService.send('bot_' + ctx.chatbot._id.toString(), 'hitl-bot', ctx.request_id, 'Restart checkout-api?', ctx.project._id.toString(), 'system', {});
    await messageService.send(ctx.owner._id.toString(), 'Owner User', ctx.request_id, 'Owner joined', ctx.project._id.toString(), 'system', { subtype: 'info' });

    const request = await statusAfter(ctx.request_id);
    expect(request.workingStatus).to.equal('pending');
    expect(request.attributes.hitl_waiting).to.equal(true);
  });
});
```

- [ ] **Step 2: Run the tests to verify they fail**

Run: `npx mocha test/hitlWaitingReset.js --exit`
Expected: the first two tests FAIL with `expected 'pending' to equal 'open'`; the third PASSES.

- [ ] **Step 3: Implement the listener**

In `event/messageEvent.js`, insert right after the closing `});` of the `messageEvent.on('message.create.from.requester', ...)` listener (line 203):

```js
// HITL: when an invited human participant answers a conversation that is waiting for them,
// reopen it so the normal auto-close rules apply again (the requester rule above does not
// fire because the requester of webhook conversations is a source lead that never writes).
messageEvent.on('message.create', function (messageJson) {
  var request = messageJson.request;
  if (!request || !request.attributes || request.attributes.hitl_waiting !== true) return;

  var agents = (request.participantsAgents || []).map(function (id) { return id && id.toString(); });
  if (agents.indexOf(messageJson.sender) === -1) return;

  var attributes = messageJson.attributes || {};
  if (attributes.subtype === 'info' && !attributes.action) return;

  Request.findOneAndUpdate(
    { request_id: request.request_id, id_project: request.id_project, 'attributes.hitl_waiting': true },
    { $set: { workingStatus: 'open' }, $unset: { 'attributes.hitl_waiting': 1 } },
    { new: true },
    function (err, updatedRequest) {
      if (err) {
        winston.error("Error resetting HITL waiting status to open", err);
        return;
      }
      if (updatedRequest) {
        winston.debug("HITL request workingStatus set to open", { request_id: request.request_id });
        requestEvent.emit('request.workingStatus.update', { request: updatedRequest });
        requestEvent.emit('request.update', updatedRequest);
      }
    }
  );
});
```

- [ ] **Step 4: Run the tests to verify they pass**

Run: `npx mocha test/hitlWaitingReset.js --exit`
Expected: PASS (3 passing).

- [ ] **Step 5: Commit**

```bash
git add event/messageEvent.js test/hitlWaitingReset.js
git commit -m "feat(requests): reopen HITL-waiting conversations when the invited human answers

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 6: Full regression run

**Files:** none (verification only).

- [ ] **Step 1: Run all new and related suites together**

Run:
```bash
npx mocha test/webhookRoute.js test/webhookConversationRoute.js test/webhookConversationService.js test/inviteParticipantsRoute.js test/hitlWaitingReset.js test/requestRoute.js test/requestService.js test/messageRoute.js test/departmentService.js test/hasRole.js --exit
```
Expected: PASS. Any failure in a pre-existing suite must be compared against the same command on `origin/master` (in a separate worktree) before being attributed to this branch.

- [ ] **Step 2: Run the full test suite**

Run: `npm test`
Expected: same pass/fail set as `origin/master` plus the new passing tests. Record any pre-existing failures in the PR description instead of fixing them here.

- [ ] **Step 3: Review the branch diff**

Run: `git diff origin/master --stat` and confirm only the files listed in "File Structure" (plus the docs committed earlier) changed.
