# AI chat history

The **chat history** displays previous conversations between the user and the AI.

## Usage

Chat history helps users maintain context, revisit previous interactions, and continue conversations across longer tasks.

This pattern is a combination of a [list](<https://element.siemens.io/components/lists-tables-trees/list/>) and the [side panel](<https://element.siemens.io/components/layout-navigation/side-panel/>).

![Chat history](<../images/chat-history-pattern.png>)

### Best practices

- Use auto-generated or user-defined titles for chat conversations, as they provide a stable reference for each conversation.
- A preview may replace the title when conversations are short-lived or primarily accessed in recent context.

## Design

### Anatomy

![AI chat history anatomy](<../images/chat-history-anatomy.png>)

> 1\. Title, 2. Metadata (optional), 3. Actions (optional)

### Actions

Actions allow users to manage chat conversations (for example rename, move, archive, delete, or export).

- If a chat history item has only one action, display it directly and associate it clearly with the item.
- If there are multiple actions, group them in an overflow menu.

![AI chat history actions](<../images/chat-history-actions.png>)

### Metadata

It is typically displayed as text-based informational attributes. Icons may be added when they improve recognition. [Badges](<https://element.siemens.io/components/status-notifications/badges/>) can be used for explicit states or applied labels that should stand out visually.

Each metadata element can be replaced by a [link](<https://element.siemens.io/components/buttons-menus/links/>), styled with `text-secondary`.

![AI chat history metadata](<../images/chat-history-metadata.png>)

If space remains insufficient due to a high number of metadata elements, consider prioritizing the most relevant attributes and progressively removing secondary ones to preserve clarity.

![AI chat history elements](<../images/chat-history-metadata-overflow.png>)

### Layouts

#### Full page layout

When the AI chat is integrated as a full page layout, the chat history is displayed in a collapsible side panel.

![Chat history in full page](<../images/chat-history-full-page-layout.png>)

#### Side panel layout

If AI chat is already handled in a side panel, chat history is accessed within the same panel. Selecting a conversation replaces the current chat content inside that panel.

![Chat history in side panel](<../images/chat-history-side-panel-layout.png>)

#### Chat organization

Conversations may be organized into temporal sections (e.g., Today, Yesterday, Last 7 days, Last 30 days, Older).

Additional grouping methods or filters can be used when further organization is needed.

- Use [tabs](<https://element.siemens.io/components/layout-navigation/tabs/>) for broad, mutually exclusive categories to help users focus on one category at a time.
- Use [summary chips](<https://element.siemens.io/components/status-notifications/summary-chip/>) to provide a quick overview of grouped conversations

![Chat history organization](<../images/chat-history-organization.png>)

## Code

Use the side panel inner navigation pattern to switch between the chat history and a selected conversation while keeping both views in the same panel.

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  afterNextRender,
  Component,
  computed,
  ElementRef,
  inject,
  Injector,
  signal,
  viewChild
} from '@angular/core';
import { RouterLink } from '@angular/router';
import {
  SiApplicationHeaderComponent,
  SiHeaderActionItemComponent,
  SiHeaderActionsDirective,
  SiHeaderBrandDirective,
  SiHeaderLogoDirective
} from '@siemens/element-ng/application-header';
import {
  ChatInputAttachment,
  PromptSuggestion,
  SiAiMessageComponent,
  SiAiWelcomeScreenComponent,
  SiChatContainerComponent,
  SiChatInputComponent,
  SiUserMessageComponent
} from '@siemens/element-ng/chat-messages';
import { ContentActionBarMainItem } from '@siemens/element-ng/content-action-bar';
import { SiMarkdownComponent } from '@siemens/element-ng/markdown';
import {
  SiSidePanelBackButtonComponent,
  SiSidePanelComponent,
  SiSidePanelContentComponent
} from '@siemens/element-ng/side-panel';
import { LOG_EVENT } from '@siemens/live-preview';

import { markdownOptions } from './markdown-options';

interface Conversation {
  id: string;
  group: string;
  title: string;
  prompt: string;
  response: string;
}

interface ChatMessage {
  role: 'user' | 'ai';
  content: string;
}

@Component({
  selector: 'app-sample',
  imports: [
    RouterLink,
    SiChatContainerComponent,
    SiAiMessageComponent,
    SiApplicationHeaderComponent,
    SiChatInputComponent,
    SiHeaderActionItemComponent,
    SiHeaderActionsDirective,
    SiHeaderBrandDirective,
    SiHeaderLogoDirective,
    SiMarkdownComponent,
    SiAiWelcomeScreenComponent,
    SiSidePanelBackButtonComponent,
    SiSidePanelComponent,
    SiSidePanelContentComponent,
    SiUserMessageComponent
  ],
  templateUrl: './si-chat-history.html'
})
export class SampleComponent {
  protected readonly markdownOptions = markdownOptions;
  private logEvent = inject(LOG_EVENT);

  readonly collapsed = signal(false);
  readonly activeView = signal<'chat' | 'history'>('chat');
  readonly searchTerm = signal('');
  readonly inputValue = signal('');

  readonly conversations: Conversation[] = [
    {
      id: 'building-faults',
      group: 'Today',
      title: 'Building faults',
      prompt: 'Show me the high priority faults in my building A.',
      // Content lines must start at column 0, otherwise markdown renders them as a code block.
      response: `I've identified several high-priority issues in Building A that need urgent attention:

1. **The HVAC systems on the 3rd and 5th floors are failing to maintain stable temperatures**, creating discomfort and potential equipment risks.
2. **There's a water leakage problem in the basement pump room** that could lead to electrical hazards if ignored.
3. **Elevator Unit #2 has been stalling during busy hours**, and several smoke detectors in Block A-East are currently offline.

These faults must be addressed immediately to maintain safety and compliance.`
    },
    {
      id: 'temperature-west-wing',
      group: 'Today',
      title: 'Temperature fluctuation in west wing',
      prompt: 'Why is the west wing temperature fluctuating?',
      response:
        'The supply-air sensor shows intermittent readings. Inspect the sensor connection before changing the control parameters.'
    },
    {
      id: 'airflow-meeting-rooms',
      group: 'Today',
      title: 'HVAC airflow imbalance in meeting rooms',
      prompt: 'Compare airflow across the meeting rooms.',
      response:
        'Rooms 2.14 and 2.16 are below the expected airflow range. The remaining meeting rooms are operating normally.'
    },
    {
      id: 'chiller-restart',
      group: 'Yesterday',
      title: 'Chiller restart after overnight shutdown',
      prompt: 'Summarize the overnight chiller restart.',
      response:
        'The restart completed successfully at 06:12. No active alarms remain, and the chilled-water loop is stable.'
    },
    {
      id: 'heating-loop',
      group: 'Last 7 days',
      title: 'Heating loop imbalance investigation',
      prompt: 'What did we find in the heating loop investigation?',
      response:
        'The investigation found a partially closed balancing valve on the north branch. Correcting it restored the expected flow.'
    }
  ];

  readonly selectedConversation = signal<Conversation | undefined>(this.conversations[0]);
  readonly messages = signal<ChatMessage[]>(this.messagesFor(this.conversations[0]));
  readonly heading = computed(() => this.selectedConversation()?.title ?? 'New chat');
  readonly primaryActions = computed<ContentActionBarMainItem[]>(() =>
    this.activeView() === 'chat'
      ? [
          {
            type: 'action',
            id: 'chat-history',
            label: 'Chat history',
            icon: 'element-backup',
            iconOnly: true,
            action: () => this.showHistory()
          },
          {
            type: 'action',
            label: 'New chat',
            icon: 'element-edit-bulk',
            iconOnly: true,
            action: () => this.startNewChat()
          }
        ]
      : []
  );

  readonly filteredConversationGroups = computed(() => {
    const searchTerm = this.searchTerm().trim().toLowerCase();
    const groups = ['Today', 'Yesterday', 'Last 7 days'];

    return groups
      .map(group => ({
        group,
        conversations: this.conversations.filter(
          conversation =>
            conversation.group === group && conversation.title.toLowerCase().includes(searchTerm)
        )
      }))
      .filter(group => group.conversations.length > 0);
  });

  private readonly backButton = viewChild('backButton', {
    read: ElementRef<HTMLButtonElement>
  });
  private readonly sidePanelContent = viewChild<unknown, ElementRef<HTMLElement>>(
    'sidePanelContent',
    { read: ElementRef }
  );
  private readonly injector = inject(Injector);
  private readonly conversationMessages = new Map(
    this.conversations.map(conversation => [conversation.id, this.messagesFor(conversation)])
  );

  readonly promptSuggestions: PromptSuggestion[] = [
    { text: 'How do I optimize performance for large datasets?' },
    { text: 'What are the best practices for data validation?' },
    { text: 'Help me troubleshoot this error message' }
  ];

  showHistory(): void {
    this.searchTerm.set('');
    this.activeView.set('history');
    afterNextRender(() => this.backButton()?.nativeElement.focus(), { injector: this.injector });
  }

  showChat(): void {
    this.activeView.set('chat');
    afterNextRender(
      () =>
        this.sidePanelContent()
          ?.nativeElement.querySelector<HTMLElement>('[data-id="chat-history"]')
          ?.focus(),
      { injector: this.injector }
    );
  }

  selectConversation(conversation: Conversation): void {
    this.selectedConversation.set(conversation);
    this.messages.set(
      this.conversationMessages.get(conversation.id) ?? this.messagesFor(conversation)
    );
    this.inputValue.set('');
    this.showChat();
  }

  startNewChat(): void {
    this.selectedConversation.set(undefined);
    this.messages.set([]);
    this.inputValue.set('');
    this.showChat();
  }

  onPromptSelected(suggestion: PromptSuggestion): void {
    this.logEvent(`Prompt selected: ${suggestion.text}`);
  }

  sendMessage(event: { content: string; attachments: ChatInputAttachment[] }): void {
    const content = event.content.trim();
    if (!content) {
      return;
    }

    const messages = [
      ...this.messages(),
      { role: 'user' as const, content },
      {
        role: 'ai' as const,
        content: 'This example keeps the response concise. Connect your AI service here.'
      }
    ];
    this.messages.set(messages);

    const selectedConversation = this.selectedConversation();
    if (selectedConversation) {
      this.conversationMessages.set(selectedConversation.id, messages);
    }

    this.inputValue.set('');
  }

  private messagesFor(conversation: Conversation): ChatMessage[] {
    return [
      { role: 'user', content: conversation.prompt },
      { role: 'ai', content: conversation.response }
    ];
  }
}
```

Template:

```html
<div class="si-layout-fixed-height h-100">
  <si-side-panel size="wide" mode="scroll" [collapsed]="collapsed()" (closed)="collapsed.set(true)">
    <main class="has-navbar-fixed-top px-6">
      <si-application-header>
        <si-header-brand>
          <a siHeaderLogo routerLink="/" class="d-none d-md-flex"></a>
          <h1 class="application-name">Application name</h1>
        </si-header-brand>

        <si-header-actions>
          <button
            type="button"
            si-header-action-item
            icon="element-ai"
            (click)="collapsed.set(false)"
          >
            AI assistant
          </button>
        </si-header-actions>
      </si-application-header>

      <div class="pt-6">
        <button type="button" class="btn btn-secondary" (click)="collapsed.set(false)">
          Open AI assistant
        </button>
      </div>
    </main>

    <si-side-panel-content
      #sidePanelContent
      searchPlaceholder="Search conversations"
      [heading]="activeView() === 'history' ? 'Chat history' : heading()"
      [primaryActions]="primaryActions()"
      [searchable]="activeView() === 'history'"
      (searchEvent)="searchTerm.set($event)"
    >
      @if (activeView() === 'history') {
        <button
          #backButton
          type="button"
          siSidePanelBackButton
          aria-label="Back to conversation"
          (click)="showChat()"
        ></button>
      }

      @if (activeView() === 'history') {
        <div class="pb-6">
          @for (group of filteredConversationGroups(); track group.group) {
            <h2 class="si-h6 text-secondary px-6 mb-0" [class]="$first ? 'pt-7 pb-5' : 'py-5'">
              {{ group.group }}
            </h2>
            <ul>
              @for (conversation of group.conversations; track conversation.id) {
                <li>
                  <button
                    type="button"
                    class="list-item list-item-action"
                    [class.active]="conversation.id === selectedConversation()?.id"
                    [attr.aria-current]="
                      conversation.id === selectedConversation()?.id ? 'page' : null
                    "
                    (click)="selectConversation(conversation)"
                  >
                    <span class="list-item-title">{{ conversation.title }}</span>
                  </button>
                </li>
              }
            </ul>
          }
        </div>
      } @else {
        <div class="si-layout-fixed-height w-100 h-100">
          <si-chat-container colorVariant="base-1">
            @for (message of messages(); track $index) {
              @if (message.role === 'user') {
                <si-user-message>
                  <si-markdown [markdown]="message.content" [options]="markdownOptions" />
                </si-user-message>
              } @else {
                <si-ai-message>
                  <si-markdown [markdown]="message.content" [options]="markdownOptions" />
                </si-ai-message>
              }
            } @empty {
              <si-ai-welcome-screen
                [promptSuggestions]="promptSuggestions"
                (promptSelected)="onPromptSelected($event)"
              >
                <p class="h1 mb-0"> <strong>Hello</strong>, </p>
                <p class="h1 mb-0">how can I help you today?</p>
              </si-ai-welcome-screen>
            }

            <si-chat-input
              class="w-100"
              placeholder="Enter a command, question or topic…"
              disclaimer="The content is AI generated. Always verify the information for accuracy."
              [allowAttachments]="false"
              [(value)]="inputValue"
              (send)="sendMessage($event)"
            />
          </si-chat-container>
        </div>
      }
    </si-side-panel-content>
  </si-side-panel>
</div>
```
