# TODO — shared-code fixes found while designing webhook-started chatbot conversations

Status: **not scheduled** — optional follow-up. The webhook → chatbot conversation + "Invite human"
design (v1) must work without these; they are recorded here in case the work is wanted.

Context: design for starting conversational (`subtype: chatbot`) flows from a webhook and pausing for
human-in-the-loop answers from platform users in chat21-ionic.

---

## 1. `requestService.create` drops the department when `participants` are passed

- **Where:** `services/requestService.js`, `async create(request)` — the "Assignment" block.
- **Current behavior:** `dep_id = result.department._id` is only set inside
  `if (participants.length === 0)`. When a caller passes explicit participants
  (e.g. `participants: ['bot_<id>']`), the request is saved with `department: undefined`
  and `snapshot.department` is not set, even though `departmentid` was provided and resolved
  by `departmentService.getOperators`.
- **Effect:** department-based filters in the dashboard, `department_id`/`department_name` flow
  variables in tybot (`TiledeskChatbotUtil` reads `message.request.department`), department
  analytics and chat21 group attributes are missing for such requests.
- **Proposed fix:** when `status !== TEMP`, always set `dep_id = result.department._id`
  (and `snapshot.department`), independently of whether participants were passed.
- **Callers affected:** every caller of `requestService.create` that passes `participants`
  (`routes/request.js` POST `/`, `routes/message.js` POST `/` on first message, and the new
  webhook conversation starter). Behavior change = requests gain a department they previously lacked.
- **v1 workaround (without this fix):** the webhook conversation starter sets `department`
  with a targeted update on the created request right after `create`, before sending `/start`.
- **Tests:** create request with `participants` + `departmentid` → `department` and
  `snapshot.department` populated; existing request/message route tests still pass.

## 2. `addParticipantByRequestId` forces `hasBot = false` when a human is added

- **Where:** `services/requestService.js`, `addParticipantByRequestId(request_id, id_project, member, options)`.
- **Current behavior:** adding a non-bot member runs `request.hasBot = false; //???` even when a bot
  is still in `participants` / `participantsBots`.
- **Effect:** a conversation where the bot keeps running next to an invited human is flagged as
  not having a bot. Consumers of `hasBot` (indexes/jobs for closing unresponsive requests,
  analytics, any `hasBot` filter) see the wrong value. Bot message delivery is NOT affected
  (`event/botEvent.js` resolves the bot from `participants`).
- **Proposed fix:** recompute `request.hasBot = request.participantsBots.length > 0` after pushing
  the member (same in `removeParticipantByRequestId` / `setParticipantsByRequestId` for consistency).
- **Callers affected:** `POST /:projectid/requests/:requestid/participants`, dashboard "join",
  and the new invite endpoint.
- **Tests:** request with bot participant → add agent → `hasBot === true`,
  `participantsBots` unchanged; request without bot → add agent → `hasBot === false`.

## 3. (tiledesk-chatbot `main`) block jumps are swallowed by an active lock; Capture User Reply does not stop

- **Repo / base:** `tiledesk-chatbot`, branch `origin/main` (2.1.13). Already fixed on `main_pre`, not on `main`.
- **Where:**
  - `tybotRoute/engine/TiledeskChatbot.js` — locked-intent branch: `if (locked_intent)` on `main`
    vs `if (locked_intent && message.sender !== "_tdinternal")` on `main_pre`.
  - `tybotRoute/tiledeskChatbotPlugs/directives/DirIntent.js` — on `main` block jumps are sent through
    `/ext` as a message from `_tdinternal` (`sendMessageToBot`), not `/exec`.
  - `tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js` — on `main`, after locking it calls
    `callback()` (flow continues) instead of `callback(true)` (stop); lock key read from
    `this.reply.attributes.intent_info.intent_name` without guards.
- **Effect:** while a conversation is locked (waiting for a reply), any block jump in the same run is
  treated as the user's reply. With Capture User Reply not stopping, actions placed after it in the same
  block keep running and a jump among them is captured as the "answer".
- **v1 guidance (without this fix):** in HITL flows, put Capture User Reply as the LAST action of its block
  and prefer Reply V2 with buttons (which stops correctly); invite the human before asking.
- **Proposed fix:** backport the `main_pre` changes (the `_tdinternal` lock bypass, Capture User Reply
  `callback(true)` + guarded lock key) to `main` in a dedicated PR.
- **Tests:** locked conversation + internal jump → jump executes, lock untouched; Capture User Reply
  followed by another action in the same block → second action not executed until reply.

- **Status:** Done on tiledesk-chatbot feature/webhook-chatbot-hitl 5ee755dd (engine lock bypass for `_tdinternal`, action-lock bypass for internal jumps in `DirectivesChatbotPlug`, Capture User Reply stops the block); tests in `test/conversation-lock_internal_jump_test.js`. The fix goes beyond `main_pre`: (a) `DirectivesChatbotPlug.process()` also lets `_tdinternal` messages bypass the locked action (on `main_pre` only the engine check exists, so an internal jump made while locked would run nothing); (b) Capture User Reply now ends the block after its goToIntent jump — actions placed after a Capture with goToIntent in the same block no longer run after the reply (they used to run alongside the jump). Coordinate with the `main_pre` owner so these reach upstream instead of being reverted on the next merge. Follow-up: an internal jump into a block that contains a Capture or Reply V2 while another question is locked makes that action take its "reply" path, because locks are checked by existence; Capture and `DirReplyV2.lockUnlock` should compare the locked action id with their own `_tdActionId` and treat a different id as a first pass.

## 4. Pre-existing webhook issues found during the master re-verification (2026-09-15)

Not required by the design (the new conversation path does not reuse this code), recorded for a separate cleanup.
Lines refer to `tiledesk-server` master `5d240683` (2.24.2).

- **Bot secret leaked in the automation webhook token** — `services/webhookService.js:85-88`
  `generateChatbotToken` signs `chatbot.toObject()` including `secret` (JWT payload is readable, and tybot stores
  the token in flow variables). `services/BotSubscriptionNotifier.js:59-64` already deletes `secret`,
  `description`, `attributes` before signing — do the same. **Security-relevant; consider prioritising.**
- **`webhookService.run` crashes when the chatbot is missing** — `services/webhookService.js:31`: `reject(...)`
  without `return`, then `chatbot.url` is read on `undefined`.
- **Webhook model pre-save hook never resolves for existing documents** — `models/webhook.js:51-66`: `next()` is only
  called inside `if (this.isNew)`; any `.save()` on an existing webhook hangs. Also `winston` is used at `:73`
  (MONGOOSE_SYNCINDEX) without being required.
- **`/webhook/:webhook_id/dev` skips the `enabled` check and the rate limit** — `routes/webhook.js:324-357`
  (production route applies both at `:287` and `:291-294`).
- **Small route bugs** — `routes/webhooks.js:73` `name: "webhook-" + this.webhook_id` (overwritten by pre-save);
  `routes/webhooks.js:235` error message references undefined `chatbot_id`; `routes/webhooks.js:105`
  `redis_client.set` not awaited.
- **tiledesk-chatbot `main`** — `tybotRoute/tiledeskChatbotPlugs/directives/DirIfOnlineAgentsV2.js:140` references an
  undefined `intentDirective` (ReferenceError on the "no falseIntent" path); `tybotRoute/index.js` sync `/block`
  has no timeout and ignores send errors (`:633-658`).

## 5. Found during implementation (2026-09-15)

- **`models/user.js:69-75` `phone` is `unique: true` without `sparse: true`** — users saved
  without a `phone` collide on the shared `null` key (`E11000 duplicate key error ... phone: null`)
  once two or more such users exist and the index is built. `test/webhookConversationService.js`
  and `test/hitlWaitingReset.js` use `mongoose.set('autoIndex', false)` as a test-only stopgap.
  Suggested fix: add `sparse: true` to the `phone` field and migrate the existing index.
- **Circular require `event/messageEvent.js` → `models/faq_kb.js` → `event/botEvent.js` →
  `event/messageEvent.js`** — `npx mocha test/requestRoute.js --exit` run alone crashes before any
  test runs, on `origin/master` too; it stays latent only because of file-list/require ordering in
  the suites that currently pass. Suggested fix: make one edge of the cycle a lazy `require(...)`
  call inside the function that needs it instead of a top-level require.
- **Request cache read-through race** — `addParticipantByRequestId` emits `request.update` with the
  pre-marker document (its own cache write is deferred via `setImmediate`), and
  `populateMessageWithRequest`'s `.cache()` can then store a read taken before a later update.
  This affects cache readers such as the requester `pending → open` rule; the HITL reset listener
  (Ruling 9) avoids it by deciding on an atomic DB filter instead of trusting the cached request.
- **Email opt-out checks duplicated** — `services/participantInviteService.js`'s `notifyInvited`
  and `pubmodules/emailNotification/requestNotification.js`'s `sendAgentEmail` each re-implement the
  same project/user email opt-out logic (spec §5.4.7 asked for a shared helper); kept deferred by
  Ruling 14. Suggested fix: extract a shared `isOptedOutOfAssignedEmail(project, project_user)` helper.
- **Partial invite is not atomic** — in `participantInviteService.invite()`, if
  `addParticipantByRequestId` fails partway through a multi-member invite, the members added before
  the failure stay participants without the `hitl_waiting` marker or notification email, and the
  caller gets a 500. Deferred by Ruling 14. Suggested fix: either make the loop best-effort and
  report per-member outcomes, or roll back the participants added so far on failure.
- **24 pre-existing test failures on origin/master in this local environment** (FileRoute/
  ImagesRoute/KbSettingsRoute storage config, a DepartmentService missing import) — see
  `.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-server/task-6-report.md` for the list;
  reproduce before relying on a plain `npm test` run to judge this branch.
- **Concurrent participant removals can lose one removal** — `services/requestService.js`
  `removeParticipantByRequestId` loads the request, splices `participants`, and saves
  (read-modify-save), so two simultaneous removals on the same conversation can each save a list
  still containing the other member. Found while testing the HITL listener
  (`test/hitlParticipantListener.js` feeds `onLeave` directly for the back-to-back case).
  Suggested fix: an atomic `$pull` on `participants`/`participantsAgents`/`participantsBots` (or
  optimistic concurrency with a version check) and re-reading the updated document for events.
  The same save also writes back the whole `attributes` object read before an `await`, so a concurrent
  DELETE can resurrect `hitl_invited`/`hitl_waiting` or erase `hitl_left` written by the HITL listener; the fix
  should `$set` `attributes.abandoned_by_project_users.<id>` atomically instead of saving `attributes`.
  Done on feature/webhook-chatbot-hitl (commit "fix(requests): remove participants atomically"): `$pull` + `$set` of the abandoned key via `findOneAndUpdate`, conditional status updates; tests in `test/requestServiceRemoveParticipant.js`.

## 6. (tiledesk-chatbot `main`) HttpUtils logs the raw axios error, including the bot JWT

- **Where:** `tybotRoute/utils/HttpUtils.js`, `request(options, callback)` — the `.catch` handler
  (`winston.error("Axios error response: ", error.response)` when the response has no body, and
  `winston.error("Axios error: ", error)` when there is no response at all: timeouts, connection errors).
- **Effect:** both objects carry the request config, including `headers.Authorization` (`JWT <bot token>`),
  so the bot token is written to the tybot logs. This affects every directive that calls `HttpUtils.request`
  with the bot token. Responses that do have a body (e.g. JSON 4xx/5xx) only log `error.response.data` and are safe.
  The `invite_human` directive no longer logs the raw error itself (tybot branch `feature/webhook-chatbot-hitl`,
  `DirInviteHuman.errorSummary`), but an invite timeout (30 s) or network failure still reaches this handler.
- **Proposed fix:** log only `{ message: error.message, code: error.code, status: error.response?.status,
  data: error.response?.data }` in both branches; never log `error`, `error.response`, `error.config` or
  `error.request` as a whole.
- **Tests:** a request to a closed port and a request that times out — the captured log output does not
  contain the Authorization header value; the callback still receives the error.
- **Security-relevant; consider prioritising.**
- **Status:** HttpUtils handler fixed on tiledesk-chatbot feature/webhook-chatbot-hitl; logger-level redaction added (see item 7). `HttpUtils.errorSummary` logs `{ message, code, status, url (no query), data }`; the callback still receives the original error; tests in `tybotRoute/test/http_utils_test.js`.

## 7. (tiledesk-chatbot) raw error objects and secrets in logs

- **Where (found in the final review):** many directives and services still pass the raw axios/error object or a
  secret-bearing value to the logger: `DirReplyV2:255`, `DirClose:27`, `DirFireTiledeskEvent:31`,
  `DirMoveToUnassigned:34`, `DirAddTags:180/215/245`, `DirSetAttributeV2:207`, `DirReply:171`, `index.js:448`,
  `DirMoveToAgent:36`, `DirDepartment:118/134`, `DirIfOnlineAgents:64`, `DirReplaceBotV2:81`,
  `DirReplaceBotV3:80`, `DirSendEmail:74`, `DirSetConversationTags:100`, `QuotasService:25/56`, `DirAddKbContent`,
  `DirAskGPTV2`, `DirAiPrompt:711`, `DirAiCondition:633`, `DirAskGPT:153` (`gptkey`), and debug-level token logs
  (`TiledeskChatbot.js:330`, HTTPREQUEST dumps).
- **Effect:** an axios error carries `config.headers.Authorization` (`JWT <bot token>`) and request bodies with
  provider keys.
- **Done:** `tybotRoute/utils/winston.js` now applies a redaction format to every transport: values of keys
  `authorization|token|x-api-key|apikey|api_key|gptkey|password|secret` become `[REDACTED]`, and `JWT <token>` /
  `Bearer <token>` in any string (messages included) become `JWT [REDACTED]` / `Bearer [REDACTED]` (copies only,
  depth-limited, cycle-safe). A secret under an unlisted key name would still be logged.
- **Follow-up:** log summaries at the source (`HttpUtils.errorSummary` style) at each call site above instead of
  relying on the filter.
- **Server side (also follow-up):** `routes/webhook.js:360-361` and `services/webhookService.js:66-71` forward and
  log tybot's error body verbatim. That is safe now that tybot's async `/block` error response is
  `{ success: false, error: <message> }` and its log is a summary, but a future tybot change could put a secret
  back into that body.

## 8. (tiledesk-chatbot main_pre only) Invite/Remove human inside a sub-agent

- **Where (found in the pre-branch ports final review):** main_pre adds sub-agents, which run in their own
  `automation-request-<project>-<runId>` request while replies go to the parent conversation.
  `DirInviteHuman.js` and `DirRemoveHuman.js` still use the running request id.
- **Effect:** Invite human inside a sub-agent calls `/requests/automation-request-…/participants/invite`, gets 404
  and takes the "No human available" branch instead of inviting into the parent conversation. Nothing is corrupted.
- **Proposed fix:** when main_pre's sub-agent context names a parent request, invite/remove against the parent;
  decide in the spec whether a sub-agent may invite at all.
- **Status:** open; exists only on `feature/webhook-chatbot-hitl-PRE` (tybot) until sub-agents reach main.

## 9. (tiledesk-server) HITL listener in queue mode

- The listener subscribes to the `.queue` request events in the API process (`services/hitlParticipantListener.js:46-51`).
  If a deployment emits those events only in a worker that does not load `app.js`, leave/reassignment and the
  fallback never fire. Unverified on master and master-COLLAUDO; check the deployment's worker topology before release.
