@tiledesk/tiledesk-server 3.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.circleci/config.yml +1 -1
- package/CHANGELOG.md +34 -0
- package/Dockerfile +3 -2
- package/Dockerfile-en +3 -2
- package/Dockerfile-jobs +3 -2
- package/Dockerfile-profiler +3 -2
- package/README.md +15 -0
- package/app.js +12 -1
- package/bin/quota-reset +68 -0
- package/bin/quota-restore +86 -0
- package/channels/chat21/chat21Handler.js +50 -34
- package/channels/chat21/chat21JoinTracker.js +43 -0
- package/config/database.js +5 -5
- package/config/native_mcp/native_mcp_servers.json +1 -0
- package/controllers/chatbot.controller.js +80 -27
- package/controllers/intents.controller.js +42 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-chat21-ionic.md +468 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-design-studio.md +1349 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md +1694 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-tybot.md +789 -0
- package/docs/superpowers/plans/2026-09-29-hitl-known-limits-server.md +83 -0
- package/docs/superpowers/plans/2026-09-29-hitl-known-limits-tybot.md +76 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-chat21-ionic.md +97 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-design-studio.md +72 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-server.md +223 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-tybot.md +121 -0
- package/docs/superpowers/plans/2026-09-29-hitl-pre-branch-ports.md +65 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-design-studio.md +88 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-server.md +103 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-tybot.md +43 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-design-studio.md +80 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-runtime.md +39 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-server.md +106 -0
- package/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md +715 -0
- package/docs/superpowers/specs/2026-09-30-flow-start-points-design.md +156 -0
- package/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md +303 -0
- package/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md +191 -0
- package/event/botEvent.js +12 -1
- package/event/emailEvent.js +3 -0
- package/event/messageEvent.js +44 -0
- package/jobs.js +10 -0
- package/jobsManager.js +19 -0
- package/middleware/errorHandler.js +6 -2
- package/models/analyticResult.js +1 -1
- package/models/channelConstants.js +3 -2
- package/models/quotaUsage.js +71 -0
- package/models/request.js +6 -0
- package/models/requestSnapshot.js +12 -0
- package/models/routerLogger.js +1 -1
- package/models/webhook.js +44 -0
- package/package.json +7 -5
- package/pubmodules/emailNotification/requestNotification.js +14 -22
- package/pubmodules/events/test/eventRoute.js +7 -6
- package/pubmodules/rules/conciergeBot.js +9 -4
- package/routes/auth.js +1 -12
- package/routes/campaigns.js +0 -13
- package/routes/dataTable.js +0 -3
- package/routes/faq_kb.js +12 -1
- package/routes/messagesRoot.js +0 -1
- package/routes/quotes.js +38 -1
- package/routes/request.js +81 -5
- package/routes/users.js +0 -1
- package/routes/webhook.js +160 -8
- package/routes/webhooks.js +276 -6
- package/routes/widgetLoader.js +6 -3
- package/services/QuoteManager.js +77 -16
- package/services/aiService.js +1 -1
- package/services/chatbotService.js +55 -1
- package/services/departmentService.js +60 -43
- package/services/dolphinSchedulerClient.js +116 -0
- package/services/emailService.js +6 -1
- package/services/hitlParticipantListener.js +260 -0
- package/services/participantInviteService.js +302 -0
- package/services/participantRemoveService.js +79 -0
- package/services/quotaSnapshotService.js +1167 -0
- package/services/requestService.js +102 -144
- package/services/scheduledStart/dolphinBackend.js +246 -0
- package/services/scheduledStart/schedulerBackend.js +101 -0
- package/services/scheduledStart/schedulerServiceClient.js +41 -0
- package/services/scheduledStartPublishListener.js +186 -0
- package/services/scheduledStartRules.js +173 -0
- package/services/scheduledStartService.js +130 -0
- package/services/startPointCleanupListener.js +30 -0
- package/services/startPointService.js +158 -0
- package/services/testWsService.js +1 -4
- package/services/updateRequestSnapshotQueued.js +8 -9
- package/services/webhookConversationService.js +185 -0
- package/services/webhookSettingsValidator.js +61 -0
- package/template/email/checkpointReachedEmail.html +5 -0
- package/test/agentPromptsRoute.test.js +3 -2
- package/test/agentTokensQuota.js +237 -0
- package/test/botEventHitlFallback.js +19 -0
- package/test/chat21HandlerJoinWiring.js +59 -0
- package/test/dataTablesRoute.test.js +10 -2
- package/test/dateUtils.test.js +0 -3
- package/test/departmentService.js +8 -12
- package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
- package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
- package/test/faqRoute.js +6 -1
- package/test/faqkbRoute.js +14 -10
- package/test/faqkbV3Route.js +1 -1
- package/test/filepRoute.js +4 -50
- package/test/hitlParticipantListener.js +446 -0
- package/test/hitlQueueWiring.js +191 -0
- package/test/hitlWaitingReset.js +124 -0
- package/test/inviteParticipantsRoute.js +492 -0
- package/test/kbRoute.js +1 -1
- package/test/messageRoute.js +33 -21
- package/test/nativemcp.test.js +7 -1
- package/test/openaiRoute.js +2 -8
- package/test/publishFailLoud.test.js +414 -0
- package/test/quotaSnapshots.js +1044 -0
- package/test/removeParticipantsRoute.js +186 -0
- package/test/requestService.js +24 -16
- package/test/requestServiceRemoveParticipant.js +144 -0
- package/test/requestVisibility.test.js +186 -0
- package/test/scheduledStartFacade.js +184 -0
- package/test/scheduledStartHandover.js +95 -0
- package/test/scheduledStartPublish.js +320 -0
- package/test/scheduledStartRoute.js +163 -0
- package/test/scheduledStartRules.js +177 -0
- package/test/scheduledStartRun.js +299 -0
- package/test/scheduledStartSchedulerBackend.js +116 -0
- package/test/scheduledStartService.js +290 -0
- package/test/startPointsCleanup.js +69 -0
- package/test/startPointsRegression.js +169 -0
- package/test/startPointsRoute.js +158 -0
- package/test/webhookConversationRoute.js +347 -0
- package/test/webhookConversationService.js +261 -0
- package/test/webhookConversationTestUtils.js +55 -0
- package/utils/aiUtils.js +95 -1
- package/utils/intentFieldNames.js +192 -0
- package/utils/quotaCliUtil.js +43 -0
- package/utils/requestVisibility.js +355 -0
- package/websocket/webSocketServer.js +36 -31
- /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# HITL known-limit corrections — tiledesk-server Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **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.
|
|
4
|
+
|
|
5
|
+
**Goal:** Replace a departed operator only while the flow is waiting, make participant removal atomic, clear the waiting state in one write, and drop a replacement the flow no longer wants.
|
|
6
|
+
|
|
7
|
+
**Architecture:** `services/hitlParticipantListener.js` gets the "only while waiting" branch, a race-free `clearWaiting`, and a post-add ownership check. `services/requestService.js` `removeParticipantByRequestId` switches from load-modify-save to atomic updates while emitting the same events.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Node/Express, Mongoose 5.13, mocha + chai-http; MongoDB `tiledesk-test-mongo` (localhost:27017), Redis `tiledesk-test-redis` (localhost:6379).
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §12.1, §12.2, §12.5 (and §11.4 for the listener it amends).
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- Branch `feature/webhook-chatbot-hitl` (HEAD `97362be4` at plan time). Never commit to `master`, never push.
|
|
16
|
+
- Only conversations with `channel.name === 'webhook'` are affected by the listener; closed requests (`status 1000`) are never changed by it.
|
|
17
|
+
- Every query filters on `request_id` + `id_project`.
|
|
18
|
+
- `removeParticipantByRequestId(request_id, id_project, member, options)` keeps its signature, its resolve value (the populated request) and its reject behaviour, and emits exactly the same events with the same payload shapes: `request.update` (request), `request.update.comment` (`{ comment: 'PARTICIPANT_REMOVE', request }`), `request.updated` (`{ comment: 'PARTICIPANT_REMOVE', request, patch: { member } }`), `request.participants.leave` (`{ member, request, actor, source, trackLeave }`). A member that is not a participant resolves with the populated request and emits nothing (today's "already not found" branch).
|
|
19
|
+
- Status rule unchanged: never touch a closed request; otherwise `ASSIGNED` when participants remain, `UNASSIGNED` when none.
|
|
20
|
+
- No MongoDB aggregation-pipeline updates (production MongoDB version is not pinned); use plain operators and conditional filters.
|
|
21
|
+
- Tests: `./node_modules/.bin/mocha <files> --timeout 60000 --exit` from the repo root.
|
|
22
|
+
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>` after a blank line.
|
|
23
|
+
|
|
24
|
+
## Review Focus
|
|
25
|
+
|
|
26
|
+
1. The last invited human leaves while the flow is NOT waiting → no replacement, no fallback message, `hitl_fallback` gone, `workingStatus` unchanged.
|
|
27
|
+
2. Two different members removed at the same instant → both removed, status correct, both leave events emitted.
|
|
28
|
+
3. A removal racing with a HITL write (e.g. `$addToSet` into `attributes.hitl_left`) → the HITL write survives.
|
|
29
|
+
4. A human removed twice concurrently → exactly one leave event.
|
|
30
|
+
5. `clearWaiting` on a conversation that is `open` → no `request.workingStatus.update` event.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
### Task 1: Atomic `removeParticipantByRequestId`
|
|
35
|
+
|
|
36
|
+
**Files:**
|
|
37
|
+
- Modify: `services/requestService.js` (`removeParticipantByRequestId`)
|
|
38
|
+
- Test: `test/requestServiceRemoveParticipant.js` (new; setup pattern from `test/inviteParticipantsRoute.js`: `userService.signup`, `projectService.create`, `faqService.create`, `requestService.create` with `participants`)
|
|
39
|
+
|
|
40
|
+
**Interfaces:**
|
|
41
|
+
- Produces: same signature/behaviour as Global Constraints. Implementation: (1) resolve `project_user` of a human member first (`Project_user.findOne({ id_user: member, id_project })`, errors logged and ignored as today); (2) one `Request.findOneAndUpdate({ request_id, id_project, participants: member }, update, { new: true })` where `update` = `$pull: { participants: member, participantsAgents: member }` for a human (plus `$set: { ['attributes.abandoned_by_project_users.' + pu._id]: Date.now() }` when `pu` exists), or `$pull: { participants: member, participantsBots: <id without bot_> }` + `$set: { hasBot: false }` for a `bot_` member; no document → the "already not found" branch (load + populate + resolve, no events); (3) unless `status === CLOSED`, `Request.updateOne({ request_id, id_project, status: { $ne: 1000 }, participants: { $size: 0 } }, { $set: { status: UNASSIGNED } })` or, when participants remain, the same with `'participants.0': { $exists: true }` → `ASSIGNED`; (4) reload + populate (same populate chain as today) and emit the four events.
|
|
42
|
+
|
|
43
|
+
- [ ] **Step 1: Write the failing tests**
|
|
44
|
+
- `removes both members when two removals run at the same time` — request with bot + agents A and B; `Promise.all([remove(A), remove(B)])` → DB `participants` = `['bot_<id>']`, `participantsAgents` = `[]`, and two `request.participants.leave` events (one per member, captured with a temporary `requestEvent.on` listener removed in `finally`).
|
|
45
|
+
- `keeps a concurrent HITL write` — start `remove(A)` and, without awaiting, `Request.updateOne({ request_id }, { $addToSet: { 'attributes.hitl_left': 'x' } })`; after both settle `attributes.hitl_left` contains `'x'` and `attributes.abandoned_by_project_users` has A's project_user id.
|
|
46
|
+
- `emits one leave event when the same member is removed twice at once` → exactly one `request.participants.leave`.
|
|
47
|
+
- `sets unassigned when the last participant leaves and never touches a closed request` — remove the only participant → `status === 100`; on a request set to `status 1000` first, remove a participant → still `1000`.
|
|
48
|
+
- `resolves without events for a member that is not a participant`.
|
|
49
|
+
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/requestServiceRemoveParticipant.js --timeout 60000 --exit`: the concurrency tests fail (one member left behind / `hitl_left` lost / two events).
|
|
50
|
+
- [ ] **Step 3: Implement** per Interfaces.
|
|
51
|
+
- [ ] **Step 4: Verify** — the new file passes; then `./node_modules/.bin/mocha test/requestService.js test/requestRoute.js test/removeParticipantsRoute.js test/hitlParticipantListener.js test/inviteParticipantsRoute.js --timeout 60000 --exit` — record counts; any failure must be shown to also fail on HEAD before this task (`git stash` the two files, run the same failing file, `git stash pop`), otherwise fix it.
|
|
52
|
+
- [ ] **Step 5: Commit** — `fix(requests): remove participants atomically` (+ trailer). Also mark the TODO entry "Concurrent participant removals can lose one removal" in `docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` with "Done on feature/webhook-chatbot-hitl <sha>" in the same commit.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
### Task 2: Listener — replace only while waiting; one-write clear; drop unwanted replacement
|
|
57
|
+
|
|
58
|
+
**Files:**
|
|
59
|
+
- Modify: `services/hitlParticipantListener.js` (`handleLeave`, `clearWaiting`)
|
|
60
|
+
- Test: `test/hitlParticipantListener.js`
|
|
61
|
+
|
|
62
|
+
**Interfaces:**
|
|
63
|
+
- Consumes: Task 1's atomic removal (unchanged API).
|
|
64
|
+
- `handleLeave(member, request, { pick })`: after step 1 (atomic pull/addToSet, unchanged), read `hitl_waiting` from the step-1 document (`updated.attributes.hitl_waiting === true`). Not waiting → if `hitl_invited` is now empty, `updateOne({ request_id, id_project, 'attributes.hitl_invited': { $size: 0 } }, { $unset: { 'attributes.hitl_fallback': '' } })`, emit `request.update` with the populated request, and return (no pick, no message, no status change). Waiting → current behaviour.
|
|
65
|
+
- `clearWaiting(request, extraFilter) → Promise<boolean>`: attempt A = `findOneAndUpdate(filter + { workingStatus: 'pending' }, { $unset: <3 fields>, $set: { workingStatus: 'open' } })`; if A matched → emit `request.workingStatus.update` and `request.update`, return true. Else attempt B = `findOneAndUpdate(filter, { $unset: <3 fields> })`; matched → emit only `request.update`, return true; else false. (`filter` = today's `HITL_EXISTS` + base filter + `extraFilter`.)
|
|
66
|
+
- After a successful `addParticipantByRequestId(replacement)`: `Request.exists({ request_id, id_project, 'attributes.hitl_invited': replacement })`; false → `requestService.removeParticipantByRequestId(request_id, id_project, replacement, {})`, log at verbose, return (no notify).
|
|
67
|
+
|
|
68
|
+
- [ ] **Step 1: Write the failing tests** (owner unavailable, departments created before the request, as in the existing file):
|
|
69
|
+
- `releases instead of replacing when the flow is not waiting` — pooled A,B; invite with `fallback_intent`; clear `hitl_waiting` and set `workingStatus: 'open'` with `Request.updateOne` (simulates the human's answer); DELETE the invited one → after 1500 ms: no other agent added, no `Message` with `attributes.hitl_fallback`, `hitl_fallback` undefined, `hitl_left` = [leaver], `workingStatus === 'open'`.
|
|
70
|
+
- `keeps replacing while the flow waits` — same setup without clearing `hitl_waiting` → the other agent is invited (regression of the §11 behaviour).
|
|
71
|
+
- `emits no workingStatus event when clearing an open conversation` — only A, invite without fallback, then set `workingStatus: 'open'` keeping `hitl_waiting: true`; capture `request.workingStatus.update` events for this request; DELETE A → HITL fields cleared, zero captured events.
|
|
72
|
+
- `removes a replacement the flow no longer wants` — pooled A,B; stub `requestService.addParticipantByRequestId` so that, for the replacement, it first runs `Request.updateOne({ request_id }, { $unset: { 'attributes.hitl_invited': '' } })` then calls the original (restore in `finally`); DELETE the invited one → after `waitFor`, the replacement is not a participant.
|
|
73
|
+
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/hitlParticipantListener.js --timeout 60000 --exit` → the three new behaviours fail; the regression test passes.
|
|
74
|
+
- [ ] **Step 3: Implement** per Interfaces.
|
|
75
|
+
- [ ] **Step 4: Verify** — `./node_modules/.bin/mocha test/hitlParticipantListener.js test/removeParticipantsRoute.js test/inviteParticipantsRoute.js test/hitlWaitingReset.js test/webhookConversationRoute.js test/webhookConversationService.js test/botEventHitlFallback.js test/requestServiceRemoveParticipant.js --timeout 60000 --exit` → all pass.
|
|
76
|
+
- [ ] **Step 5: Commit** — `fix(requests): replace departed HITL humans only while the flow waits` (+ trailer).
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
### Task 3: Full-suite comparison
|
|
81
|
+
|
|
82
|
+
- [ ] **Step 1:** `npm test` on the branch head and on `origin/master` (temporary worktree under the session scratchpad with `node_modules` symlinked; run sequentially; remove the worktree and `git worktree prune` afterwards). Disk: the worktree without `node_modules` is ~130 MB — check `df -h` shows > 2 GB free first.
|
|
83
|
+
- [ ] **Step 2:** Compare failing test titles. Expected: none failing only on the branch; a branch-only title is re-run alone on both sides and reported if it is a real regression (no fix in this task).
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# HITL known-limit corrections — tybot (tiledesk-chatbot) Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **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.
|
|
4
|
+
|
|
5
|
+
**Goal:** Stop tybot from logging the bot token on HTTP errors, make a block lock count only for the action that set it, and make Capture User Reply stop when it cannot lock.
|
|
6
|
+
|
|
7
|
+
**Architecture:** `tybotRoute/utils/HttpUtils.js` logs a safe error summary. `DirCaptureUserReply` and `DirReplyV2.lockUnlock` compare the locked action id with their own `_tdActionId` before taking the "reply" path.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Node, mocha (`../node_modules/.bin/mocha` from `tybotRoute/`), in-process tilebot on 10001 + mock API on 10002, Redis `tiledesk-test-redis` on 6379.
|
|
10
|
+
|
|
11
|
+
**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §12.3, §12.5.
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- Repo `tiledesk-chatbot`, branch `feature/webhook-chatbot-hitl` (HEAD `7d3e1a67` at plan time). Never commit to `main`, never push.
|
|
16
|
+
- HttpUtils error log shape exactly: `{ message, code, status, url, data }` where `url` has no query string; never log `error`, `error.response`, `error.config` or `error.request`; the callback still receives the original error object.
|
|
17
|
+
- Lock ownership: "reply path" only when `currentLockedAction(requestId) === action._tdActionId`; a different locked action id → first pass (ask, then `lockIntent` + `lockAction` with this action's values, overwriting the old lock).
|
|
18
|
+
- Capture User Reply without a lock key: log an error and call `callback(true)`.
|
|
19
|
+
- Tests from `tybotRoute/`: `API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 ../node_modules/.bin/mocha <files> --timeout 60000 --exit`, one conversation file per mocha process when checking regressions (shared ports).
|
|
20
|
+
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>` after a blank line.
|
|
21
|
+
|
|
22
|
+
## Review Focus
|
|
23
|
+
|
|
24
|
+
1. A Reply V2 with buttons answered by a button click (same action, lock held) still takes the reply path.
|
|
25
|
+
2. A Reply V2 no-input timeout still fires and unlocks.
|
|
26
|
+
3. An HTTP error whose response body itself contains the token (echoing server) — the body is logged as-is; acceptable, but the request headers must never be.
|
|
27
|
+
4. A non-axios error (e.g. thrown before the request) passed to the catch → summary still logged without crashing.
|
|
28
|
+
5. Two Captures in the same block (unusual) → the first stops the block; the second never runs until the reply.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
### Task 1: HttpUtils logs a safe summary
|
|
33
|
+
|
|
34
|
+
**Files:**
|
|
35
|
+
- Modify: `tybotRoute/utils/HttpUtils.js` (`.catch` in `request`)
|
|
36
|
+
- Test: `tybotRoute/test/http_utils_test.js` (new)
|
|
37
|
+
|
|
38
|
+
**Interfaces:**
|
|
39
|
+
- Produces: `static errorSummary(error, url) → { message, code, status, url, data }` on `HttpUtils` (exported class unchanged otherwise); `url` stripped at `?`.
|
|
40
|
+
|
|
41
|
+
- [ ] **Step 1: Write the failing tests** — capture `winston` output by temporarily wrapping `require('../utils/winston').error` (restore in `afterEach`):
|
|
42
|
+
- `does not log the Authorization header on a connection error` — `new HttpUtils().request({ url: 'http://127.0.0.1:1/x?token=q', method: 'GET', headers: { Authorization: 'JWT SECRET' }, json: null }, cb)` → cb gets an error; captured log text contains neither `SECRET` nor `token=q`.
|
|
43
|
+
- `does not log the Authorization header on a timeout` — local `http` server that never answers, `timeout: 200` → same assertions; close the server in `finally`.
|
|
44
|
+
- `logs the server response body on an HTTP error` — local server answering 422 `{"error":"nope"}` → captured text contains `nope` and `422`, not `SECRET`.
|
|
45
|
+
- `errorSummary handles a non-axios error` — `HttpUtils.errorSummary(new Error('boom'), 'http://a/b?c=1')` → `{ message: 'boom', code: undefined, status: undefined, url: 'http://a/b', data: undefined }`.
|
|
46
|
+
- [ ] **Step 2: Run to verify they fail** — the two header tests fail (`SECRET` found), `errorSummary` is not a function.
|
|
47
|
+
- [ ] **Step 3: Implement.**
|
|
48
|
+
- [ ] **Step 4: Verify** — new file passes; regression, each alone: `test/conversation-invite_human_test.js`, `test/conversation-remove_human_test.js`, `test/conversation-web_requestv2_test.js`, `test/invite_human_members_test.js`, `test/remove_human_test.js`.
|
|
49
|
+
- [ ] **Step 5: Commit** — `fix(http): never log request headers on HTTP errors` (+ trailer); mark TODO item 6 in `tiledesk-server/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` "Done on tiledesk-chatbot feature/webhook-chatbot-hitl <sha>" and commit it in tiledesk-server (`docs(todo): …`, + trailer; only that file there).
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
### Task 2: A lock belongs to the action that set it; Capture without lock key stops
|
|
54
|
+
|
|
55
|
+
**Files:**
|
|
56
|
+
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js` (`go`: the `if (!lockedAction)` branch and the missing-key path)
|
|
57
|
+
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirReplyV2.js` (`lockUnlock`)
|
|
58
|
+
- Test: `tybotRoute/test/conversation-lock_ownership_bot.js` + `conversation-lock_ownership_test.js` (new; harness copied from `test/conversation-lock_internal_jump_test.js`); unit test in `tybotRoute/test/capture_user_reply_test.js` (new) for the missing-key path.
|
|
59
|
+
|
|
60
|
+
**Interfaces:**
|
|
61
|
+
- Both directives: `const locked = await this.chatbot.currentLockedAction(this.requestId); const own = locked && locked === action._tdActionId;` → `own` = reply path (today's `else` branch); otherwise first pass.
|
|
62
|
+
|
|
63
|
+
- [ ] **Step 1: Write the failing tests**
|
|
64
|
+
- Fixture: block `a` = reply `question A?` + `capture_user_reply` (`goToIntent: '#a_done-id'`, `assignResultTo: 'ans_a'`); block `a_done` = reply `A: {{ans_a}}`; block `b` = reply `question B?` + `capture_user_reply` (`goToIntent: '#b_done-id'`, `assignResultTo: 'ans_b'`); block `b_done` = reply `B: {{ans_b}}`; block `rv` = replyv2 `choose` with one action button `Go` → `#rv_done-id`; block `rv_done` = reply `rv done`.
|
|
65
|
+
- `an internal jump to another question does not consume the waiting one` — send `/a` → `question A?`; send a `_tdinternal` `/b` → `question B?`; send user text `yes` → `B: yes`; no `A: …` message within 1500 ms.
|
|
66
|
+
- `the same for a Reply V2 reached by an internal jump` — send `/a` → `question A?`; `_tdinternal` `/rv` → `choose`; user clicks `Go` (message with `attributes.action: '#rv_done-id'`) → `rv done`; no `A: …` message within 1500 ms.
|
|
67
|
+
- `capture_user_reply_test.js`: a `DirCaptureUserReply` whose reply has no intent info (`reply: {}`) and no lock → callback called once with `true`, lock not set (stub `chatbot.lockIntent`/`lockAction` to fail the test if called).
|
|
68
|
+
- [ ] **Step 2: Run to verify they fail** — the internal-jump test prints `A: yes` (reply path taken by B), the unit test gets `undefined`.
|
|
69
|
+
- [ ] **Step 3: Implement.**
|
|
70
|
+
- [ ] **Step 4: Verify** — new files pass; regression, each file alone: `conversation-lock_internal_jump_test.js`, `conversation-capture_test.js`, `conversation-replyv2_button_match_test.js`, `conversation-replyv2_noinput_test.js`, `conversation-invite_human_test.js`, `conversation-remove_human_test.js` (Review Focus 1 and 2 are covered by the replyv2 suites).
|
|
71
|
+
- [ ] **Step 5: Commit** — `fix(directives): a block lock only counts for the action that set it` (+ trailer).
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
### Task 3: Suite comparison
|
|
76
|
+
- [ ] Full suite from `tybotRoute/` on the branch and on `origin/main` (temporary worktree under the session scratchpad, repo-root `node_modules` symlinked, removed afterwards; check `df -h` > 2 GB free first). Expected: no failing title only on the branch other than port-10002 cascades whose files pass alone.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# HITL participant removal — chat21-ionic Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **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.
|
|
4
|
+
|
|
5
|
+
**Goal:** An operator can leave a conversation started by a webhook flow from the conversation list, after a confirmation, so the server can reassign or let the flow continue.
|
|
6
|
+
|
|
7
|
+
**Architecture:** A pure helper decides when Leave is shown; `TiledeskService.removeParticipant` calls the existing project-scoped `DELETE /:projectid/requests/:id/participants/:userId` with the operator's own id. The list item emits `onLeaveConversation`; the conversations page confirms with an Ionic alert, calls the service, and shows a toast on error.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Angular 12 + Ionic, Node 14 (nvm), Jasmine/Karma through the workspace narrow tsconfig.
|
|
10
|
+
|
|
11
|
+
**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11.6 (and §7 for v1).
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- Branch `feature/webhook-chatbot-hitl` (checked out, head `7988a98d`; `origin/master` unchanged). Never commit to `master`, never push.
|
|
16
|
+
- Node 14 for every npm/npx command: prefix `source ~/.nvm/nvm.sh >/dev/null && nvm use 14 >/dev/null && `. Never `npm install`.
|
|
17
|
+
- Leave is shown only when `isWebhookConversation(conversation)` and `!conversation.archived`.
|
|
18
|
+
- Leave uses `DELETE {SERVER_BASE_URL}{projectId}/requests/{requestId}/participants/{userId}` with `Authorization: <tiledeskToken>` — the same header pattern as `addParticipant` (`src/app/services/tiledesk/tiledesk.service.ts:254-268`).
|
|
19
|
+
- New i18n keys exactly `LEAVE_FLOW_CONVERSATION_ALERT_MSG`, `LEAVE_CONVERSATION_CONFIRM_LABEL`, `LEAVE_CONVERSATION_ERROR`, in all 15 files of `src/assets/i18n/`, inserted right after `CLOSE_FLOW_CONVERSATION_ALERT_MSG`, matching each file's indentation (it.json 4 spaces, others 2).
|
|
20
|
+
- Do not change archive/close behaviour, composer, canned responses, Copilot, push notifications.
|
|
21
|
+
- Specs run with the workspace narrow tsconfig (`.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-chat21-ionic/tsconfig.utils-message.json`); the repo's own `tsconfig.spec.json` does not compile on master.
|
|
22
|
+
- Build check: `npx ng build` exits 0 with only the 5 baseline "is part of the TypeScript compilation but it's unused" warnings.
|
|
23
|
+
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
|
24
|
+
|
|
25
|
+
## Review Focus
|
|
26
|
+
|
|
27
|
+
1. Leave pressed twice quickly → only one request is sent (disable the action while the alert/request is pending).
|
|
28
|
+
2. The server answers an error (e.g. 400 from the DELETE) → a toast with the server's `error` text, the conversation stays in the list.
|
|
29
|
+
3. A webhook conversation that is archived → no Leave button.
|
|
30
|
+
4. The project id for the DELETE comes from the conversation (`support-group-<projectId>-…`), never from another selected project.
|
|
31
|
+
5. Every locale file still parses as JSON after the insert.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Texts
|
|
36
|
+
|
|
37
|
+
| File | `LEAVE_FLOW_CONVERSATION_ALERT_MSG` | `LEAVE_CONVERSATION_CONFIRM_LABEL` | `LEAVE_CONVERSATION_ERROR` |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| en | You will leave this conversation. The flow will look for another operator, or continue without you. Continue? | Leave | Unable to leave the conversation |
|
|
40
|
+
| it | Uscirai da questa conversazione. Il flusso cercherà un altro operatore o continuerà senza di te. Continuare? | Esci | Impossibile uscire dalla conversazione |
|
|
41
|
+
| de | Sie verlassen diese Unterhaltung. Der Ablauf sucht einen anderen Mitarbeiter oder läuft ohne Sie weiter. Fortfahren? | Verlassen | Die Unterhaltung kann nicht verlassen werden |
|
|
42
|
+
| es | Saldrás de esta conversación. El flujo buscará otro operador o continuará sin ti. ¿Continuar? | Salir | No se puede salir de la conversación |
|
|
43
|
+
| fr | Vous allez quitter cette conversation. Le flux cherchera un autre opérateur ou continuera sans vous. Continuer ? | Quitter | Impossible de quitter la conversation |
|
|
44
|
+
| pt | Você sairá desta conversa. O fluxo procurará outro operador ou continuará sem você. Continuar? | Sair | Não foi possível sair da conversa |
|
|
45
|
+
| ru | Вы покинете этот разговор. Сценарий найдёт другого оператора или продолжит без вас. Продолжить? | Покинуть | Не удалось покинуть разговор |
|
|
46
|
+
| uk | Ви залишите цю розмову. Сценарій знайде іншого оператора або продовжить без вас. Продовжити? | Залишити | Не вдалося залишити розмову |
|
|
47
|
+
| tr | Bu konuşmadan ayrılacaksınız. Akış başka bir operatör arayacak veya sizsiz devam edecek. Devam edilsin mi? | Ayrıl | Konuşmadan ayrılınamadı |
|
|
48
|
+
| sv | Du lämnar den här konversationen. Flödet söker en annan operatör eller fortsätter utan dig. Fortsätta? | Lämna | Det gick inte att lämna konversationen |
|
|
49
|
+
| sr | Напустићете овај разговор. Ток ће потражити другог оператера или наставити без вас. Наставити? | Напусти | Није могуће напустити разговор |
|
|
50
|
+
| ar | ستغادر هذه المحادثة. سيبحث التدفق عن مشغل آخر أو يتابع بدونك. هل تريد المتابعة؟ | مغادرة | تعذر مغادرة المحادثة |
|
|
51
|
+
| az | Bu söhbətdən çıxacaqsınız. Axın başqa operator axtaracaq və ya sizsiz davam edəcək. Davam edilsin? | Çıx | Söhbətdən çıxmaq mümkün olmadı |
|
|
52
|
+
| kk | Сіз бұл сөйлесуден шығасыз. Ағын басқа операторды іздейді немесе сізсіз жалғасады. Жалғастыру керек пе? | Шығу | Сөйлесуден шығу мүмкін болмады |
|
|
53
|
+
| uz | Siz bu suhbatdan chiqasiz. Oqim boshqa operatorni qidiradi yoki sizsiz davom etadi. Davom etilsinmi? | Chiqish | Suhbatdan chiqib bo'lmadi |
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
### Task 1: Leave helper and service call
|
|
58
|
+
|
|
59
|
+
**Files:**
|
|
60
|
+
- Modify: `src/chat21-core/utils/utils-message.ts` (append), `src/chat21-core/utils/utils-message.spec.ts` (append)
|
|
61
|
+
- Modify: `src/app/services/tiledesk/tiledesk.service.ts` (append after `addParticipant`)
|
|
62
|
+
- Create: `src/app/services/tiledesk/tiledesk-remove-participant.spec.ts`
|
|
63
|
+
- Modify (workspace, not committed): `.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-chat21-ionic/tsconfig.utils-message.json` — add the new spec to `files`, and use `--include` with both specs when running
|
|
64
|
+
|
|
65
|
+
**Interfaces:**
|
|
66
|
+
- Produces: `canLeaveConversation(conversation: any): boolean` in `utils-message.ts` — `isWebhookConversation(conversation) && !conversation.archived`.
|
|
67
|
+
- Produces: `TiledeskService.removeParticipant(requestid: string, userid: string, project_id: string): Observable<any>` — DELETE per Global Constraints, `Content-Type: application/json`.
|
|
68
|
+
|
|
69
|
+
- [ ] **Step 1: Write the failing tests**
|
|
70
|
+
- `describe('utils-message canLeaveConversation')`: true for `{ attributes: { request_channel: 'webhook' }, archived: false }`; false when `archived: true`; false for `request_channel: 'chat21'`; false for `null`.
|
|
71
|
+
- `tiledesk-remove-participant.spec.ts` with `HttpClientTestingModule`, `TiledeskService` and stubbed `AppStorageService` (`getItem: () => 'JWT tok'`) and `LoggerInstance.setInstance(<no-op logger>)` if the service reads the logger singleton: after `initialize('https://api.test/')`, `removeParticipant('support-group-p1-abc', 'u1', 'p1')` issues exactly one `DELETE https://api.test/p1/requests/support-group-p1-abc/participants/u1` with `Authorization: JWT tok`.
|
|
72
|
+
- [ ] **Step 2: Run to verify they fail** — `npx ng test --watch=false --browsers=ChromeHeadless --ts-config=.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-chat21-ionic/tsconfig.utils-message.json --include=src/chat21-core/utils/utils-message.spec.ts --include=src/app/services/tiledesk/tiledesk-remove-participant.spec.ts` → compile errors for the missing members.
|
|
73
|
+
- [ ] **Step 3: Implement** both members.
|
|
74
|
+
- [ ] **Step 4: Run to verify they pass** — `TOTAL: 15 SUCCESS` (10 existing + 4 + 1).
|
|
75
|
+
- [ ] **Step 5: Commit** — `feat(chat): add the leave-conversation helper and service call` (+ trailer), committing only the `src/` files.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
### Task 2: Leave button, confirmation and error toast
|
|
80
|
+
|
|
81
|
+
**Files:**
|
|
82
|
+
- Modify: `src/app/chatlib/list-conversations-component/ion-list-conversations/ion-list-conversations.component.ts` (new `@Output() onLeaveConversation`, method `leaveConversation(conversation)`, method `canLeave(conversation)` wrapping the helper)
|
|
83
|
+
- Modify: `…/ion-list-conversations.component.html` (new `ion-button` right after the archive button at `:167-174`, icon `exit-outline`, id `'leave_conversation_button' + conversation.uid`, same classes as the archive button, `*ngIf="canLeave(conversation)"`, click stops propagation)
|
|
84
|
+
- Modify: `src/app/pages/conversations-list/conversations-list.page.html` (`(onLeaveConversation)="onLeaveConversation($event)"` on both list usages, next to `(onCloseConversation)` at `:70` and `:95`)
|
|
85
|
+
- Modify: `src/app/pages/conversations-list/conversations-list.page.ts` (inject `ToastController`; `onLeaveConversation(conversation)`, `presentAlertConfirmLeaveConversation(conversation)`, `leaveConversationConfirmed(conversation)`)
|
|
86
|
+
- Modify: the 15 `src/assets/i18n/*.json` files (Texts table)
|
|
87
|
+
|
|
88
|
+
**Interfaces:**
|
|
89
|
+
- Consumes: Task 1 `canLeaveConversation`, `TiledeskService.removeParticipant`; the page's existing `loggedUserUid`, `translateService.translateLanguage(keys)` and the project-id lookup used by `closeConversationConfirmed` (`tiledeskService.getProjectIdByConvRecipient(conversationId)`, `conversations-list.page.ts:1141`).
|
|
90
|
+
- Produces: page field `leavingConversationUid: string | null` — set while the alert or request for that conversation is pending; `onLeaveConversation` returns immediately when it equals `conversation.uid` (Review Focus 1).
|
|
91
|
+
- Behaviour: alert header `ALERT_TITLE`, message `LEAVE_FLOW_CONVERSATION_ALERT_MSG`, buttons `CLOSE_ALERT_CANCEL_LABEL` (role cancel, clears the field) and `LEAVE_CONVERSATION_CONFIRM_LABEL` (calls `leaveConversationConfirmed`). On success nothing else (chat21 removes the conversation from the list). On error: toast (3 s, position top) with `error.error.error` when a non-empty string, else `LEAVE_CONVERSATION_ERROR`; clear the field in both cases.
|
|
92
|
+
|
|
93
|
+
- [ ] **Step 1:** Insert the 3 keys in all 15 locale files; verify with `for f in src/assets/i18n/*.json; do node -e "JSON.parse(require('fs').readFileSync('$f','utf8'))" || echo BAD $f; done` (prints nothing) and `grep -c '"LEAVE_CONVERSATION_CONFIRM_LABEL"' src/assets/i18n/*.json` (1 per file).
|
|
94
|
+
- [ ] **Step 2:** Implement the component output/button and the page methods.
|
|
95
|
+
- [ ] **Step 3:** `npx ng build` → exit 0 with only the 5 baseline warnings; Task 1 spec command → `TOTAL: 15 SUCCESS`.
|
|
96
|
+
- [ ] **Step 4: Manual check (record as pending if no stack is running):** agent in a webhook conversation → Leave icon visible; Cancel keeps it; Leave removes it from the list and the server reassigns or sends the flow to its fallback; a widget conversation shows no Leave icon; an archived webhook conversation shows none.
|
|
97
|
+
- [ ] **Step 5: Commit** — `feat(chat): let operators leave a conversation started by a flow` (+ trailer).
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# HITL participant removal — design-studio Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **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.
|
|
4
|
+
|
|
5
|
+
**Goal:** Flow designers can add a "Remove human" action (scope: humans invited by the flow, or all humans) and read how Invite human behaves when the invited human leaves.
|
|
6
|
+
|
|
7
|
+
**Architecture:** A copy of the "Invite human" action pattern already on this branch (`CV/actions/list/cds-action-invite-human/`): model, enum + registry entry, factory branch, component with spec, module registration, both switch cases, connector redraw, icon, `en.json`.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Angular 14, Node 16 (nvm), Jasmine/Karma through the workspace test entry.
|
|
10
|
+
|
|
11
|
+
**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11.7 (and §8.3 for Invite human).
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- Branch `feature/webhook-chatbot-hitl` (checked out, `origin/master` 1.40.15 merged at `ab164466`). Never commit to `master`, never push.
|
|
16
|
+
- Paths: `C = src/app/chatbot-design-studio`, `CV = C/cds-dashboard/cds-canvas`.
|
|
17
|
+
- Action type exactly `'remove_human'`; `TYPE_ACTION.REMOVE_HUMAN` and `ACTIONS_LIST.REMOVE_HUMAN` (same key name, `CV/cds-intent/cds-intent.component.ts` looks the list up by enum key); `chatbot_types: [TYPE_CHATBOT.CHATBOT]`, category `MOST_USED`.
|
|
18
|
+
- Model `ActionRemoveHuman extends Action` with `scope: string` (default `'invited'`), `trueIntent`, `falseIntent`, `trueIntentAttributes?`, `falseIntentAttributes?`; `_tdActionType = TYPE_ACTION.REMOVE_HUMAN`.
|
|
19
|
+
- Scope values exactly `'invited'` and `'all_humans'`.
|
|
20
|
+
- Node 16 for every npm/npx command: prefix `source ~/.nvm/nvm.sh >/dev/null && nvm use 16 >/dev/null && `. Never `npm install`.
|
|
21
|
+
- Specs run only through the workspace entry (`.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-design-studio/test-hitl.ts` + `tsconfig.hitl-specs.json`, not committed). Build: `npx ng build` exit 0 with only the 2 baseline CommonJS warnings and the "3 rules skipped due to selector errors" note.
|
|
22
|
+
- `strictTemplates` is off: check every binding against the component members and `cds-select` inputs/outputs by hand.
|
|
23
|
+
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
|
24
|
+
|
|
25
|
+
## Review Focus
|
|
26
|
+
|
|
27
|
+
1. An imported flow whose `remove_human` action has no `scope` (or an unknown one) → the panel shows "Only humans invited by this flow" and saves `'invited'`.
|
|
28
|
+
2. Pasting/duplicating the action → new `_tdActionId`, connectors reset (same as Invite human; covered by the existing paste logic, check it is not special-cased by type).
|
|
29
|
+
3. A `webhook` (automation) subtype flow → the action is not offered.
|
|
30
|
+
4. Both outputs unconnected → the action still saves and the preview shows two empty connectors.
|
|
31
|
+
5. The new icon registers under the exact `src` path used in `ACTIONS_LIST`.
|
|
32
|
+
|
|
33
|
+
## Texts (`src/assets/i18n/en.json`)
|
|
34
|
+
|
|
35
|
+
- `CDSActionList.NAME`, after `"InviteHuman": "Invite human",`: `"RemoveHuman": "Remove human",`
|
|
36
|
+
- `CDSActionList.DOC`, after the `"InviteHuman": { … },` block:
|
|
37
|
+
`"RemoveHuman": { "TITLE": "Remove a human", "DESCRIPTION": "Removes human participants from the conversation while the chatbot keeps running: only the humans this flow invited, or all of them. Use Remove current bot instead to hand the conversation over completely.", "IMAGE": "", "VIDEO_URL": "", "DOC_URL": "" },`
|
|
38
|
+
- `CDSActionList.DOC.InviteHuman.DESCRIPTION`: append ` If the invited human leaves, another available agent is invited; if nobody is available, the flow continues from No human available.`
|
|
39
|
+
- `CDSCanvas`, after `"InviteHumanNoHuman": "No human available",`: `"RemoveHumanScope": "Who to remove"`, `"RemoveHumanScopeInvited": "Only humans invited by this flow"`, `"RemoveHumanScopeAll": "All human participants"`, `"RemoveHumanRemoved": "Removed"`, `"RemoveHumanError": "Error"`.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
### Task 1: "Remove human" action
|
|
44
|
+
|
|
45
|
+
**Files:**
|
|
46
|
+
- Modify: `src/app/models/action-model.ts` (after `ActionInviteHuman`, `:97`)
|
|
47
|
+
- Modify: `C/utils-actions.ts` (enum after `INVITE_HUMAN` `:57`; list entry after `INVITE_HUMAN:` `:143`, `src: "assets/images/actions/remove_human.svg"`, `doc: "CDSActionList.DOC.RemoveHuman"`)
|
|
48
|
+
- Modify: `C/services/intent.service.ts` (import `ActionRemoveHuman` in the action-model import; factory branch after the `INVITE_HUMAN` branch `:1029`)
|
|
49
|
+
- Create: `CV/actions/list/cds-action-remove-human/cds-action-remove-human.component.{ts,html,scss,spec.ts}` (scss copied from `cds-action-invite-human`)
|
|
50
|
+
- Modify: `CV/actions/list/cds-actions.module.ts` (import; declarations and exports right after `CdsActionInviteHumanComponent,`)
|
|
51
|
+
- Modify: `CV/cds-intent/cds-intent.component.html` (case after the `cds-action-invite-human` case `:220`) and `CV/cds-panel-action-detail/cds-panel-action-detail.component.html` (case after `:93`), same bindings as their invite-human neighbours
|
|
52
|
+
- Modify: `C/services/connector.service.ts:523` (add `|| action._tdActionType === TYPE_ACTION.REMOVE_HUMAN` to the true/false connector condition)
|
|
53
|
+
- Modify: `C/services/icon.service.ts` (register `assets/images/actions/remove_human.svg` after `invite_human.svg` `:234-235`)
|
|
54
|
+
- Create: `src/assets/images/actions/remove_human.svg` — `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24" fill="currentColor"><path d="M0 0h24v24H0z" fill="none"/><path d="M14 8c0-2.21-1.79-4-4-4S6 5.79 6 8s1.79 4 4 4 4-1.79 4-4zm3 2v2h6v-2h-6zM2 18v2h16v-2c0-2.66-5.33-4-8-4s-8 1.34-8 4z"/></svg>`
|
|
55
|
+
- Modify: `src/assets/i18n/en.json` (Texts)
|
|
56
|
+
- Modify (workspace, not committed): `test-hitl.ts` regex and `tsconfig.hitl-specs.json` include, to also load `cds-action-remove-human.component.spec.ts`
|
|
57
|
+
|
|
58
|
+
**Interfaces:**
|
|
59
|
+
- Consumes: `checkConnectionStatusOfAction`, `updateConnector` (`C/utils-connectors`), `TYPE_UPDATE_ACTION` (`C/utils`), `IntentService.isChangedConnector$`, `IntentService.getListOfIntents()`, `TranslateService.instant`.
|
|
60
|
+
- Produces: `CdsActionRemoveHumanComponent` (selector `cds-action-remove-human`; inputs `intentSelected`, `action: ActionRemoveHuman`, `previewMode` default `true`; outputs `updateAndSaveAction`, `onConnectorChange`); members `scopeOptions: {name: string, value: string}[]` (translated `RemoveHumanScopeInvited` → `'invited'`, `RemoveHumanScopeAll` → `'all_humans'`), `onChangeScope(item)`, `onChangeSelect(event, 'trueIntent'|'falseIntent')`, `onResetBlockSelect(event, 'trueIntent'|'falseIntent')`, connector ids `<intent_id>/<_tdActionId>/true|false` — same semantics as the invite-human component.
|
|
61
|
+
- Behaviour: on init an unknown/missing `scope` becomes `'invited'` (in memory; saved on the next change, same as Invite human's department reset). Panel: `cds-select` for the scope (`bindLabelSelect 'name'`, `bindValueSelect 'value'`, not clearable), then the "Removed" and "Error" block selects. Preview: scope label, then the two connectors labelled `RemoveHumanRemoved` / `RemoveHumanError`.
|
|
62
|
+
|
|
63
|
+
- [ ] **Step 1: Write the failing spec** `cds-action-remove-human.component.spec.ts` (TestBed as in `cds-action-invite-human.component.spec.ts`: `TranslateModule.forRoot()`, `NO_ERRORS_SCHEMA`, stub `IntentService` with `isChangedConnector$: new Subject()` and `getListOfIntents: () => []`):
|
|
64
|
+
- `creates an action with type remove_human and scope invited` — `new ActionRemoveHuman()`: `_tdActionType === 'remove_human'`, `scope === 'invited'`.
|
|
65
|
+
- `falls back to invited for a missing or unknown scope` — `action.scope = 'everyone'` → after `detectChanges`, `'invited'`.
|
|
66
|
+
- `saves the selected scope` — `onChangeScope({ name: 'x', value: 'all_humans' })` → `scope === 'all_humans'`, `updateAndSaveAction` emitted once.
|
|
67
|
+
- `emits connector changes for the removed and error connectors` — same assertions as the invite-human connector test with `/true` and `/false` ids.
|
|
68
|
+
- [ ] **Step 2: Run to verify it fails** — `npx ng test --watch=false --browsers=ChromeHeadless --main=.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-design-studio/test-hitl.ts --ts-config=.superpowers/sdd/2026-09-15-webhook-chatbot-hitl-design-studio/tsconfig.hitl-specs.json` → compile error, module not found.
|
|
69
|
+
- [ ] **Step 3: Implement** everything in the Files list.
|
|
70
|
+
- [ ] **Step 4: Verify** — spec command → `TOTAL: 13 SUCCESS` (9 existing + 4); `node -e "JSON.parse(require('fs').readFileSync('src/assets/i18n/en.json','utf8')); console.log('ok')"` → `ok`; `npx ng build` → exit 0 with only the baseline warnings.
|
|
71
|
+
- [ ] **Step 5: Manual check (record as pending if no stack is running):** chatbot subtype → "Remove human" in Most used; webhook subtype → absent; add it, choose "All human participants", connect both outputs, reload → restored; exported JSON has `_tdActionType: "remove_human"`, `scope: "all_humans"`, `trueIntent`, `falseIntent`.
|
|
72
|
+
- [ ] **Step 6: Commit** — `feat(actions): add Remove human action for conversational chatbots` (+ trailer), committing only tracked `src/` changes.
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# HITL participant removal and reassignment — tiledesk-server Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **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.
|
|
4
|
+
|
|
5
|
+
**Goal:** Let a flow remove the humans it invited, reassign automatically when an invited human leaves, and send the flow to its "No human available" block when nobody can replace them.
|
|
6
|
+
|
|
7
|
+
**Architecture:** The invite records the HITL context on the conversation (`attributes.hitl_*`). A new project-scoped remove endpoint releases humans on the flow's request. One new listener on the existing participant leave/update events handles every other removal path: it reassigns with the invite service's picker or clears the state and posts a system info message whose `action` jumps the bot to the fallback block; `botEvent` forwards that one message type to the bot.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Node/Express, Mongoose 5.13, mocha + chai-http, local MongoDB (`tiledesk-test-mongo`, 27017) and Redis (`tiledesk-test-redis`, 6379).
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11 (read §5.3–§5.5 for the v1 code this extends).
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- Branch `feature/webhook-chatbot-hitl` (already checked out, default branch merged at `6ff4ac52`). Never commit to `master`, never push.
|
|
16
|
+
- All new REST APIs are project scoped: under `/:projectid/requests/...` in `routes/request.js` (mounted `app.js:621` with `hasRoleOrTypes('agent', ['bot','subscription'])`); every query filters on `id_project`; a conversation id of another project answers 404.
|
|
17
|
+
- Only conversations with `request.channel.name === ChannelConstants.WEBHOOK` are affected; closed conversations (`status === RequestConstants.CLOSED`, 1000) are never touched by the listener.
|
|
18
|
+
- Attribute names exactly: `start_type`, `hitl_waiting`, `hitl_invited`, `hitl_department_id`, `hitl_fallback` (`{ intent: '#<blockId>' }`), `hitl_left`.
|
|
19
|
+
- Remove scopes exactly `'invited' | 'all_humans'`, default `'invited'`.
|
|
20
|
+
- Fallback message text: `The invited human left and no replacement is available`; its `attributes.action` exactly `'#<blockId>{"flowError":"(Invite human) The invited human left and no replacement is available"}'` (no `'` inside the flowError text).
|
|
21
|
+
- The bot (`bot_*` participants) is never removed by the new endpoint; removing it through the generic DELETE stays allowed.
|
|
22
|
+
- Tests: `NODE_ENV=test`, run with `./node_modules/.bin/mocha <files> --timeout 60000 --exit` from the repo root; new test files use `mongoose.set('autoIndex', false)` only if they reproduce the known `phone` E11000 (TODO item 5).
|
|
23
|
+
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
|
24
|
+
|
|
25
|
+
## Review Focus
|
|
26
|
+
|
|
27
|
+
1. A human who was never invited by the flow (e.g. an admin who joined) leaves → nothing happens (no pick, no fallback).
|
|
28
|
+
2. The flow's own `remove` call must never trigger a reassignment or fallback for the humans it removes.
|
|
29
|
+
3. The replacement must never be someone in `hitl_left` or already in the conversation, even when routing's selected operator is such a user (the v1 picker falls back to already-participants — the replacement picker must not).
|
|
30
|
+
4. Two invited humans removed back-to-back → at most one reassignment/fallback.
|
|
31
|
+
5. A request id of another project passed on this project's URL → 404, never a removal.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## File Structure
|
|
36
|
+
|
|
37
|
+
| File | Status | Responsibility |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| `services/webhookConversationService.js` | Modify | set `attributes.start_type = 'webhook'` at start |
|
|
40
|
+
| `services/participantInviteService.js` | Modify | record HITL context on invite; `pickReplacement` |
|
|
41
|
+
| `services/participantRemoveService.js` | Create | flow-requested removal (`remove`) |
|
|
42
|
+
| `services/hitlParticipantListener.js` | Create | leave/update listener: reassign or fallback |
|
|
43
|
+
| `routes/request.js` | Modify | `fallback_intent` validation; `POST /:requestid/participants/remove` |
|
|
44
|
+
| `event/botEvent.js` | Modify | forward the HITL fallback system message |
|
|
45
|
+
| `app.js` | Modify | `hitlParticipantListener.listen()` |
|
|
46
|
+
| `test/inviteParticipantsRoute.js`, `test/webhookConversationService.js` | Modify | invite context, start_type |
|
|
47
|
+
| `test/removeParticipantsRoute.js`, `test/hitlParticipantListener.js`, `test/botEventHitlFallback.js` | Create | new behaviour |
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
### Task 1: Record the HITL context on invite and the start type
|
|
52
|
+
|
|
53
|
+
**Files:**
|
|
54
|
+
- Modify: `services/webhookConversationService.js:92` (the `attributes` object)
|
|
55
|
+
- Modify: `services/participantInviteService.js` (`invite`, `markWaiting`)
|
|
56
|
+
- Modify: `routes/request.js:426-461` (invite route)
|
|
57
|
+
- Test: `test/inviteParticipantsRoute.js`, `test/webhookConversationService.js`
|
|
58
|
+
|
|
59
|
+
**Interfaces:**
|
|
60
|
+
- Produces: `participantInviteService.invite(id_project, request_id, { department_id, members, fallback_intent })` — same response shape as v1.
|
|
61
|
+
- Produces: `participantInviteService.markWaiting(request_id, id_project, { invitedIds, department_id, fallback_intent })` → populated request. It sets `workingStatus: 'pending'`, `attributes.hitl_waiting: true`, `attributes.hitl_department_id` (when non-null), `attributes.hitl_fallback: { intent: fallback_intent }` (only when `fallback_intent` is given), and `$addToSet: { 'attributes.hitl_invited': { $each: invitedIds } }`, in one `findOneAndUpdate` filtered by `request_id` + `id_project`.
|
|
62
|
+
- Produces: stored `attributes.hitl_department_id` is always the resolved department: explicit `department_id`, else `request.department`, else the project default. On the members path (no department pick) resolve it best-effort with `resolveDepartment` and store `null` on error — the members path must keep answering exactly as v1 (no new 422).
|
|
63
|
+
|
|
64
|
+
- [ ] **Step 1: Write the failing tests**
|
|
65
|
+
|
|
66
|
+
In `test/inviteParticipantsRoute.js` (reuse `setup`, `addAgent`, `invite`):
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
it('records the invited humans, the department and the fallback block', async () => {
|
|
70
|
+
const ctx = await setup({ ownerAvailable: false, beforeRequest: async (project, owner) => {
|
|
71
|
+
const department = await departmentService.create('SRE pooled', project._id, 'pooled', owner._id);
|
|
72
|
+
return { department, agents: [await addAgent(project, owner)] };
|
|
73
|
+
}});
|
|
74
|
+
const res = await invite(ctx, { department_id: ctx.department._id.toString(), fallback_intent: '#noone-id' });
|
|
75
|
+
expect(res).to.have.status(200);
|
|
76
|
+
const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
|
|
77
|
+
expect(request.attributes.hitl_invited).to.deep.equal([res.body.invited[0].id_user]);
|
|
78
|
+
expect(request.attributes.hitl_department_id).to.equal(ctx.department._id.toString());
|
|
79
|
+
expect(request.attributes.hitl_fallback).to.deep.equal({ intent: '#noone-id' });
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('does not record HITL context when nobody is invited', async () => {
|
|
83
|
+
const ctx = await setup({ ownerAvailable: false });
|
|
84
|
+
const res = await invite(ctx, { fallback_intent: '#noone-id' });
|
|
85
|
+
expect(res.body.invited).to.have.length(0);
|
|
86
|
+
const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
|
|
87
|
+
expect(request.attributes && request.attributes.hitl_fallback).to.equal(undefined);
|
|
88
|
+
expect(request.attributes && request.attributes.hitl_invited).to.equal(undefined);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('stores the default department when members are invited by email', async () => {
|
|
92
|
+
// owner invited by email: hitl_department_id = the project's default department id
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('rejects a non-string fallback_intent with 422', async () => {
|
|
96
|
+
const ctx = await setup();
|
|
97
|
+
const res = await invite(ctx, { fallback_intent: 42 });
|
|
98
|
+
expect(res).to.have.status(422);
|
|
99
|
+
expect(res.body.error).to.equal('fallback_intent must be a string');
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The third test: invite `{ members: [ctx.ownerEmail] }` and assert `hitl_department_id` equals `(await Department.findOne({ id_project: ctx.project._id, default: true })).id` and `hitl_invited` contains the owner id.
|
|
104
|
+
|
|
105
|
+
In `test/webhookConversationService.js` add `it('marks the conversation start type as webhook')`: after a start, `request.attributes.start_type === 'webhook'`.
|
|
106
|
+
|
|
107
|
+
- [ ] **Step 2: Run to verify they fail**
|
|
108
|
+
|
|
109
|
+
Run: `./node_modules/.bin/mocha test/inviteParticipantsRoute.js test/webhookConversationService.js --timeout 60000 --exit`
|
|
110
|
+
Expected: the 5 new tests FAIL (undefined attributes, 200 instead of 422); existing tests pass.
|
|
111
|
+
|
|
112
|
+
- [ ] **Step 3: Implement**
|
|
113
|
+
|
|
114
|
+
`start_type: 'webhook'` in the starter's `attributes`; route validation `fallback_intent` (undefined/null allowed, otherwise must be a string → 422 `fallback_intent must be a string`) and pass it to `invite`; `invite` computes `invitedIds` (every returned invitee, including `already_participant`) and the resolved department id, then calls the new `markWaiting` signature.
|
|
115
|
+
|
|
116
|
+
- [ ] **Step 4: Run to verify they pass**
|
|
117
|
+
|
|
118
|
+
Same command. Expected: all tests in both files PASS.
|
|
119
|
+
|
|
120
|
+
- [ ] **Step 5: Commit**
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
git add services/webhookConversationService.js services/participantInviteService.js routes/request.js test/inviteParticipantsRoute.js test/webhookConversationService.js
|
|
124
|
+
git commit -m "feat(requests): record the HITL invite context and the conversation start type" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
### Task 2: Flow-requested removal endpoint
|
|
130
|
+
|
|
131
|
+
**Files:**
|
|
132
|
+
- Create: `services/participantRemoveService.js`
|
|
133
|
+
- Modify: `routes/request.js` (new route right after the invite route)
|
|
134
|
+
- Test: `test/removeParticipantsRoute.js` (copy the `addAgent` / `setup` helpers' approach from `test/inviteParticipantsRoute.js`; add a `remove(ctx, body, auth)` helper posting to `/:projectid/requests/:id/participants/remove`)
|
|
135
|
+
|
|
136
|
+
**Interfaces:**
|
|
137
|
+
- Consumes: Task 1 attributes; `participantInviteService.InviteError` (status + message), `participantInviteService.fullnameOf(id_user)`.
|
|
138
|
+
- Produces: `participantRemoveService.remove(id_project, request_id, { scope }) → Promise<{ request_id, removed: [{ id_user, fullname }] }>`; throws `InviteError` 404 `Request not found with id <id>`, 409 `Request <id> is closed`, 422 `Remove human requires a conversation started by a webhook`.
|
|
139
|
+
- Produces: route `POST /:requestid/participants/remove` — `scope` absent → `'invited'`; any other value than the two scopes → 422 `scope must be "invited" or "all_humans"`; errors answer `{ success: false, error }` with the service status, 500 `Error removing participants` otherwise.
|
|
140
|
+
- Behaviour order (spec §11.3.2): load and check the request; atomically `$unset` `attributes.hitl_waiting`, `attributes.hitl_invited`, `attributes.hitl_fallback` with `{ new: false }` to read the pre-clear `hitl_invited`; if the old `workingStatus` was `'pending'` set it to `'open'` and emit `request.workingStatus.update` + `request.update` with the populated request (same populate chain as `markWaiting`); then call `requestService.removeParticipantByRequestId(request_id, id_project, id_user, {})` for each target, sequentially. Targets: `invited` = pre-clear `hitl_invited` ∩ current participants; `all_humans` = current participants not starting with `bot_`.
|
|
141
|
+
|
|
142
|
+
- [ ] **Step 1: Write the failing tests** — `describe('RemoveParticipantsRoute')` with:
|
|
143
|
+
- `removes only the humans invited by the flow and keeps the bot` — invite agent A (department with A), add agent B directly with `requestService.addParticipantByRequestId`; `remove({ scope: 'invited' })` → 200, `removed` = `[{ id_user: A, fullname: 'Agent Smith' }]`; participants = `['bot_<id>', B]`.
|
|
144
|
+
- `removes every human with all_humans and keeps the bot` → participants = `['bot_<id>']`.
|
|
145
|
+
- `clears the HITL context and reopens a pending conversation` → `hitl_waiting`, `hitl_invited`, `hitl_fallback` undefined, `workingStatus === 'open'`.
|
|
146
|
+
- `answers 200 with an empty list when nobody is left to remove`.
|
|
147
|
+
- `does not reassign the removed humans` — department has A and B, invite picks one with a fallback, remove it; `waitFor` 1500 ms then participants contain no agent and `hitl_left` is undefined (Task 3 must not act on it).
|
|
148
|
+
- `rejects an unknown scope with 422` (`{ scope: 'everyone' }`).
|
|
149
|
+
- `returns 404 for unknown and other-project requests, 409 for closed, 422 for non-webhook` — other project: owner of project A posts to `/A/requests/<request of B>/participants/remove` → 404.
|
|
150
|
+
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/removeParticipantsRoute.js --timeout 60000 --exit` → 404 route not found for every test.
|
|
151
|
+
- [ ] **Step 3: Implement** the service and route per the Interfaces block.
|
|
152
|
+
- [ ] **Step 4: Run to verify they pass** — same command, all PASS; then `./node_modules/.bin/mocha test/inviteParticipantsRoute.js test/hitlWaitingReset.js --timeout 60000 --exit` still PASS.
|
|
153
|
+
- [ ] **Step 5: Commit** — `feat(requests): let the flow remove the humans it invited` (+ trailer), adding the service, route and test files.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
### Task 3: Removal listener — reassignment and fallback
|
|
158
|
+
|
|
159
|
+
**Files:**
|
|
160
|
+
- Modify: `services/participantInviteService.js` (add `pickReplacement`)
|
|
161
|
+
- Create: `services/hitlParticipantListener.js`
|
|
162
|
+
- Modify: `event/botEvent.js:50-56` (system-message filter)
|
|
163
|
+
- Modify: `app.js` (after `BanUserNotifier.listen();` at `:229`)
|
|
164
|
+
- Test: `test/hitlParticipantListener.js`, `test/botEventHitlFallback.js`
|
|
165
|
+
|
|
166
|
+
**Interfaces:**
|
|
167
|
+
- Consumes: Task 1 attributes and `markWaiting`-populated requests; `participantInviteService.resolveDepartment`, `notifyInvited`, `fullnameOf`; `requestService.addParticipantByRequestId`; `messageService.send(sender, senderFullname, recipient, text, id_project, createdBy, attributes)`.
|
|
168
|
+
- Produces: `participantInviteService.pickReplacement(id_project, department, request, excluded: string[]) → Promise<string|null>` — first routing operator (`departmentService.getOperators(dept, project, true, undefined, { request })`) not in `excluded`, else one random `available_agents` entry not in `excluded` (`getRandomAvailableOperator`), else `null`. Never returns an excluded id (Review Focus 3).
|
|
169
|
+
- Produces: `hitlParticipantListener.listen()` — subscribes to `request.participants.leave` and `request.participants.update` (use the `.queue` variants when `requestEvent.queueEnabled`, as `pubmodules/routing-queue/listenerQueued.js:252-258` does).
|
|
170
|
+
- Produces: `hitlParticipantListener.onLeave({ member, request })` and `onUpdate({ request, removedParticipants, addedParticipants })`, both returning a Promise (exported for tests; handlers call them and log errors).
|
|
171
|
+
- Produces: exported `botEvent.shouldForwardSystemMessage(message) → boolean`, true for `/start` or `\start` text (v1) and for `message.attributes.hitl_fallback === true && message.attributes.action`; the `message.create` handler uses it.
|
|
172
|
+
- Algorithm (spec §11.4), ids compared as strings:
|
|
173
|
+
- leave of a `bot_*` member → one `findOneAndUpdate` filtered by `request_id` + `id_project` unsetting `hitl_waiting`, `hitl_invited`, `hitl_fallback`, and setting `workingStatus: 'open'` when it was `'pending'`; emit the two events; no message.
|
|
174
|
+
- leave of a human → step 1 is the atomic `findOneAndUpdate({ request_id, id_project, status: { $ne: 1000 }, 'channel.name': 'webhook', 'attributes.hitl_invited': member }, { $pull: { 'attributes.hitl_invited': member }, $addToSet: { 'attributes.hitl_left': member } }, { new: true })`; no document → return. Remaining `hitl_invited` non-empty or no `hitl_fallback` → return. Otherwise `pickReplacement(project, department(hitl_department_id), request, [...hitl_left, ...participants])`.
|
|
175
|
+
- replacement found → `addParticipantByRequestId`, `$addToSet` it into `hitl_invited`, `notifyInvited`; do not touch `hitl_waiting` / `workingStatus`.
|
|
176
|
+
- no replacement (or `hitl_department_id` null / department gone) → clear exactly as for the bot case, emit events, then `messageService.send('system', 'System', request_id, 'The invited human left and no replacement is available', id_project, 'system', { subtype: 'info', hitl_fallback: true, updateconversation: false, action: <Global Constraints action> })` built from `hitl_fallback.intent`; a send error is logged with `winston.error` and swallowed.
|
|
177
|
+
- update event → for each added human `$addToSet` into `hitl_invited`; for each removed human run the leave algorithm but stop before the pick when the same update added any human.
|
|
178
|
+
|
|
179
|
+
- [ ] **Step 1: Write the failing tests**
|
|
180
|
+
|
|
181
|
+
`test/botEventHitlFallback.js` (pure, no server):
|
|
182
|
+
```js
|
|
183
|
+
const botEvent = require('../event/botEvent');
|
|
184
|
+
it('forwards /start and the HITL fallback system message only', () => {
|
|
185
|
+
expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: '/start' })).to.equal(true);
|
|
186
|
+
expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { hitl_fallback: true, action: '#noone-id' } })).to.equal(true);
|
|
187
|
+
expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { action: '#noone-id' } })).to.equal(false);
|
|
188
|
+
expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { hitl_fallback: true } })).to.equal(false);
|
|
189
|
+
});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
`test/hitlParticipantListener.js` (server + chai-http; setup like `test/inviteParticipantsRoute.js`, department created in `beforeRequest`; each scenario invites through the route with `fallback_intent: '#noone-id'`, then removes a participant with `DELETE /:projectid/requests/:id/participants/:userId` as the owner, then `waitFor` the DB state):
|
|
193
|
+
- `invites another department agent when the invited human leaves` — pooled department with A and B (owner unavailable); invited X ∈ {A,B}; after DELETE X: participants contain the other agent, `hitl_invited` = [other], `hitl_left` = [X], `workingStatus === 'pending'`.
|
|
194
|
+
- `never re-picks a human who already left` — A and B; invite picks X, delete X → Y invited; delete Y → no human participant, fallback message sent (see next).
|
|
195
|
+
- `sends the fallback action when nobody can replace the human` — department with only A: after DELETE A, a `Message` with `recipient: request_id`, `sender: 'system'` and `attributes.action === '#noone-id{"flowError":"(Invite human) The invited human left and no replacement is available"}'` exists; `hitl_invited`/`hitl_fallback`/`hitl_waiting` undefined; `workingStatus === 'open'`.
|
|
196
|
+
- `does nothing when a human the flow did not invite leaves` — owner added with `addParticipantByRequestId` directly, then deleted: no new participant, no message, `hitl_left` undefined.
|
|
197
|
+
- `does nothing while another invited human remains` — invite `{ members: [A, B] }`, delete A: participants still B only (plus bot), no message.
|
|
198
|
+
- `does not pick or fall back when an admin replaces the invited human` — `PUT /:projectid/requests/:id/participants` with `['bot_<id>', C]` after inviting A: participants = bot + C, `hitl_invited` includes C, no message.
|
|
199
|
+
- `clears the HITL state when the bot is removed` — delete `bot_<id>`: `hitl_*` cleared, `workingStatus === 'open'`, no message.
|
|
200
|
+
- `acts once when two invited humans are removed back to back` — invite `{ members: [A, B] }` with only A,B in the department, delete A and B without awaiting between them: exactly one fallback `Message` (count by `attributes.hitl_fallback`).
|
|
201
|
+
- `ignores other channels` — a non-webhook request with `attributes.hitl_invited` seeded by `Request.updateOne`; delete that member: `hitl_left` undefined.
|
|
202
|
+
|
|
203
|
+
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/botEventHitlFallback.js test/hitlParticipantListener.js --timeout 60000 --exit` → `shouldForwardSystemMessage is not a function` and `waitFor timeout` failures.
|
|
204
|
+
- [ ] **Step 3: Implement** `pickReplacement`, `shouldForwardSystemMessage` (keep the existing `/start` behaviour byte-for-byte), the listener module, and `hitlParticipantListener.listen();` in `app.js` right after `BanUserNotifier.listen();`.
|
|
205
|
+
- [ ] **Step 4: Run to verify they pass** — same command, all PASS; then the regression set `./node_modules/.bin/mocha test/webhookRoute.js test/webhookConversationRoute.js test/webhookConversationService.js test/inviteParticipantsRoute.js test/removeParticipantsRoute.js test/hitlWaitingReset.js --timeout 60000 --exit` all PASS.
|
|
206
|
+
- [ ] **Step 5: Commit** — `feat(requests): reassign or fall back when an invited human leaves a webhook conversation` (+ trailer).
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
### Task 4: Full-suite check and spec status
|
|
211
|
+
|
|
212
|
+
**Files:**
|
|
213
|
+
- Modify: `docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` (only if new pre-existing problems are found)
|
|
214
|
+
|
|
215
|
+
- [ ] **Step 1:** Run `npm test > /tmp/server-full.log 2>&1`; record passing/failing counts.
|
|
216
|
+
- [ ] **Step 2:** On a temporary worktree of `origin/master` (`git worktree add /tmp/ts-master origin/master`, symlink `node_modules`), run the same and diff the failing test titles. Expected: no test fails only on the branch. Remove the worktree afterwards (`git worktree remove /tmp/ts-master`).
|
|
217
|
+
- [ ] **Step 3:** If a branch-only failure appears, stop and report it (it belongs to Tasks 1–3). Otherwise commit any TODO addition with `docs(todo): …` (+ trailer).
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
### Task 5: End-to-end acceptance (after the tybot, chat21-ionic and design-studio plans)
|
|
222
|
+
|
|
223
|
+
Run spec §11.8 "End-to-end" steps 1–5 on a local stack (this branch's server with the test MongoDB/Redis, tybot branch, chat21-ionic and design-studio branches), with a department containing agents A and B. Record each step's result in the SDD ledger; any failure goes back to the plan that owns the code. No commit unless a fix is needed.
|