# HITL participant removal — chat21-ionic 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:** 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.

**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.

**Tech Stack:** Angular 12 + Ionic, Node 14 (nvm), Jasmine/Karma through the workspace narrow tsconfig.

**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11.6 (and §7 for v1).

## Global Constraints

- Branch `feature/webhook-chatbot-hitl` (checked out, head `7988a98d`; `origin/master` unchanged). Never commit to `master`, never push.
- Node 14 for every npm/npx command: prefix `source ~/.nvm/nvm.sh >/dev/null && nvm use 14 >/dev/null && `. Never `npm install`.
- Leave is shown only when `isWebhookConversation(conversation)` and `!conversation.archived`.
- 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`).
- 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).
- Do not change archive/close behaviour, composer, canned responses, Copilot, push notifications.
- 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.
- Build check: `npx ng build` exits 0 with only the 5 baseline "is part of the TypeScript compilation but it's unused" warnings.
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.

## Review Focus

1. Leave pressed twice quickly → only one request is sent (disable the action while the alert/request is pending).
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.
3. A webhook conversation that is archived → no Leave button.
4. The project id for the DELETE comes from the conversation (`support-group-<projectId>-…`), never from another selected project.
5. Every locale file still parses as JSON after the insert.

---

## Texts

| File | `LEAVE_FLOW_CONVERSATION_ALERT_MSG` | `LEAVE_CONVERSATION_CONFIRM_LABEL` | `LEAVE_CONVERSATION_ERROR` |
|---|---|---|---|
| en | You will leave this conversation. The flow will look for another operator, or continue without you. Continue? | Leave | Unable to leave the conversation |
| it | Uscirai da questa conversazione. Il flusso cercherà un altro operatore o continuerà senza di te. Continuare? | Esci | Impossibile uscire dalla conversazione |
| 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 |
| 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 |
| fr | Vous allez quitter cette conversation. Le flux cherchera un autre opérateur ou continuera sans vous. Continuer ? | Quitter | Impossible de quitter la conversation |
| pt | Você sairá desta conversa. O fluxo procurará outro operador ou continuará sem você. Continuar? | Sair | Não foi possível sair da conversa |
| ru | Вы покинете этот разговор. Сценарий найдёт другого оператора или продолжит без вас. Продолжить? | Покинуть | Не удалось покинуть разговор |
| uk | Ви залишите цю розмову. Сценарій знайде іншого оператора або продовжить без вас. Продовжити? | Залишити | Не вдалося залишити розмову |
| 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ı |
| 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 |
| sr | Напустићете овај разговор. Ток ће потражити другог оператера или наставити без вас. Наставити? | Напусти | Није могуће напустити разговор |
| ar | ستغادر هذه المحادثة. سيبحث التدفق عن مشغل آخر أو يتابع بدونك. هل تريد المتابعة؟ | مغادرة | تعذر مغادرة المحادثة |
| 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ı |
| kk | Сіз бұл сөйлесуден шығасыз. Ағын басқа операторды іздейді немесе сізсіз жалғасады. Жалғастыру керек пе? | Шығу | Сөйлесуден шығу мүмкін болмады |
| uz | Siz bu suhbatdan chiqasiz. Oqim boshqa operatorni qidiradi yoki sizsiz davom etadi. Davom etilsinmi? | Chiqish | Suhbatdan chiqib bo'lmadi |

---

### Task 1: Leave helper and service call

**Files:**
- Modify: `src/chat21-core/utils/utils-message.ts` (append), `src/chat21-core/utils/utils-message.spec.ts` (append)
- Modify: `src/app/services/tiledesk/tiledesk.service.ts` (append after `addParticipant`)
- Create: `src/app/services/tiledesk/tiledesk-remove-participant.spec.ts`
- 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

**Interfaces:**
- Produces: `canLeaveConversation(conversation: any): boolean` in `utils-message.ts` — `isWebhookConversation(conversation) && !conversation.archived`.
- Produces: `TiledeskService.removeParticipant(requestid: string, userid: string, project_id: string): Observable<any>` — DELETE per Global Constraints, `Content-Type: application/json`.

- [ ] **Step 1: Write the failing tests**
  - `describe('utils-message canLeaveConversation')`: true for `{ attributes: { request_channel: 'webhook' }, archived: false }`; false when `archived: true`; false for `request_channel: 'chat21'`; false for `null`.
  - `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`.
- [ ] **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.
- [ ] **Step 3: Implement** both members.
- [ ] **Step 4: Run to verify they pass** — `TOTAL: 15 SUCCESS` (10 existing + 4 + 1).
- [ ] **Step 5: Commit** — `feat(chat): add the leave-conversation helper and service call` (+ trailer), committing only the `src/` files.

---

### Task 2: Leave button, confirmation and error toast

**Files:**
- 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)
- 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)
- Modify: `src/app/pages/conversations-list/conversations-list.page.html` (`(onLeaveConversation)="onLeaveConversation($event)"` on both list usages, next to `(onCloseConversation)` at `:70` and `:95`)
- Modify: `src/app/pages/conversations-list/conversations-list.page.ts` (inject `ToastController`; `onLeaveConversation(conversation)`, `presentAlertConfirmLeaveConversation(conversation)`, `leaveConversationConfirmed(conversation)`)
- Modify: the 15 `src/assets/i18n/*.json` files (Texts table)

**Interfaces:**
- 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`).
- 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).
- 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.

- [ ] **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).
- [ ] **Step 2:** Implement the component output/button and the page methods.
- [ ] **Step 3:** `npx ng build` → exit 0 with only the 5 baseline warnings; Task 1 spec command → `TOTAL: 15 SUCCESS`.
- [ ] **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.
- [ ] **Step 5: Commit** — `feat(chat): let operators leave a conversation started by a flow` (+ trailer).
