# Webhook-started chatbot conversations + HITL — 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:** Make the agent chat usable for conversations started by a webhook flow: approval buttons stay clickable after info lines, the conversation shows a webhook channel icon, closing it asks for confirmation (it stops the flow), and lead-less loading races don't throw.

**Architecture:** Small, isolated changes. A pure helper change in `utils-message.ts` (`isLastMessage` ignores info messages) plus a new `isWebhookConversation` helper, both unit-tested; template additions for the icon; a confirmation alert in the conversations list page before the existing close/archive logic; null guards in the conversation detail page.

**Tech Stack:** Angular + Ionic, TypeScript, Jasmine/Karma (`ng test`), ngx-translate via `CustomTranslateService`.

**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` (section 7, 9.4).

## Global Constraints

- Repo `chat21-ionic`, branch `feature/webhook-chatbot-hitl` created from `origin/master` (`a7894025`, 3.4.35). Never commit to `master`.
- Webhook conversations are identified by `conversation.attributes.request_channel === 'webhook'` (set by tiledesk-server from `request.channel.name`).
- Do not change composer, canned responses, Copilot, push notifications (spec non-goals).
- Commit messages end with `Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>`.

### How to run tests
```bash
cd /Users/nicocardone/Desktop/DEV/TILEDESK/chat21-ionic
npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts
```
(`karma.conf.js` defaults to `browsers: ['Chrome']`, `singleRun: false`; the flags above make it a single headless run.)

---

## File Structure

| File | Status | Responsibility |
|---|---|---|
| `src/chat21-core/utils/utils-message.ts` | Modify | `isLastMessage` ignores info messages; new `isWebhookConversation` |
| `src/chat21-core/utils/utils-message.spec.ts` | Create | unit tests for both helpers |
| `src/chat21-core/utils/constants.ts` | Modify | `CHANNEL_TYPE.WEBHOOK = 'webhook'` |
| `src/assets/img/channel_icons/webhook.svg` | Create | channel icon |
| `src/app/chatlib/list-conversations-component/ion-list-conversations/ion-list-conversations.component.html` | Modify | webhook icon in the list |
| `src/app/components/conversation-detail/header-conversation-detail/header-conversation-detail.component.html` | Modify | webhook icon in the header |
| `src/app/pages/conversations-list/conversations-list.page.ts` | Modify | confirmation before closing a webhook conversation |
| `src/assets/i18n/en.json`, `src/assets/i18n/it.json` | Modify | confirmation message |
| `src/app/pages/conversation-detail/conversation-detail.page.ts` | Modify | null guards in `getLeadDetail` / `updateLeadInfo` |

---

### Task 1: Create the branch and make buttons survive trailing info messages

**Files:**
- Modify: `src/chat21-core/utils/utils-message.ts:78-83`
- Create: `src/chat21-core/utils/utils-message.spec.ts`

**Interfaces:**
- Produces: `isLastMessage(messages: any[], idMessage: string): boolean` — true only if `idMessage` is the uid of the last message whose `attributes.subtype` is not `info`/`info/support`. Used unchanged by `ConversationContentComponent.isLastMessage` (`src/app/chatlib/conversation-detail/conversation-content/conversation-content.component.ts:215`), which `ion-conversation-detail.component.html:207` passes to the attachment/buttons component.

- [ ] **Step 1: Create the feature branch**

```bash
cd /Users/nicocardone/Desktop/DEV/TILEDESK/chat21-ionic
git fetch origin
git switch -c feature/webhook-chatbot-hitl origin/master
git branch --unset-upstream
```

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

Create `src/chat21-core/utils/utils-message.spec.ts`:

```ts
import { isLastMessage } from './utils-message';

describe('utils-message isLastMessage', () => {

  const text = (uid: string) => ({ uid: uid, attributes: {} });
  const info = (uid: string) => ({ uid: uid, attributes: { subtype: 'info' } });
  const infoSupport = (uid: string) => ({ uid: uid, attributes: { subtype: 'info/support' } });

  it('returns true only for the last message', () => {
    expect(isLastMessage([text('1'), text('2')], '2')).toBeTrue();
    expect(isLastMessage([text('1'), text('2')], '1')).toBeFalse();
  });

  it('ignores trailing info messages (e.g. "agent added to the group")', () => {
    expect(isLastMessage([text('1'), info('2'), infoSupport('3')], '1')).toBeTrue();
    expect(isLastMessage([text('1'), info('2')], '2')).toBeFalse();
  });

  it('handles messages without attributes', () => {
    expect(isLastMessage([{ uid: '1' }, info('2')], '1')).toBeTrue();
  });

  it('returns false for empty or missing lists', () => {
    expect(isLastMessage([], '1')).toBeFalse();
    expect(isLastMessage(undefined, '1')).toBeFalse();
    expect(isLastMessage([info('1')], '1')).toBeFalse();
  });
});
```

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

Run: `npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts`
Expected: FAIL — `ignores trailing info messages` (`Expected false to be true`) and `returns false for empty or missing lists` (`TypeError: Cannot read properties of undefined`).

- [ ] **Step 4: Implement**

In `src/chat21-core/utils/utils-message.ts`, replace:

```ts
export function isLastMessage(messages, idMessage):boolean {
  if (idMessage === messages[messages.length - 1].uid) {
    return true;
  }
  return false;
}
```

with:

```ts
export function isLastMessage(messages, idMessage):boolean {
  if (!messages || messages.length === 0) {
    return false;
  }
  // info lines (member added, conversation reopened, ...) must not hide the buttons
  // of the last real message
  for (let i = messages.length - 1; i >= 0; i--) {
    if (!isInfo(messages[i])) {
      return messages[i].uid === idMessage;
    }
  }
  return false;
}
```

`isInfo` is defined earlier in the same file and already guards `message.attributes`.

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

Run: `npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts`
Expected: PASS (4 specs, 0 failures).

- [ ] **Step 6: Commit**

```bash
git add src/chat21-core/utils/utils-message.ts src/chat21-core/utils/utils-message.spec.ts
git commit -m "fix(chat): keep reply buttons visible when info messages follow them

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

---

### Task 2: Webhook channel constant, helper and icon

**Files:**
- Modify: `src/chat21-core/utils/constants.ts:44-55`
- Modify: `src/chat21-core/utils/utils-message.ts` (append helper)
- Modify: `src/chat21-core/utils/utils-message.spec.ts` (append specs)
- Create: `src/assets/img/channel_icons/webhook.svg`
- Modify: `src/app/chatlib/list-conversations-component/ion-list-conversations/ion-list-conversations.component.html:117`
- Modify: `src/app/components/conversation-detail/header-conversation-detail/header-conversation-detail.component.html:56`

**Interfaces:**
- Produces: `CHANNEL_TYPE.WEBHOOK === 'webhook'`; `isWebhookConversation(conversation: any): boolean`.

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

Append to `src/chat21-core/utils/utils-message.spec.ts`:

```ts
import { isWebhookConversation } from './utils-message';

describe('utils-message isWebhookConversation', () => {

  it('is true for conversations whose request channel is webhook', () => {
    expect(isWebhookConversation({ attributes: { request_channel: 'webhook' } })).toBeTrue();
  });

  it('is false for other channels and missing data', () => {
    expect(isWebhookConversation({ attributes: { request_channel: 'chat21' } })).toBeFalse();
    expect(isWebhookConversation({ attributes: {} })).toBeFalse();
    expect(isWebhookConversation({})).toBeFalse();
    expect(isWebhookConversation(null)).toBeFalse();
  });
});
```

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

Run: `npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts`
Expected: FAIL — compilation error `Module '"./utils-message"' has no exported member 'isWebhookConversation'`.

- [ ] **Step 3: Add the enum value**

In `src/chat21-core/utils/constants.ts`, in `export enum CHANNEL_TYPE { ... }`, replace:

```ts
    VOICE = 'voice',
}
```

with:

```ts
    VOICE = 'voice',
    WEBHOOK = 'webhook',
}
```

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

Append to `src/chat21-core/utils/utils-message.ts`:

```ts
/** Conversations started by a webhook flow (tiledesk-server request.channel.name === 'webhook') */
export function isWebhookConversation(conversation: any): boolean {
  return !!(conversation && conversation.attributes && conversation.attributes.request_channel === CHANNEL_TYPE.WEBHOOK);
}
```

(`CHANNEL_TYPE` is already imported at the top of the file.)

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

Run: `npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts`
Expected: PASS (6 specs, 0 failures).

- [ ] **Step 6: Add the icon asset**

Create `src/assets/img/channel_icons/webhook.svg`:

```svg
<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24" fill="#5f6368"><path d="M10 15h5.88c.27-.31.67-.5 1.12-.5.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5c-.44 0-.84-.19-1.12-.5H11.9c-.46 2.28-2.48 4-4.9 4-2.76 0-5-2.24-5-5 0-2.42 1.72-4.44 4-4.9v2.07c-1.16.41-2 1.53-2 2.83 0 1.65 1.35 3 3 3s3-1.35 3-3v-1zm2.5-11c1.65 0 3 1.35 3 3h2c0-2.76-2.24-5-5-5s-5 2.24-5 5c0 1.43.6 2.71 1.55 3.62l-2.35 3.9c-.68.14-1.2.75-1.2 1.48 0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5c0-.16-.02-.31-.07-.45l3.38-5.63C10.49 9.61 9.5 8.42 9.5 7c0-1.65 1.35-3 3-3zm4.5 9c-.64 0-1.23.2-1.72.54l-3.05-5.07C11.53 8.35 11 7.74 11 7c0-.83.67-1.5 1.5-1.5S14 6.17 14 7c0 .15-.02.29-.06.43l2.19 3.65c.28-.05.57-.08.87-.08 2.76 0 5 2.24 5 5s-2.24 5-5 5c-1.85 0-3.47-1.01-4.33-2.5h2.67c.48.32 1.05.5 1.66.5 1.65 0 3-1.35 3-3s-1.35-3-3-3z"/></svg>
```

- [ ] **Step 7: Show the icon in the conversation list**

In `ion-list-conversations.component.html`, after the line (117):

```html
          <img class="channel-icon" src="assets/img/channel_icons/voice.svg" *ngIf="conversation?.attributes && conversation?.attributes?.request_channel && conversation?.attributes?.request_channel.startsWith(CHANNEL_TYPE.VOICE)" >
```

add:

```html
          <img class="channel-icon" src="assets/img/channel_icons/webhook.svg" *ngIf="conversation?.attributes && conversation?.attributes?.request_channel && conversation?.attributes?.request_channel === CHANNEL_TYPE.WEBHOOK" >
```

- [ ] **Step 8: Show the icon in the conversation header**

In `header-conversation-detail.component.html`, after the line (56):

```html
                        <img class="channel-icon" src="assets/img/channel_icons/voice.svg" *ngIf="conversationAvatar?.request_channel && conversationAvatar?.request_channel.startsWith(CHANNEL_TYPE.VOICE)" >
```

add:

```html
                        <img class="channel-icon" src="assets/img/channel_icons/webhook.svg" *ngIf="conversationAvatar?.request_channel && conversationAvatar?.request_channel === CHANNEL_TYPE.WEBHOOK" >
```

- [ ] **Step 9: Compile check**

Run: `npx ng build`
Expected: build completes without errors.

- [ ] **Step 10: Commit**

```bash
git add src/chat21-core/utils/constants.ts src/chat21-core/utils/utils-message.ts src/chat21-core/utils/utils-message.spec.ts src/assets/img/channel_icons/webhook.svg src/app/chatlib/list-conversations-component/ion-list-conversations/ion-list-conversations.component.html src/app/components/conversation-detail/header-conversation-detail/header-conversation-detail.component.html
git commit -m "feat(chat): show a webhook channel icon for flow-started conversations

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

---

### Task 3: Confirm before closing a webhook conversation

**Files:**
- Modify: `src/app/pages/conversations-list/conversations-list.page.ts` (imports `:4` and `:49-50`, constructor, `onCloseConversation` `:1060-1102`)
- Modify: `src/assets/i18n/en.json:55`, `src/assets/i18n/it.json` (same key)

**Interfaces:**
- Consumes: `isWebhookConversation` (Task 2).
- Produces: `onCloseConversation(conversation)` shows an Ionic alert for webhook conversations and runs the unchanged close logic (now `closeConversationConfirmed(conversation)`) only after confirmation. Both close entry points (list item button → `onCloseConversation`, and the `conversation:closed` event at `:1041-1049`) go through it.

- [ ] **Step 1: Add the translation**

In `src/assets/i18n/en.json`, after `"CLOSE_ALERT_MSG": "Close the conversation?",` add:

```json
  "CLOSE_FLOW_CONVERSATION_ALERT_MSG": "This conversation was started by an automated flow. Closing it stops the flow. Continue?",
```

In `src/assets/i18n/it.json`, after the `"CLOSE_ALERT_MSG"` entry add:

```json
  "CLOSE_FLOW_CONVERSATION_ALERT_MSG": "Questa conversazione è stata avviata da un flusso automatico. Chiuderla interrompe il flusso. Continuare?",
```

(If `it.json` has no `CLOSE_ALERT_MSG`, add the key after `"ALERT_TITLE"`.)

- [ ] **Step 2: Import AlertController and the helper**

In `conversations-list.page.ts` replace:

```ts
import { IonContent, ModalController } from '@ionic/angular'
```

with:

```ts
import { AlertController, IonContent, ModalController } from '@ionic/angular'
```

and replace:

```ts
import { getProjectIdSelectedConversation } from 'src/chat21-core/utils/utils-message';
```

with:

```ts
import { getProjectIdSelectedConversation, isWebhookConversation } from 'src/chat21-core/utils/utils-message';
```

Add `public alertController: AlertController,` as a new constructor parameter (next to the existing `ModalController` parameter).

- [ ] **Step 3: Split the close logic behind a confirmation**

Replace the method signature line and the lines before `this.loadingIsActive = false`:

```ts
  onCloseConversation(conversation: ConversationModel) {
    this.logger.log('[CONVS-LIST-PAGE] onCloseConversation  conversation', conversation)
```

with:

```ts
  onCloseConversation(conversation: ConversationModel) {
    this.logger.log('[CONVS-LIST-PAGE] onCloseConversation  conversation', conversation)
    if (isWebhookConversation(conversation)) {
      this.presentAlertConfirmCloseFlowConversation(conversation)
      return
    }
    this.closeConversationConfirmed(conversation)
  }

  async presentAlertConfirmCloseFlowConversation(conversation: ConversationModel) {
    const keys = ['ALERT_TITLE', 'CLOSE_FLOW_CONVERSATION_ALERT_MSG', 'CLOSE_ALERT_CANCEL_LABEL', 'CLOSE_ALERT_CONFIRM_LABEL']
    const translationMap = this.translateService.translateLanguage(keys)
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: translationMap.get('ALERT_TITLE'),
      message: translationMap.get('CLOSE_FLOW_CONVERSATION_ALERT_MSG'),
      buttons: [
        {
          text: translationMap.get('CLOSE_ALERT_CANCEL_LABEL'),
          role: 'cancel',
          cssClass: 'secondary',
        },
        {
          text: translationMap.get('CLOSE_ALERT_CONFIRM_LABEL'),
          handler: () => {
            this.closeConversationConfirmed(conversation)
          },
        },
      ],
    })
    await alert.present()
  }

  closeConversationConfirmed(conversation: ConversationModel) {
```

The rest of the original method body (from `this.loadingIsActive = false` to its closing `}`) stays unchanged and now belongs to `closeConversationConfirmed`.

- [ ] **Step 4: Compile check**

Run: `npx ng build`
Expected: build completes without errors.

- [ ] **Step 5: Manual verification**

With a local stack (or stage after deployment), open chat21-ionic as an agent participant of:
1. a conversation with `request.channel.name = 'webhook'` → click the list item's archive icon → the alert appears; **Cancel** keeps the conversation; **OK** closes it (request status 1000 in the dashboard).
2. a widget conversation → archive closes immediately, as before.

- [ ] **Step 6: Commit**

```bash
git add src/app/pages/conversations-list/conversations-list.page.ts src/assets/i18n/en.json src/assets/i18n/it.json
git commit -m "feat(chat): confirm before closing a conversation started by a flow

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

---

### Task 4: Null guards in the conversation detail page

**Files:**
- Modify: `src/app/pages/conversation-detail/conversation-detail.page.ts` (`getLeadDetail` `:1004-1044`, `updateLeadInfo` `:1365-1395`)

**Interfaces:** none (defensive change).

- [ ] **Step 1: Guard `getLeadDetail`**

Replace:

```ts
        if(request && request.channel){
          this.conversation.attributes['request_channel'] = request.channel.name
        } 
        if (request.lead && request.lead.email) { //LEAD has an email
```

with:

```ts
        if(request && request.channel && this.conversation && this.conversation.attributes){
          this.conversation.attributes['request_channel'] = request.channel.name
        }
        if (!request || !request.lead) {
          return
        }
        if (request.lead.email) { //LEAD has an email
```

- [ ] **Step 2: Guard `updateLeadInfo`**

In `updateLeadInfo(msg)`, replace both occurrences of:

```ts
        this.conversation.attributes['projectId'],
        this.conversation.attributes['project_name'],
        this.conversation.attributes['request_channel']
```

with:

```ts
        this.conversation?.attributes?.['projectId'],
        this.conversation?.attributes?.['project_name'],
        this.conversation?.attributes?.['request_channel']
```

- [ ] **Step 3: Compile check and existing tests**

Run: `npx ng build`
Expected: build completes without errors.

Run: `npx ng test --watch=false --browsers=ChromeHeadless --include=src/chat21-core/utils/utils-message.spec.ts`
Expected: PASS.

- [ ] **Step 4: Commit**

```bash
git add src/app/pages/conversation-detail/conversation-detail.page.ts
git commit -m "fix(chat): guard lead and conversation attributes while loading request details

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