---
title: "AI Chat"
description: "Application scaffold: an Open WebUI-style AI chat - chats by day in a sidebar, a model picker, images, audio, video and files as attachments, voice messages, answers that ask with Chat Components cards and scripted example chats, streamed Markdown answers with thinking, copy, edit, regenerate and ratings, chat controls for the system prompt and sampling, an OpenAI-compatible connection and a sign-in - built only from the shipped components."
slug: "scaffold-ai-chat"
---

import { DocPage, PageHeader, DocText, DocLink } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="scaffold-ai-chat" title="AI Chat" introStyle="max-width:44rem;">
  An Open WebUI-style chat for language models - "Lumen". Pick a suggestion or type a question: the answer streams in as Markdown, with its thinking folded above it. Attach pictures, audio, video and documents - with +, by pasting, by dropping them on the conversation - or record a voice message. Copy, edit, regenerate and rate answers, keep chats by day in the sidebar, set the system prompt and sampling in Controls, or point it at any OpenAI-compatible API. Adapted from the <a href="https://github.com/kyr0/defuss/tree/main/examples/ai-chat" target="_blank" rel="noopener">defuss ai-chat example</a>. Part of the <DocLink href="application-scaffolds.html">Application Scaffolds</DocLink>.
</PageHeader>

<div class="flex flex-wrap items-center gap-2 mb-6">
  <a class="btn" href="app-ai-chat.html" target="_blank" rel="noopener"><i data-lucide="maximize-2"></i> Open full screen</a>
  <a class="btn" data-variant="outline" href="#how-it-works">How it works</a>
</div>

```html example label="AI Chat" schema="none" height="50" mode="desktop" hint="The whole chat in one source. Chats are routes (#/c/...) of defuss-dom-router; Settings › Language translates the chrome with defuss-i18n; the sidebars are the Sidebar component, the transcript the Session, every message a Message with a Bubble. Answers come from a local demo model, or from any OpenAI-compatible API set in Controls › Connection." previewStyle="align-items:stretch;padding:0;"
<style>
  /* Lumen: the scaffold's own glue - layout and the chat look; every control
     is a shipped component (Sidebar, Session, Message, Bubble, Marker,
     Textarea, Dropdown, Dialog, Alert Dialog, Slider, Switch, Avatar, Table) */
  .ac {
    --ac-measure: 48rem;
    container: ac / inline-size;
    position: relative;
    width: 100%;
    height: var(--scaffold-height, 50rem);
    min-height: 0;
    overflow: hidden;
    background: var(--background);
    color: var(--foreground);
    font-size: 0.875rem;
  }
  .ac [hidden] {
    display: none !important;
  }

  /* the two sidebars sit in the flow: open or closed, never an icon rail */
  .ac .app-sidebar {
    position: relative;
    flex: none;
    height: 100%;
    display: flex;
  }
  .ac .app-sidebar[data-state='collapsed'] {
    display: none;
  }
  .ac-nav {
    --sidebar-width: 16.5rem;
  }
  .ac-controls {
    --sidebar-width: 20rem;
    background: var(--background);
  }
  .ac .sidebar-header {
    justify-content: space-between;
    padding: 0.625rem 0.5rem 0.625rem 0.875rem;
    border-bottom: 0;
  }
  .ac-header-tools {
    display: flex;
    align-items: center;
    gap: 0.25rem;
  }
  .ac .sidebar-logo {
    gap: 0.5rem;
    font-weight: 600;
    font-size: 0.9375rem;
    text-decoration: none;
    color: inherit;
  }
  .ac-mark {
    display: grid;
    place-items: center;
    width: 1.75rem;
    height: 1.75rem;
    border-radius: 999px;
    background: var(--foreground);
    color: var(--background);
    flex: none;
  }
  .ac-mark svg {
    width: 1rem;
    height: 1rem;
  }
  .ac-nav-tools {
    display: grid;
    gap: 0.25rem;
    padding: 0 0.5rem 0.5rem;
  }
  .ac-new {
    justify-content: flex-start;
    gap: 0.625rem;
    width: 100%;
  }
  .ac-search {
    position: relative;
  }
  .ac-search svg {
    position: absolute;
    inset-inline-start: 0.625rem;
    top: 50%;
    translate: 0 -50%;
    width: 1rem;
    height: 1rem;
    color: var(--muted-foreground);
    pointer-events: none;
  }
  .ac-search .input {
    padding-inline-start: 2rem;
    background: transparent;
  }
  .ac .sidebar-content {
    padding-inline: 0.25rem;
  }
  .ac-chat {
    position: relative;
  }
  .ac-chat .sidebar-link {
    padding-inline-end: 2rem;
  }
  .ac-chat .sidebar-link span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .ac-chat-more {
    position: absolute;
    inset-inline-end: 0.25rem;
    top: 50%;
    translate: 0 -50%;
    opacity: 0;
  }
  .ac-chat:is(:hover, :focus-within) .ac-chat-more,
  .ac-chat-more[aria-expanded='true'] {
    opacity: 1;
  }
  .ac-rename {
    padding: 0.125rem 0.25rem;
  }
  .ac-empty-list {
    padding: 0.75rem 1rem;
    color: var(--muted-foreground);
    font-size: 0.8125rem;
  }
  .ac .sidebar-footer {
    padding: 0.5rem;
  }
  .ac-user {
    justify-content: flex-start;
    gap: 0.625rem;
    width: 100%;
    height: auto;
    padding: 0.375rem 0.5rem;
  }

  /* main column */
  .ac-main {
    position: relative;
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 0;
    height: 100%;
  }
  .ac-top {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    min-height: 3.25rem;
    padding: 0.5rem 0.75rem;
  }
  .ac-top-spacer {
    flex: 1;
  }
  /* the header's sidebar and new-chat buttons show only while the sidebar is closed */
  .ac:has(.ac-nav[data-state='expanded']) .ac-when-closed {
    display: none;
  }
  .ac-model {
    gap: 0.375rem;
    font-size: 1.0625rem;
    font-weight: 600;
  }
  .ac-model-menu {
    min-width: 17rem;
  }
  .ac-model-menu .dropdown-item {
    align-items: flex-start;
  }
  .ac-model-menu small {
    display: block;
    color: var(--muted-foreground);
    font-size: 0.75rem;
    font-weight: 400;
  }
  .ac-pill {
    margin-inline-start: 0.25rem;
  }

  /* the conversation: a Session without its card frame */
  .ac-session.session {
    flex: 1;
    border: 0;
    border-radius: 0;
    background: var(--background);
  }
  .ac-session .session-viewport {
    padding-inline: 1rem;
  }
  .ac-session .session-content {
    width: 100%;
    max-width: var(--ac-measure);
    margin-inline: auto;
    gap: 1.5rem;
    padding-block-end: 1rem;
  }
  .ac-session .session-footer {
    border-top: 0;
    background: var(--background);
    padding: 0 1rem 0.75rem;
  }
  .ac-session[data-empty] .session-viewport {
    display: none;
  }
  .ac-session[data-empty] {
    justify-content: center;
  }
  .ac-composer {
    width: 100%;
    max-width: var(--ac-measure);
    margin-inline: auto;
  }
  .ac-composer .textarea-group {
    border-radius: 1.5rem;
    padding: 0.5rem 0.5rem 0.375rem 0.75rem;
    box-shadow: var(--shadow-sm);
  }
  .ac-composer .textarea {
    padding-inline: 0.25rem;
  }
  .ac-fine {
    margin: 0.5rem 0 0;
    text-align: center;
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  .ac-send[data-streaming] .ac-icon-send,
  .ac-send:not([data-streaming]) .ac-icon-stop {
    display: none;
  }

  /* the welcome: model, greeting and suggestions above the composer while a chat is empty */
  .ac-welcome {
    display: none;
    flex-direction: column;
    align-items: center;
    gap: 1.25rem;
    width: 100%;
    max-width: var(--ac-measure);
    margin: 0 auto 1.25rem;
    padding-inline: 1rem;
    text-align: center;
  }
  .ac-session[data-empty] .ac-welcome {
    display: flex;
  }
  .ac-welcome h1 {
    margin: 0;
    font-size: 1.75rem;
    font-weight: 500;
    letter-spacing: -0.01em;
    text-wrap: balance;
  }
  .ac-welcome-model {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: var(--muted-foreground);
  }
  .ac-suggestions {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.5rem;
    width: 100%;
    margin: 0;
    padding: 0;
    list-style: none;
    text-align: start;
  }
  .ac-suggestion {
    display: grid;
    gap: 0.125rem;
    width: 100%;
    height: auto;
    padding: 0.625rem 0.875rem;
    justify-content: start;
    text-align: start;
    white-space: normal;
    font-weight: 500;
  }
  .ac-suggestion small {
    color: var(--muted-foreground);
    font-weight: 400;
  }

  /* messages */
  /* a question: up to 36rem wide (a percentage on the bubble would resolve against its shrink-wrapped column) */
  .ac-session .message[data-align='end'] > .message-content {
    max-width: min(36rem, 85%);
  }
  /* an answer: the model's avatar beside its name at the top, the text the whole measure wide */
  .ac-turn:not([data-align]) {
    align-items: flex-start;
  }
  .ac-turn:not([data-align]) > .message-avatar {
    margin-block: 0.125rem 0;
  }
  .ac-turn:not([data-align]) > .message-content {
    flex: 1;
    max-width: none;
  }
  .ac-turn .bubble[data-variant='ghost'] {
    width: 100%;
  }
  .ac-turn .message-footer {
    gap: 0;
  }
  .ac-turn .message-footer .btn[aria-pressed='true'] {
    color: var(--foreground);
    background: var(--accent);
  }
  .ac-mark-sm {
    width: 100%;
    height: 100%;
  }
  .ac-think {
    margin-block-end: 0.25rem;
  }
  .ac-think > summary {
    cursor: pointer;
    list-style: none;
  }
  .ac-think > summary::-webkit-details-marker {
    display: none;
  }
  .ac-think-body {
    margin: 0.25rem 0 0.5rem;
    padding-inline-start: 0.875rem;
    border-inline-start: 2px solid var(--border);
    color: var(--muted-foreground);
    white-space: pre-wrap;
  }
  .ac-info {
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  /* attachments: images as media bubbles, audio and video in their players, the rest as attachment cards */
  .ac-files {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    gap: 0.375rem;
    max-width: 100%;
  }
  .ac-files > .bubble:has(> .ac-image) {
    width: fit-content;
  }
  .ac-image.bubble-content {
    width: fit-content;
    padding: 0;
    border: 0;
    cursor: zoom-in;
  }
  .ac-image img {
    display: block;
    width: auto;
    height: auto;
    max-width: 16rem; /* a length, not a percentage: inside a fit-content bubble a percentage resolves late and the bubble keeps the picture's full width */
    max-height: 16rem;
  }
  .ac-files :is(.video, .audio) {
    width: min(22rem, 100%);
  }
  .ac-files .message-attachment {
    max-width: 22rem;
  }
  .ac-composer .file-drop-thumb img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  [data-ac-record][aria-pressed='true'] {
    color: var(--destructive);
  }
  .ac-recording output {
    font-variant-numeric: tabular-nums;
  }
  .ac-rec-dot {
    display: block;
    width: 0.5rem;
    height: 0.5rem;
    border-radius: 999px;
    background: var(--destructive);
    animation: ac-pulse 1s ease-in-out infinite;
  }
  @keyframes ac-pulse {
    50% {
      opacity: 0.3;
    }
  }
  .ac-preview img {
    display: block;
    max-width: 100%;
    max-height: 68vh;
    margin-inline: auto;
    border-radius: var(--radius-md);
  }
  .ac-edit {
    width: min(36rem, 100%);
  }

  /* Markdown answers: prose rhythm; code blocks are Code mockups, tables the Table component */
  .ac-md {
    line-height: 1.65;
  }
  .ac-md > :first-child {
    margin-top: 0;
  }
  .ac-md > :last-child {
    margin-bottom: 0;
  }
  .ac-md :is(p, ul, ol, .table-container, blockquote, .ac-code) {
    margin: 0 0 0.75rem;
  }
  .ac-md :is(h1, h2, h3, h4) {
    margin: 1rem 0 0.5rem;
    font-size: 1rem;
    font-weight: 600;
  }
  .ac-md :is(ul, ol) {
    padding-inline-start: 1.25rem;
  }
  .ac-md li + li {
    margin-top: 0.25rem;
  }
  .ac-md :not(pre) > code {
    padding: 0.0625rem 0.3125rem;
    border-radius: var(--radius-sm);
    background: var(--muted);
    font-family: var(--font-mono);
    font-size: 0.8125rem;
  }
  .ac-md blockquote {
    padding-inline-start: 0.875rem;
    border-inline-start: 3px solid var(--border);
    color: var(--muted-foreground);
  }
  .ac-code {
    position: relative;
  }
  .ac-code-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.25rem 0.25rem 0.25rem 0.75rem;
    border-radius: var(--radius-lg) var(--radius-lg) 0 0;
    background: var(--muted);
    color: var(--muted-foreground);
    font-family: var(--font-mono);
    font-size: 0.75rem;
  }
  .ac-code .mockup-code {
    margin: 0;
    border-start-start-radius: 0;
    border-start-end-radius: 0;
  }
  .ac-md .table-container {
    overflow-x: auto;
  }

  /* controls */
  .ac-controls .sidebar-content {
    padding: 0 1rem 1rem;
  }
  .ac-form {
    display: grid;
    gap: 1rem;
  }
  .ac-form fieldset {
    display: grid;
    gap: 0.75rem;
    margin: 0;
    padding: 0;
    border: 0;
    min-width: 0;
  }
  .ac-form legend {
    margin-bottom: 0.5rem;
    padding: 0;
    font-size: 0.75rem;
    font-weight: 600;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    color: var(--muted-foreground);
  }
  .ac-field {
    display: grid;
    gap: 0.375rem;
  }
  .ac-field-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.75rem;
  }
  .ac-field output {
    font-family: var(--font-mono);
    font-size: 0.75rem;
    color: var(--muted-foreground);
  }
  .ac-hint {
    margin: 0;
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  .ac-conn {
    display: grid;
    gap: 0.375rem;
  }
  .ac-form fieldset[disabled] .ac-api {
    opacity: 0.55;
  }

  /* settings dialog */
  .ac-settings-list {
    display: grid;
    gap: 0;
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .ac-settings-list li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    padding-block: 0.75rem;
    border-bottom: 1px solid var(--border);
  }
  .ac-settings-list li:last-child {
    border-bottom: 0;
  }
  .ac-settings-list label {
    display: grid;
    gap: 0.125rem;
  }
  .ac-settings-list small {
    color: var(--muted-foreground);
  }
  .ac-locale {
    flex: none;
    width: auto;
  }

  /* sign-in */
  .ac-auth {
    position: absolute;
    inset: 0;
    z-index: 40;
    display: grid;
    place-items: center;
    padding: 1rem;
    background:
      radial-gradient(60rem 30rem at 50% -10%, color-mix(in oklab, var(--muted) 90%, transparent), transparent),
      var(--background);
  }
  .ac-auth .card {
    width: min(24rem, 100%);
  }
  .ac-auth-brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.25rem;
    font-weight: 600;
  }
  .ac-auth form {
    display: grid;
    gap: 0.875rem;
  }
  .ac-demo {
    margin: 0;
    color: var(--muted-foreground);
    font-size: 0.75rem;
  }
  .ac-demo code {
    font-family: var(--font-mono);
    color: var(--foreground);
  }

  /* narrow: the sidebars lie over the conversation, a scrim closes them */
  .ac-scrim {
    display: none;
  }
  @container ac (width < 52rem) {
    .ac .app-sidebar {
      position: absolute;
      inset-block: 0;
      z-index: 20;
      box-shadow: var(--shadow-xl);
    }
    .ac-nav {
      inset-inline-start: 0;
    }
    .ac-controls {
      inset-inline-end: 0;
      max-width: 90%;
    }
    .ac:has(.app-sidebar[data-state='expanded']) .ac-scrim {
      display: block;
      position: absolute;
      inset: 0;
      z-index: 15;
      background: color-mix(in oklab, var(--foreground) 25%, transparent);
    }
    .ac:has(.ac-nav[data-state='expanded']) .ac-when-closed {
      display: inline-flex;
    }
    .ac-suggestions {
      grid-template-columns: minmax(0, 1fr);
    }
    .ac-suggestions li:nth-child(n + 3) {
      display: none;
    }
    .ac-welcome h1 {
      font-size: 1.375rem;
    }
  }
  @media (prefers-reduced-motion: reduce) {
    .ac-rec-dot {
      animation: none;
    }
    .ac * {
      scroll-behavior: auto;
    }
  }
</style>

<div class="ac sidebar-layout" id="ac" data-ac data-i18n-component>
  <aside
    class="app-sidebar ac-nav"
    id="ac-nav"
    data-state="expanded"
    aria-label="Chats"
    data-i18n-aria-label-en="Chats"
    data-i18n-aria-label-de="Chats"
  >
    <div class="sidebar-header">
      <a class="sidebar-logo" href="#/" data-router-link
        ><span class="ac-mark" aria-hidden="true"
          ><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
            <path
              d="M12 3v4M12 17v4M3 12h4M17 12h4M6.3 6.3l2.5 2.5M15.2 15.2l2.5 2.5M6.3 17.7l2.5-2.5M15.2 8.8l2.5-2.5"
            /></svg></span
        ><span class="sidebar-logo-text">Lumen</span></a
      >
      <div class="ac-header-tools">
        <label class="swap ac-mode" data-variant="rotate" data-size="sm">
          <input
            type="checkbox"
            data-ac-mode
            aria-label="Dark mode"
            data-i18n-aria-label-en="Dark mode"
            data-i18n-aria-label-de="Dunkelmodus"
          />
          <span class="swap-on" aria-hidden="true"><i data-lucide="moon"></i></span>
          <span class="swap-off" aria-hidden="true"><i data-lucide="sun"></i></span>
        </label>
        <button
          class="btn"
          data-variant="ghost"
          data-size="icon-sm"
          type="button"
          data-sidebar-trigger="ac-nav"
          aria-label="Close sidebar"
          data-i18n-aria-label-en="Close sidebar"
          data-i18n-aria-label-de="Seitenleiste schließen"
          ><i data-lucide="panel-left-close"></i
        ></button>
      </div>
    </div>
    <div class="ac-nav-tools">
      <a class="btn ac-new" data-variant="ghost" href="#/" data-router-link data-ac-new
        ><i data-lucide="square-pen"></i> <span data-i18n-target="new-chat">New chat</span></a
      >
      <div class="ac-search"
        ><i data-lucide="search"></i
        ><input
          class="input"
          type="search"
          data-size="sm"
          data-ac-search
          placeholder="Search chats"
          aria-label="Search chats"
          data-i18n-placeholder-en="Search chats"
          data-i18n-placeholder-de="Chats durchsuchen"
          data-i18n-aria-label-en="Search chats"
          data-i18n-aria-label-de="Chats durchsuchen"
      /></div>
    </div>
    <div class="sidebar-content" data-ac-list>
      <details class="sidebar-group" open data-ac-group="examples">
        <summary><span data-i18n-target="grp-examples">Examples</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Example chats"
          data-i18n-aria-label-en="Example chats"
          data-i18n-aria-label-de="Beispiel-Chats"
        ></nav>
      </details>
      <details class="sidebar-group" open data-ac-group="pinned">
        <summary><span data-i18n-target="grp-pinned">Pinned</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Pinned chats"
          data-i18n-aria-label-en="Pinned chats"
          data-i18n-aria-label-de="Angeheftete Chats"
        ></nav>
      </details>
      <details class="sidebar-group" open data-ac-group="today">
        <summary><span data-i18n-target="grp-today">Today</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Today"
          data-i18n-aria-label-en="Today"
          data-i18n-aria-label-de="Heute"
        ></nav>
      </details>
      <details class="sidebar-group" open data-ac-group="yesterday">
        <summary><span data-i18n-target="grp-yesterday">Yesterday</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Yesterday"
          data-i18n-aria-label-en="Yesterday"
          data-i18n-aria-label-de="Gestern"
        ></nav>
      </details>
      <details class="sidebar-group" open data-ac-group="week">
        <summary><span data-i18n-target="grp-week">Previous 7 days</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Previous 7 days"
          data-i18n-aria-label-en="Previous 7 days"
          data-i18n-aria-label-de="Letzte 7 Tage"
        ></nav>
      </details>
      <details class="sidebar-group" open data-ac-group="older">
        <summary><span data-i18n-target="grp-older">Older</span><i data-lucide="chevron-right"></i></summary>
        <nav
          class="sidebar-nav"
          aria-label="Older"
          data-i18n-aria-label-en="Older"
          data-i18n-aria-label-de="Älter"
        ></nav>
      </details>
      <p class="ac-empty-list" data-ac-none hidden data-i18n-target="no-chats">No chats match your search.</p>
    </div>
    <div class="sidebar-footer">
      <button
        class="btn ac-user"
        data-variant="ghost"
        type="button"
        aria-haspopup="menu"
        aria-expanded="false"
        aria-controls="ac-user-menu"
        data-dropdown-trigger="ac-user-menu"
        ><span class="avatar" data-size="sm"><span class="avatar-fallback">AL</span></span
        ><span data-ac-user-name>Ada Lindqvist</span></button
      >
      <div
        id="ac-user-menu"
        role="menu"
        popover
        class="dropdown-content"
        aria-label="Account"
        data-i18n-aria-label-en="Account"
        data-i18n-aria-label-de="Konto"
      >
        <button role="menuitem" class="dropdown-item" tabindex="-1" data-dialog-trigger="ac-settings"
          ><i data-lucide="settings"></i> <span data-i18n-target="menu-settings">Settings</span></button
        >
        <button role="menuitem" class="dropdown-item" tabindex="-1" data-ac-action="controls"
          ><i data-lucide="sliders-horizontal"></i> <span data-i18n-target="menu-controls">Chat controls</span></button
        >
        <div class="dropdown-separator" role="separator"></div>
        <button role="menuitem" class="dropdown-item" tabindex="-1" data-ac-action="sign-out"
          ><i data-lucide="log-out"></i> <span data-i18n-target="menu-sign-out">Sign out</span></button
        >
      </div>
    </div>
  </aside>

  <div class="ac-main">
    <header class="ac-top">
      <button
        class="btn ac-when-closed"
        data-variant="ghost"
        data-size="icon"
        type="button"
        data-sidebar-trigger="ac-nav"
        aria-label="Open sidebar"
        data-i18n-aria-label-en="Open sidebar"
        data-i18n-aria-label-de="Seitenleiste öffnen"
        ><i data-lucide="panel-left-open"></i
      ></button>
      <a
        class="btn ac-when-closed"
        data-variant="ghost"
        data-size="icon"
        href="#/"
        data-router-link
        aria-label="New chat"
        data-i18n-aria-label-en="New chat"
        data-i18n-aria-label-de="Neuer Chat"
        ><i data-lucide="square-pen"></i
      ></a>
      <button
        class="btn ac-model"
        data-variant="ghost"
        type="button"
        aria-haspopup="menu"
        aria-expanded="false"
        aria-controls="ac-models"
        data-dropdown-trigger="ac-models"
        ><span data-ac-model-name>Lumen 8B</span><i data-lucide="chevron-down"></i
      ></button>
      <div
        id="ac-models"
        role="menu"
        popover
        class="dropdown-content ac-model-menu"
        aria-label="Model"
        data-i18n-aria-label-en="Model"
        data-i18n-aria-label-de="Modell"
      >
        <div class="dropdown-label" data-i18n-target="models-label">Models</div>
        <button
          role="menuitemradio"
          class="dropdown-item dropdown-radio"
          aria-checked="true"
          tabindex="-1"
          data-value="lumen-8b"
          ><span
            ><span>Lumen 8B</span><small data-i18n-target="model-8b">Fast, for everyday questions</small></span
          ></button
        >
        <button
          role="menuitemradio"
          class="dropdown-item dropdown-radio"
          aria-checked="false"
          tabindex="-1"
          data-value="lumen-70b"
          ><span
            ><span>Lumen 70B</span><small data-i18n-target="model-70b">Slower, longer and more careful</small></span
          ></button
        >
        <button
          role="menuitemradio"
          class="dropdown-item dropdown-radio"
          aria-checked="false"
          tabindex="-1"
          data-value="lumen-coder"
          ><span
            ><span>Lumen Coder 14B</span><small data-i18n-target="model-coder">Answers with code first</small></span
          ></button
        >
        <button
          role="menuitemradio"
          class="dropdown-item dropdown-radio"
          aria-checked="false"
          tabindex="-1"
          data-value="echo"
          ><span
            ><span>Echo</span><small data-i18n-target="model-echo">Repeats your message - for testing</small></span
          ></button
        >
        <button
          role="menuitemradio"
          class="dropdown-item dropdown-radio"
          aria-checked="false"
          tabindex="-1"
          data-value="api"
          data-ac-api-model
          hidden
          ><span
            ><span data-ac-api-model-name>API model</span
            ><small data-i18n-target="model-api">From your OpenAI-compatible API</small></span
          ></button
        >
      </div>
      <span class="badge ac-pill" data-variant="outline" data-ac-conn-badge hidden data-i18n-target="badge-api"
        >API</span
      >
      <span class="ac-top-spacer"></span>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon"
        type="button"
        data-sidebar-trigger="ac-controls"
        aria-label="Chat controls"
        data-i18n-aria-label-en="Chat controls"
        data-i18n-aria-label-de="Chat-Steuerung"
        ><i data-lucide="sliders-horizontal"></i
      ></button>
    </header>

    <section
      class="session ac-session"
      id="ac-session"
      aria-label="Conversation"
      data-i18n-aria-label-en="Conversation"
      data-i18n-aria-label-de="Unterhaltung"
      data-default-position="last-anchor"
      data-drop
      data-drop-label="Drop files to attach"
      data-empty
    >
      <div
        class="session-viewport"
        aria-label="Messages"
        data-i18n-aria-label-en="Messages"
        data-i18n-aria-label-de="Nachrichten"
      >
        <div class="session-content"></div>
        <button
          type="button"
          class="session-scroll-button"
          data-to="end"
          aria-label="Scroll to the latest message"
          data-i18n-aria-label-en="Scroll to the latest message"
          data-i18n-aria-label-de="Zur neuesten Nachricht"
        ></button>
      </div>
      <div class="ac-welcome" data-ac-welcome>
        <div class="ac-welcome-model"
          ><span class="avatar" data-size="sm"
            ><span class="avatar-fallback ac-mark"
              ><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
                <path
                  d="M12 3v4M12 17v4M3 12h4M17 12h4M6.3 6.3l2.5 2.5M15.2 15.2l2.5 2.5M6.3 17.7l2.5-2.5M15.2 8.8l2.5-2.5"
                /></svg></span></span
          ><span data-ac-model-name>Lumen 8B</span></div
        >
        <h1 data-i18n-target="greeting">How can I help you today?</h1>
        <ul
          class="ac-suggestions"
          aria-label="Suggestions"
          data-i18n-aria-label-en="Suggestions"
          data-i18n-aria-label-de="Vorschläge"
        >
          <li
            ><button
              class="btn ac-suggestion"
              data-variant="outline"
              type="button"
              data-ac-prompt="Write a debounce function in JavaScript"
              ><span data-i18n-target="sg-1">Write a debounce function</span
              ><small data-i18n-target="sg-1d">in JavaScript, with a short explanation</small></button
            ></li
          >
          <li
            ><button
              class="btn ac-suggestion"
              data-variant="outline"
              type="button"
              data-ac-prompt="Compare SQLite, Postgres and DuckDB in a table"
              ><span data-i18n-target="sg-2">Compare three databases</span
              ><small data-i18n-target="sg-2d">SQLite, Postgres and DuckDB in a table</small></button
            ></li
          >
          <li
            ><button
              class="btn ac-suggestion"
              data-variant="outline"
              type="button"
              data-ac-prompt="Plan a three-day trip to Lisbon"
              ><span data-i18n-target="sg-3">Plan a city trip</span
              ><small data-i18n-target="sg-3d">three days in Lisbon, day by day</small></button
            ></li
          >
          <li
            ><button
              class="btn ac-suggestion"
              data-variant="outline"
              type="button"
              data-ac-prompt="Explain how a transformer reads a sentence"
              ><span data-i18n-target="sg-4">Explain a transformer</span
              ><small data-i18n-target="sg-4d">how it reads a sentence, step by step</small></button
            ></li
          >
        </ul>
      </div>
      <div class="session-footer">
        <div class="ac-composer">
          <form
            class="textarea-group"
            data-ac-composer
            aria-label="Message composer"
            data-i18n-aria-label-en="Message composer"
            data-i18n-aria-label-de="Nachricht verfassen"
          >
            <ul
              class="file-drop-list"
              aria-label="Attachments"
              data-i18n-aria-label-en="Attachments"
              data-i18n-aria-label-de="Anhänge"
            ></ul>
            <textarea
              class="textarea"
              data-rows="1"
              data-max-rows="8"
              name="message"
              placeholder="Send a message"
              aria-label="Message"
              data-i18n-placeholder-en="Send a message"
              data-i18n-placeholder-de="Nachricht senden"
              data-i18n-aria-label-en="Message"
              data-i18n-aria-label-de="Nachricht"
            ></textarea>
            <div class="textarea-group-actions">
              <button
                class="btn"
                data-variant="ghost"
                data-size="icon-sm"
                type="button"
                data-ac-attach
                aria-label="Attach files"
                data-i18n-aria-label-en="Attach files"
                data-i18n-aria-label-de="Dateien anhängen"
                ><i data-lucide="plus"></i
              ></button>
              <input type="file" hidden multiple data-ac-file />
              <button
                class="btn"
                data-variant="ghost"
                data-size="icon-sm"
                type="button"
                aria-pressed="false"
                data-ac-record
                aria-label="Record a voice message"
                data-i18n-aria-label-en="Record a voice message"
                data-i18n-aria-label-de="Sprachnachricht aufnehmen"
                ><i data-lucide="mic"></i
              ></button>
              <div class="marker ac-recording" role="status" data-ac-recording hidden
                ><span class="marker-icon" aria-hidden="true"><span class="ac-rec-dot"></span></span
                ><span class="marker-content"
                  ><span data-i18n-target="recording">Recording</span> <output data-ac-rec-time>0:00</output></span
                ></div
              >
              <button
                class="toggle"
                data-size="sm"
                type="button"
                aria-pressed="false"
                data-ac-think-toggle
                aria-label="Think before answering"
                data-i18n-aria-label-en="Think before answering"
                data-i18n-aria-label-de="Vor der Antwort nachdenken"
                ><i data-lucide="lightbulb"></i> <span data-i18n-target="think">Think</span></button
              >
              <span class="textarea-group-spacer"></span>
              <button
                class="btn ac-send"
                data-size="icon-sm"
                type="submit"
                data-ac-send
                aria-label="Send message"
                data-i18n-aria-label-en="Send message"
                data-i18n-aria-label-de="Nachricht senden"
                ><i class="ac-icon-send" data-lucide="arrow-up"></i><i class="ac-icon-stop" data-lucide="square"></i
              ></button>
            </div>
          </form>
          <p class="ac-fine" data-ac-fine>Lumen answers from a demo model in this page. Check important information.</p>
        </div>
      </div>
    </section>
    <div class="ac-scrim" data-ac-scrim></div>
  </div>

  <aside
    class="app-sidebar ac-controls"
    id="ac-controls"
    data-side="right"
    data-state="collapsed"
    aria-label="Chat controls"
    data-i18n-aria-label-en="Chat controls"
    data-i18n-aria-label-de="Chat-Steuerung"
  >
    <div class="sidebar-header">
      <strong data-i18n-target="controls-title">Controls</strong>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        data-sidebar-trigger="ac-controls"
        aria-label="Close controls"
        data-i18n-aria-label-en="Close controls"
        data-i18n-aria-label-de="Steuerung schließen"
        ><i data-lucide="x"></i
      ></button>
    </div>
    <div class="sidebar-content">
      <form class="ac-form" data-ac-settings>
        <fieldset>
          <legend data-i18n-target="sec-connection">Connection</legend>
          <div
            class="ac-conn"
            role="radiogroup"
            aria-label="Connection"
            data-i18n-aria-label-en="Connection"
            data-i18n-aria-label-de="Verbindung"
          >
            <div class="flex items-center gap-2"
              ><input class="radio" type="radio" name="connection" id="ac-conn-demo" value="demo" checked /><label
                class="label"
                for="ac-conn-demo"
                data-i18n-target="conn-demo"
                >Demo model in this page</label
              ></div
            >
            <div class="flex items-center gap-2"
              ><input class="radio" type="radio" name="connection" id="ac-conn-api" value="api" /><label
                class="label"
                for="ac-conn-api"
                data-i18n-target="conn-api"
                >OpenAI-compatible API</label
              ></div
            >
          </div>
          <fieldset class="ac-api" data-ac-api disabled>
            <div class="ac-field"
              ><label class="label" for="ac-base" data-i18n-target="base-url">Base URL</label
              ><input
                class="input"
                id="ac-base"
                name="baseUrl"
                type="url"
                data-size="sm"
                placeholder="http://localhost:11434/v1"
                value="http://localhost:11434/v1"
            /></div>
            <div class="ac-field"
              ><label class="label" for="ac-key" data-i18n-target="api-key">API key</label
              ><input
                class="input"
                id="ac-key"
                name="apiKey"
                type="password"
                data-size="sm"
                placeholder="sk-..."
                autocomplete="off"
            /></div>
            <div class="ac-field"
              ><label class="label" for="ac-model-id" data-i18n-target="model-id">Model</label
              ><input class="input" id="ac-model-id" name="model" type="text" data-size="sm" value="llama3.2"
            /></div>
            <p class="ac-hint" data-i18n-target="api-hint"
              >Requests go from this browser to the URL; the server must allow it (CORS).</p
            >
            <div class="switch-item flex items-center gap-2"
              ><input class="switch" type="checkbox" role="switch" id="ac-tool" name="componentTool" checked /><label
                for="ac-tool"
                data-i18n-target="p-tool"
                >Chat components (cards and the tool)</label
              ></div
            >
          </fieldset>
        </fieldset>
        <div class="separator" role="separator"></div>
        <fieldset>
          <legend data-i18n-target="sec-system">System prompt</legend>
          <textarea
            class="textarea"
            name="systemPrompt"
            data-rows="3"
            data-max-rows="8"
            aria-label="System prompt"
            data-i18n-aria-label-en="System prompt"
            data-i18n-aria-label-de="Systemanweisung"
          >You are a helpful assistant.</textarea>
        </fieldset>
        <div class="separator" role="separator"></div>
        <fieldset>
          <legend data-i18n-target="sec-params">Advanced parameters</legend>
          <div class="ac-field"
            ><div class="ac-field-row"
              ><label class="label" for="ac-temp" data-i18n-target="p-temp">Temperature</label
              ><output for="ac-temp" data-ac-out="temperature">0.7</output></div
            ><input class="slider" id="ac-temp" name="temperature" type="range" min="0" max="2" step="0.05" value="0.7"
          /></div>
          <div class="ac-field"
            ><div class="ac-field-row"
              ><label class="label" for="ac-topp" data-i18n-target="p-topp">Top P</label
              ><output for="ac-topp" data-ac-out="topP">0.9</output></div
            ><input class="slider" id="ac-topp" name="topP" type="range" min="0" max="1" step="0.01" value="0.9"
          /></div>
          <div class="ac-field"
            ><div class="ac-field-row"
              ><label class="label" for="ac-topk" data-i18n-target="p-topk">Top K</label
              ><output for="ac-topk" data-ac-out="topK">40</output></div
            ><input class="slider" id="ac-topk" name="topK" type="range" min="1" max="100" step="1" value="40"
          /></div>
          <div class="ac-field"
            ><div class="ac-field-row"
              ><label class="label" for="ac-rep" data-i18n-target="p-rep">Repetition penalty</label
              ><output for="ac-rep" data-ac-out="repetitionPenalty">1.1</output></div
            ><input
              class="slider"
              id="ac-rep"
              name="repetitionPenalty"
              type="range"
              min="1"
              max="2"
              step="0.05"
              value="1.1"
          /></div>
          <div class="ac-field"
            ><div class="ac-field-row"
              ><label class="label" for="ac-pres" data-i18n-target="p-pres">Presence penalty</label
              ><output for="ac-pres" data-ac-out="presencePenalty">0</output></div
            ><input
              class="slider"
              id="ac-pres"
              name="presencePenalty"
              type="range"
              min="0"
              max="2"
              step="0.05"
              value="0"
          /></div>
          <div class="ac-field"
            ><label class="label" for="ac-max" data-i18n-target="p-max">Max tokens</label
            ><input
              class="input"
              id="ac-max"
              name="maxTokens"
              type="number"
              data-size="sm"
              min="16"
              max="128000"
              step="1"
              value="2048"
          /></div>
          <div class="switch-item flex items-center gap-2"
            ><input class="switch" type="checkbox" role="switch" id="ac-thinking" name="enableThinking" /><label
              for="ac-thinking"
              data-i18n-target="p-think"
              >Think before answering</label
            ></div
          >
        </fieldset>
        <button class="btn" data-variant="outline" data-size="sm" type="button" data-ac-reset
          ><i data-lucide="rotate-ccw"></i> <span data-i18n-target="reset">Reset to defaults</span></button
        >
      </form>
    </div>
  </aside>

  <dialog class="dialog" id="ac-settings" role="dialog" aria-modal="true" aria-labelledby="ac-settings-title">
    <div class="dialog-content">
      <div class="dialog-header">
        <h2 class="dialog-title" id="ac-settings-title" data-i18n-target="settings-title">Settings</h2>
        <p class="dialog-description" data-i18n-target="settings-desc">Language, appearance and how sending works.</p>
      </div>
      <div class="dialog-body">
        <ul class="ac-settings-list">
          <li
            ><label for="ac-lang"
              ><strong data-i18n-target="set-lang">Language</strong
              ><small data-i18n-target="set-lang-d">Menus, labels and buttons</small></label
            ><div
              class="language-switcher ac-locale"
              id="ac-lang"
              data-app-locale
              role="group"
              aria-label="Language"
              data-i18n-aria-label-en="Language"
              data-i18n-aria-label-de="Sprache"
              data-languages="en de"
              data-value="en"
              data-size="sm"
            ></div
          ></li>
          <li
            ><label for="ac-dark"
              ><strong data-i18n-target="set-dark">Dark mode</strong
              ><small data-i18n-target="set-dark-d">Easier on the eyes at night</small></label
            ><input class="switch" type="checkbox" role="switch" id="ac-dark" data-ac-dark
          /></li>
          <li
            ><label for="ac-enter"
              ><strong data-i18n-target="set-enter">Enter sends</strong
              ><small data-i18n-target="set-enter-d">Shift+Enter starts a new line</small></label
            ><input class="switch" type="checkbox" role="switch" id="ac-enter" data-ac-enter checked
          /></li>
          <li
            ><label
              ><strong data-i18n-target="set-clear">Delete all chats</strong
              ><small data-i18n-target="set-clear-d">Pinned chats too - this cannot be undone</small></label
            ><button class="btn" data-variant="destructive" data-size="sm" type="button" data-ac-action="clear-all"
              ><span data-i18n-target="set-clear-btn">Delete all</span></button
            ></li
          >
        </ul>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-dialog-close
          ><span data-i18n-target="done">Done</span></button
        >
      </div>
    </div>
  </dialog>

  <dialog
    class="dialog ac-preview"
    id="ac-preview"
    data-size="xl"
    role="dialog"
    aria-modal="true"
    aria-labelledby="ac-preview-title"
  >
    <div class="dialog-content">
      <div class="dialog-header">
        <h2 class="dialog-title" id="ac-preview-title" data-ac-preview-title>Image</h2>
        <p class="dialog-description" data-ac-preview-meta></p>
      </div>
      <div class="dialog-body"><img data-ac-preview-img alt="" /></div>
      <div class="dialog-footer">
        <a class="btn" data-variant="outline" href="#" download data-ac-preview-download
          ><i data-lucide="download"></i> <span data-i18n-target="download">Download</span></a
        >
        <button class="btn" type="button" data-dialog-close><span data-i18n-target="close">Close</span></button>
      </div>
    </div>
  </dialog>

  <dialog
    class="alert-dialog"
    id="ac-confirm"
    role="alertdialog"
    aria-modal="true"
    aria-labelledby="ac-confirm-title"
    aria-describedby="ac-confirm-desc"
  >
    <div class="alert-dialog-content">
      <div class="alert-dialog-header">
        <h2 class="alert-dialog-title" id="ac-confirm-title" data-ac-confirm-title>Delete?</h2>
        <p class="alert-dialog-description" id="ac-confirm-desc" data-ac-confirm-desc>This cannot be undone.</p>
      </div>
      <div class="alert-dialog-footer">
        <button class="btn" data-variant="outline" type="button" data-alert-dialog-close
          ><span data-i18n-target="cancel">Cancel</span></button
        >
        <button class="btn" data-variant="destructive" type="button" data-ac-confirm-ok
          ><span data-i18n-target="delete">Delete</span></button
        >
      </div>
    </div>
  </dialog>

  <section class="ac-auth" data-ac-auth hidden aria-labelledby="ac-auth-title">
    <div class="card">
      <div class="card-header">
        <div class="ac-auth-brand"
          ><span class="ac-mark" aria-hidden="true"
            ><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
              <path
                d="M12 3v4M12 17v4M3 12h4M17 12h4M6.3 6.3l2.5 2.5M15.2 15.2l2.5 2.5M6.3 17.7l2.5-2.5M15.2 8.8l2.5-2.5"
              /></svg></span
          >Lumen</div
        >
        <h2 class="card-title" id="ac-auth-title" data-i18n-target="auth-title">Sign in to Lumen</h2>
        <p class="card-description" data-i18n-target="auth-desc"
          >Chat with any OpenAI-compatible model, answers streamed as they are written.</p
        >
      </div>
      <div class="card-content">
        <form data-ac-signin novalidate>
          <div class="alert" data-variant="destructive" role="alert" data-ac-auth-error hidden
            ><div class="alert-content"
              ><h5 class="alert-title" data-i18n-target="auth-error">Invalid email or password</h5
              ><p class="alert-description" data-i18n-target="auth-error-d">Use the demo account below.</p></div
            ></div
          >
          <div class="ac-field"
            ><label class="label" for="ac-email" data-i18n-target="email">Email</label
            ><input
              class="input"
              id="ac-email"
              name="email"
              type="email"
              autocomplete="username"
              required
              placeholder="you@example.com"
          /></div>
          <div class="ac-field"
            ><label class="label" for="ac-password" data-i18n-target="password">Password</label
            ><input
              class="input"
              id="ac-password"
              name="password"
              type="password"
              autocomplete="current-password"
              required
          /></div>
          <button class="btn" type="submit"><span data-i18n-target="sign-in">Sign in</span></button>
          <p class="ac-demo"
            ><span data-i18n-target="demo-account">Demo account:</span> <code>ada@example.com</code> /
            <code>lumen</code></p
          >
        </form>
      </div>
    </div>
  </section>

  <template data-i18n-for="new-chat" data-i18n-locale="en">New chat</template>
  <template data-i18n-for="new-chat" data-i18n-locale="de">Neuer Chat</template>
  <template data-i18n-for="grp-examples" data-i18n-locale="en">Examples</template>
  <template data-i18n-for="grp-examples" data-i18n-locale="de">Beispiele</template>
  <template data-i18n-for="p-tool" data-i18n-locale="en">Chat components (cards and the tool)</template>
  <template data-i18n-for="p-tool" data-i18n-locale="de">Chat-Komponenten (Karten und das Tool)</template>
  <template data-i18n-for="grp-pinned" data-i18n-locale="en">Pinned</template>
  <template data-i18n-for="grp-pinned" data-i18n-locale="de">Angeheftet</template>
  <template data-i18n-for="grp-today" data-i18n-locale="en">Today</template>
  <template data-i18n-for="grp-today" data-i18n-locale="de">Heute</template>
  <template data-i18n-for="grp-yesterday" data-i18n-locale="en">Yesterday</template>
  <template data-i18n-for="grp-yesterday" data-i18n-locale="de">Gestern</template>
  <template data-i18n-for="grp-week" data-i18n-locale="en">Previous 7 days</template>
  <template data-i18n-for="grp-week" data-i18n-locale="de">Letzte 7 Tage</template>
  <template data-i18n-for="grp-older" data-i18n-locale="en">Older</template>
  <template data-i18n-for="grp-older" data-i18n-locale="de">Älter</template>
  <template data-i18n-for="no-chats" data-i18n-locale="en">No chats match your search.</template>
  <template data-i18n-for="no-chats" data-i18n-locale="de">Kein Chat passt zur Suche.</template>
  <template data-i18n-for="menu-settings" data-i18n-locale="en">Settings</template>
  <template data-i18n-for="menu-settings" data-i18n-locale="de">Einstellungen</template>
  <template data-i18n-for="menu-controls" data-i18n-locale="en">Chat controls</template>
  <template data-i18n-for="menu-controls" data-i18n-locale="de">Chat-Steuerung</template>
  <template data-i18n-for="menu-sign-out" data-i18n-locale="en">Sign out</template>
  <template data-i18n-for="menu-sign-out" data-i18n-locale="de">Abmelden</template>
  <template data-i18n-for="models-label" data-i18n-locale="en">Models</template>
  <template data-i18n-for="models-label" data-i18n-locale="de">Modelle</template>
  <template data-i18n-for="model-8b" data-i18n-locale="en">Fast, for everyday questions</template>
  <template data-i18n-for="model-8b" data-i18n-locale="de">Schnell, für Alltagsfragen</template>
  <template data-i18n-for="model-70b" data-i18n-locale="en">Slower, longer and more careful</template>
  <template data-i18n-for="model-70b" data-i18n-locale="de">Langsamer, ausführlicher und sorgfältiger</template>
  <template data-i18n-for="model-coder" data-i18n-locale="en">Answers with code first</template>
  <template data-i18n-for="model-coder" data-i18n-locale="de">Antwortet zuerst mit Code</template>
  <template data-i18n-for="model-echo" data-i18n-locale="en">Repeats your message - for testing</template>
  <template data-i18n-for="model-echo" data-i18n-locale="de">Wiederholt deine Nachricht - zum Testen</template>
  <template data-i18n-for="model-api" data-i18n-locale="en">From your OpenAI-compatible API</template>
  <template data-i18n-for="model-api" data-i18n-locale="de">Von deiner OpenAI-kompatiblen API</template>
  <template data-i18n-for="badge-api" data-i18n-locale="en">API</template>
  <template data-i18n-for="badge-api" data-i18n-locale="de">API</template>
  <template data-i18n-for="greeting" data-i18n-locale="en">How can I help you today?</template>
  <template data-i18n-for="greeting" data-i18n-locale="de">Wie kann ich dir heute helfen?</template>
  <template data-i18n-for="sg-1" data-i18n-locale="en">Write a debounce function</template>
  <template data-i18n-for="sg-1" data-i18n-locale="de">Schreib eine Debounce-Funktion</template>
  <template data-i18n-for="sg-1d" data-i18n-locale="en">in JavaScript, with a short explanation</template>
  <template data-i18n-for="sg-1d" data-i18n-locale="de">in JavaScript, kurz erklärt</template>
  <template data-i18n-for="sg-2" data-i18n-locale="en">Compare three databases</template>
  <template data-i18n-for="sg-2" data-i18n-locale="de">Vergleiche drei Datenbanken</template>
  <template data-i18n-for="sg-2d" data-i18n-locale="en">SQLite, Postgres and DuckDB in a table</template>
  <template data-i18n-for="sg-2d" data-i18n-locale="de">SQLite, Postgres und DuckDB in einer Tabelle</template>
  <template data-i18n-for="sg-3" data-i18n-locale="en">Plan a city trip</template>
  <template data-i18n-for="sg-3" data-i18n-locale="de">Plane eine Städtereise</template>
  <template data-i18n-for="sg-3d" data-i18n-locale="en">three days in Lisbon, day by day</template>
  <template data-i18n-for="sg-3d" data-i18n-locale="de">drei Tage Lissabon, Tag für Tag</template>
  <template data-i18n-for="sg-4" data-i18n-locale="en">Explain a transformer</template>
  <template data-i18n-for="sg-4" data-i18n-locale="de">Erkläre einen Transformer</template>
  <template data-i18n-for="sg-4d" data-i18n-locale="en">how it reads a sentence, step by step</template>
  <template data-i18n-for="sg-4d" data-i18n-locale="de">wie er einen Satz liest, Schritt für Schritt</template>
  <template data-i18n-for="think" data-i18n-locale="en">Think</template>
  <template data-i18n-for="think" data-i18n-locale="de">Nachdenken</template>
  <template data-i18n-for="controls-title" data-i18n-locale="en">Controls</template>
  <template data-i18n-for="controls-title" data-i18n-locale="de">Steuerung</template>
  <template data-i18n-for="sec-connection" data-i18n-locale="en">Connection</template>
  <template data-i18n-for="sec-connection" data-i18n-locale="de">Verbindung</template>
  <template data-i18n-for="conn-demo" data-i18n-locale="en">Demo model in this page</template>
  <template data-i18n-for="conn-demo" data-i18n-locale="de">Demo-Modell in dieser Seite</template>
  <template data-i18n-for="conn-api" data-i18n-locale="en">OpenAI-compatible API</template>
  <template data-i18n-for="conn-api" data-i18n-locale="de">OpenAI-kompatible API</template>
  <template data-i18n-for="base-url" data-i18n-locale="en">Base URL</template>
  <template data-i18n-for="base-url" data-i18n-locale="de">Basis-URL</template>
  <template data-i18n-for="api-key" data-i18n-locale="en">API key</template>
  <template data-i18n-for="api-key" data-i18n-locale="de">API-Schlüssel</template>
  <template data-i18n-for="model-id" data-i18n-locale="en">Model</template>
  <template data-i18n-for="model-id" data-i18n-locale="de">Modell</template>
  <template data-i18n-for="api-hint" data-i18n-locale="en"
    >Requests go from this browser to the URL; the server must allow it (CORS).</template
  >
  <template data-i18n-for="api-hint" data-i18n-locale="de"
    >Anfragen gehen von diesem Browser an die URL; der Server muss sie erlauben (CORS).</template
  >
  <template data-i18n-for="sec-system" data-i18n-locale="en">System prompt</template>
  <template data-i18n-for="sec-system" data-i18n-locale="de">Systemanweisung</template>
  <template data-i18n-for="sec-params" data-i18n-locale="en">Advanced parameters</template>
  <template data-i18n-for="sec-params" data-i18n-locale="de">Erweiterte Parameter</template>
  <template data-i18n-for="p-temp" data-i18n-locale="en">Temperature</template>
  <template data-i18n-for="p-temp" data-i18n-locale="de">Temperatur</template>
  <template data-i18n-for="p-topp" data-i18n-locale="en">Top P</template>
  <template data-i18n-for="p-topp" data-i18n-locale="de">Top P</template>
  <template data-i18n-for="p-topk" data-i18n-locale="en">Top K</template>
  <template data-i18n-for="p-topk" data-i18n-locale="de">Top K</template>
  <template data-i18n-for="p-rep" data-i18n-locale="en">Repetition penalty</template>
  <template data-i18n-for="p-rep" data-i18n-locale="de">Wiederholungsstrafe</template>
  <template data-i18n-for="p-pres" data-i18n-locale="en">Presence penalty</template>
  <template data-i18n-for="p-pres" data-i18n-locale="de">Präsenzstrafe</template>
  <template data-i18n-for="p-max" data-i18n-locale="en">Max tokens</template>
  <template data-i18n-for="p-max" data-i18n-locale="de">Maximale Tokens</template>
  <template data-i18n-for="p-think" data-i18n-locale="en">Think before answering</template>
  <template data-i18n-for="p-think" data-i18n-locale="de">Vor der Antwort nachdenken</template>
  <template data-i18n-for="reset" data-i18n-locale="en">Reset to defaults</template>
  <template data-i18n-for="reset" data-i18n-locale="de">Auf Standard zurücksetzen</template>
  <template data-i18n-for="settings-title" data-i18n-locale="en">Settings</template>
  <template data-i18n-for="settings-title" data-i18n-locale="de">Einstellungen</template>
  <template data-i18n-for="settings-desc" data-i18n-locale="en">Language, appearance and how sending works.</template>
  <template data-i18n-for="settings-desc" data-i18n-locale="de"
    >Sprache, Darstellung und wie Senden funktioniert.</template
  >
  <template data-i18n-for="set-lang" data-i18n-locale="en">Language</template>
  <template data-i18n-for="set-lang" data-i18n-locale="de">Sprache</template>
  <template data-i18n-for="set-lang-d" data-i18n-locale="en">Menus, labels and buttons</template>
  <template data-i18n-for="set-lang-d" data-i18n-locale="de">Menüs, Beschriftungen und Schaltflächen</template>
  <template data-i18n-for="set-dark" data-i18n-locale="en">Dark mode</template>
  <template data-i18n-for="set-dark" data-i18n-locale="de">Dunkelmodus</template>
  <template data-i18n-for="set-dark-d" data-i18n-locale="en">Easier on the eyes at night</template>
  <template data-i18n-for="set-dark-d" data-i18n-locale="de">Schont nachts die Augen</template>
  <template data-i18n-for="set-enter" data-i18n-locale="en">Enter sends</template>
  <template data-i18n-for="set-enter" data-i18n-locale="de">Enter sendet</template>
  <template data-i18n-for="set-enter-d" data-i18n-locale="en">Shift+Enter starts a new line</template>
  <template data-i18n-for="set-enter-d" data-i18n-locale="de">Umschalt+Enter beginnt eine neue Zeile</template>
  <template data-i18n-for="set-clear" data-i18n-locale="en">Delete all chats</template>
  <template data-i18n-for="set-clear" data-i18n-locale="de">Alle Chats löschen</template>
  <template data-i18n-for="set-clear-d" data-i18n-locale="en">Pinned chats too - this cannot be undone</template>
  <template data-i18n-for="set-clear-d" data-i18n-locale="de"
    >Auch angeheftete - das lässt sich nicht rückgängig machen</template
  >
  <template data-i18n-for="set-clear-btn" data-i18n-locale="en">Delete all</template>
  <template data-i18n-for="set-clear-btn" data-i18n-locale="de">Alle löschen</template>
  <template data-i18n-for="recording" data-i18n-locale="en">Recording</template>
  <template data-i18n-for="recording" data-i18n-locale="de">Aufnahme</template>
  <template data-i18n-for="download" data-i18n-locale="en">Download</template>
  <template data-i18n-for="download" data-i18n-locale="de">Herunterladen</template>
  <template data-i18n-for="close" data-i18n-locale="en">Close</template>
  <template data-i18n-for="close" data-i18n-locale="de">Schließen</template>
  <template data-i18n-for="done" data-i18n-locale="en">Done</template>
  <template data-i18n-for="done" data-i18n-locale="de">Fertig</template>
  <template data-i18n-for="cancel" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="cancel" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="delete" data-i18n-locale="en">Delete</template>
  <template data-i18n-for="delete" data-i18n-locale="de">Löschen</template>
  <template data-i18n-for="auth-title" data-i18n-locale="en">Sign in to Lumen</template>
  <template data-i18n-for="auth-title" data-i18n-locale="de">Bei Lumen anmelden</template>
  <template data-i18n-for="auth-desc" data-i18n-locale="en"
    >Chat with any OpenAI-compatible model, answers streamed as they are written.</template
  >
  <template data-i18n-for="auth-desc" data-i18n-locale="de"
    >Chatte mit jedem OpenAI-kompatiblen Modell, Antworten erscheinen, während sie entstehen.</template
  >
  <template data-i18n-for="auth-error" data-i18n-locale="en">Invalid email or password</template>
  <template data-i18n-for="auth-error" data-i18n-locale="de">E-Mail oder Passwort ist falsch</template>
  <template data-i18n-for="auth-error-d" data-i18n-locale="en">Use the demo account below.</template>
  <template data-i18n-for="auth-error-d" data-i18n-locale="de">Nimm das Demo-Konto unten.</template>
  <template data-i18n-for="email" data-i18n-locale="en">Email</template>
  <template data-i18n-for="email" data-i18n-locale="de">E-Mail</template>
  <template data-i18n-for="password" data-i18n-locale="en">Password</template>
  <template data-i18n-for="password" data-i18n-locale="de">Passwort</template>
  <template data-i18n-for="sign-in" data-i18n-locale="en">Sign in</template>
  <template data-i18n-for="sign-in" data-i18n-locale="de">Anmelden</template>
  <template data-i18n-for="demo-account" data-i18n-locale="en">Demo account:</template>
  <template data-i18n-for="demo-account" data-i18n-locale="de">Demo-Konto:</template>
</div>
<script type="module">
  // Lumen: routing (defuss-dom-router), translation (defuss-i18n), Markdown (marked) - pinned builds
  import { createRouter } from 'https://cdn.jsdelivr.net/npm/defuss-dom-router@0.1.1/dist/index.js';
  import { createDomI18n, createI18n } from 'https://cdn.jsdelivr.net/npm/defuss-i18n@0.2.0/dist/core.js';
  const MARKED_URL = 'https://cdn.jsdelivr.net/npm/marked@18.1.0/lib/marked.esm.js';

  // df$ comes with the component bundle - a full-screen page loads it after this module
  addEventListener('DOMContentLoaded', async () => {
    const $ = df$;
    const app = $('[data-ac]').get(0);
    const nav = $('#ac-nav').get(0);
    const controls = $('#ac-controls').get(0);
    const chat = $('#ac-session').get(0);
    const content = $(chat).find('.session-content').get(0);
    const composer = $('[data-ac-composer]').get(0);
    const input = $(composer).find('.textarea').get(0);
    const sendBtn = $('[data-ac-send]').get(0);
    const settingsForm = $('[data-ac-settings]').get(0);
    const session = $.shadcn.session;

    // -- translation: the markup is the catalog; strings the script writes come from this table
    const locale = createI18n({ locale: 'en' });
    createDomI18n($).bind(app, locale);
    $.shadcn.languageSwitcher.bind($('[data-app-locale]').get(0), locale);
    const T = {
      en: {
        untitled: 'New chat',
        you: 'You',
        copy: 'Copy',
        copied: 'Copied to the clipboard',
        copyCode: 'Copy code',
        edit: 'Edit',
        save: 'Send',
        cancel: 'Cancel',
        regenerate: 'Regenerate',
        good: 'Good response',
        bad: 'Bad response',
        thanks: 'Thanks for the feedback',
        readAloud: 'Read aloud',
        info: 'Generation info',
        remove: 'Delete',
        more: 'Chat options',
        pin: 'Pin',
        unpin: 'Unpin',
        rename: 'Rename',
        thinking: 'Thinking...',
        thought: (s) => `Thought for ${s} second${s === 1 ? '' : 's'}`,
        stopped: 'Stopped',
        stop: 'Stop generating',
        send: 'Send message',
        failed: 'The model did not answer',
        delMsgTitle: 'Delete message?',
        delMsgDesc: 'This removes the message and every message after it. This cannot be undone.',
        delChatTitle: (t) => `Delete "${t}"?`,
        delChatDesc: 'The chat and all its messages are deleted. This cannot be undone.',
        delAllTitle: 'Delete all chats?',
        delAllDesc: 'Every chat, pinned ones too, is deleted. This cannot be undone.',
        deleted: 'Chat deleted',
        welcome: 'Welcome back, Ada',
        signedOut: 'Signed out',
        attached: (n) => `${n} file${n === 1 ? '' : 's'} attached`,
        play: 'Play',
        seek: 'Seek',
        mute: 'Mute',
        fullscreen: 'Full screen',
        openImage: (n) => `Open ${n}`,
        gone: 'Not kept after a reload',
        noMic: 'The microphone is not available here',
        voiceName: 'Voice message',
        dropLabel: 'Drop files to attach',
        image: 'Image',
        tokens: (n, r, s) => `${n} tokens · ${r} tokens/s · ${s} s`,
        fine: 'Lumen answers from a demo model in this page. Check important information.',
        fineApi: (u) => `Answers come from ${u}. Check important information.`,
        preparingCard: 'Preparing a card...',
        cardError: (e) => `The card's JSON does not parse: ${e}`,
        noted: (s) => `Thanks - noted: **${s}**.`,
      },
      de: {
        untitled: 'Neuer Chat',
        you: 'Du',
        copy: 'Kopieren',
        copied: 'In die Zwischenablage kopiert',
        copyCode: 'Code kopieren',
        edit: 'Bearbeiten',
        save: 'Senden',
        cancel: 'Abbrechen',
        regenerate: 'Neu erzeugen',
        good: 'Gute Antwort',
        bad: 'Schlechte Antwort',
        thanks: 'Danke für die Rückmeldung',
        readAloud: 'Vorlesen',
        info: 'Infos zur Antwort',
        remove: 'Löschen',
        more: 'Chat-Optionen',
        pin: 'Anheften',
        unpin: 'Lösen',
        rename: 'Umbenennen',
        thinking: 'Denkt nach...',
        thought: (s) => `${s} Sekunde${s === 1 ? '' : 'n'} nachgedacht`,
        stopped: 'Angehalten',
        stop: 'Antwort anhalten',
        send: 'Nachricht senden',
        failed: 'Das Modell hat nicht geantwortet',
        delMsgTitle: 'Nachricht löschen?',
        delMsgDesc: 'Die Nachricht und alle danach werden entfernt. Das lässt sich nicht rückgängig machen.',
        delChatTitle: (t) => `„${t}" löschen?`,
        delChatDesc: 'Der Chat und alle seine Nachrichten werden gelöscht. Das lässt sich nicht rückgängig machen.',
        delAllTitle: 'Alle Chats löschen?',
        delAllDesc: 'Jeder Chat, auch angeheftete, wird gelöscht. Das lässt sich nicht rückgängig machen.',
        deleted: 'Chat gelöscht',
        welcome: 'Willkommen zurück, Ada',
        signedOut: 'Abgemeldet',
        attached: (n) => `${n} Datei${n === 1 ? '' : 'en'} angehängt`,
        play: 'Abspielen',
        seek: 'Spulen',
        mute: 'Stumm',
        fullscreen: 'Vollbild',
        openImage: (n) => `${n} öffnen`,
        gone: 'Nach dem Neuladen nicht mehr da',
        noMic: 'Das Mikrofon ist hier nicht verfügbar',
        voiceName: 'Sprachnachricht',
        dropLabel: 'Dateien zum Anhängen ablegen',
        image: 'Bild',
        tokens: (n, r, s) => `${n} Tokens · ${r} Tokens/s · ${s} s`,
        fine: 'Lumen antwortet mit einem Demo-Modell in dieser Seite. Prüfe wichtige Informationen.',
        fineApi: (u) => `Die Antworten kommen von ${u}. Prüfe wichtige Informationen.`,
        preparingCard: 'Bereite eine Karte vor...',
        cardError: (e) => `Das JSON der Karte lässt sich nicht lesen: ${e}`,
        noted: (s) => `Danke - notiert: **${s}**.`,
      },
    };
    const lang = () => (app.getAttribute('lang') || 'en').slice(0, 2);
    const tr = (k, ...a) => {
      const v = (T[lang()] || T.en)[k] ?? T.en[k];
      return typeof v === 'function' ? v(...a) : v;
    };
    const esc = (s) =>
      String(s).replace(
        /[&<>"']/g,
        (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
      );
    // toasts at the top: at the bottom they would cover the send / stop button
    df$.shadcn.toast.configure({ position: 'top-center' });
    const toast = (title) => df$.shadcn.toast.show({ title });

    // inline icons for the markup the script writes (Lucide, ISC)
    const svg = (d) =>
      `<svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`;
    const ICON = {
      copy: svg(
        '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
      ),
      check: svg('<path d="M20 6 9 17l-5-5"/>'),
      edit: svg(
        '<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',
      ),
      regenerate: svg('<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'),
      good: svg(
        '<path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"/>',
      ),
      bad: svg(
        '<path d="M17 14V2"/><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"/>',
      ),
      read: svg(
        '<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/>',
      ),
      info: svg('<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>'),
      remove: svg(
        '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
      ),
      more: svg('<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>'),
      pin: svg(
        '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>',
      ),
      chat: svg('<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>'),
      spark: svg(
        '<path d="M12 3v4M12 17v4M3 12h4M17 12h4M6.3 6.3l2.5 2.5M15.2 15.2l2.5 2.5M6.3 17.7l2.5-2.5M15.2 8.8l2.5-2.5"/>',
      ),
      audio: svg('<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>'),
      video: svg(
        '<path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/>',
      ),
      download: svg(
        '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
      ),
      play: svg('<path d="M6 3 20 12 6 21Z"/>'),
      pause: svg('<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>'),
      volume: svg(
        '<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/>',
      ),
      muted: svg(
        '<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="m22 9-6 6"/><path d="m16 9 6 6"/>',
      ),
      maximize: svg(
        '<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>',
      ),
      minimize: svg(
        '<path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/>',
      ),
      file: svg(
        '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
      ),
      spinner:
        '<svg class="spinner" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',
    };

    // -- models: four demo models answer in the page; "api" is the OpenAI-compatible connection
    const MODELS = {
      'lumen-8b': { name: 'Lumen 8B', pace: 14 },
      'lumen-70b': { name: 'Lumen 70B', pace: 30 },
      'lumen-coder': { name: 'Lumen Coder 14B', pace: 18 },
      echo: { name: 'Echo', pace: 8 },
    };

    // -- state: chats and settings in stores (localStorage on a page, memory in a docs card)
    const DEFAULTS = {
      model: 'lumen-8b',
      connection: 'demo',
      baseUrl: 'http://localhost:11434/v1',
      apiKey: '',
      apiModel: 'llama3.2',
      systemPrompt: 'You are a helpful assistant.',
      temperature: 0.7,
      topP: 0.9,
      topK: 40,
      repetitionPenalty: 1.1,
      presencePenalty: 0,
      maxTokens: 2048,
      enableThinking: false,
      enterSends: true,
      componentTool: true,
    };
    const DAY = 86400000;
    const now = Date.now();
    const msg = (role, content, at, extra = {}) => ({
      id: 'm' + Math.round(at).toString(36) + role[0],
      role,
      content,
      at,
      ...extra,
    });
    // -- Chat Components: Component Schema documents the demo model answers with (and the examples use)
    const FENCE = df$.shadcn.chatComponents.fence;
    const fenceOf = (spec) => '```' + FENCE + '\n' + JSON.stringify(spec, null, 1) + '\n```';
    const CARDS = {
      deploy: {
        version: 1,
        id: 'deploy',
        title: 'Confirm the release plan',
        description: 'Release 2.4 tonight at 22:00 - untick a step to leave it out.',
        body: [
          {
            type: 'plan',
            name: 'steps',
            label: 'Steps',
            steps: [
              { id: 'backup', title: 'Back up the database', description: 'A snapshot, kept 30 days' },
              { id: 'migrate', title: 'Run the migrations', description: 'About 4 minutes read-only' },
              { id: 'canary', title: 'Canary to 5 % of traffic' },
              { id: 'all', title: 'Everyone after an hour' },
            ],
          },
        ],
        actions: [
          { id: 'confirm', label: 'Confirm', submit: true },
          { id: 'later', label: 'Not tonight', variant: 'outline', cancel: true },
        ],
      },
      budget: {
        version: 1,
        id: 'budget',
        title: 'Budget and start',
        body: [
          {
            type: 'currency',
            name: 'budget',
            label: 'Budget',
            currency: 'EUR',
            locale: 'de-DE',
            required: true,
            max: 100000,
          },
          { type: 'number', name: 'weeks', label: 'Weeks', min: 1, max: 52, default: 6, unit: 'weeks' },
          {
            type: 'radio',
            name: 'start',
            label: 'Start',
            required: true,
            options: [
              { value: 'now', label: 'Right away' },
              { value: 'q1', label: 'Next quarter' },
            ],
            other: 'Another time',
          },
        ],
        actions: [{ id: 'confirm', label: 'Confirm', submit: true }],
      },
      booking: {
        version: 1,
        id: 'booking',
        title: 'A table at Oktav',
        body: [
          { type: 'date', name: 'day', label: 'Day', required: true },
          { type: 'input', name: 'time', label: 'Time', inputType: 'time', required: true, default: '19:30' },
          { type: 'number', name: 'guests', label: 'Guests', min: 1, max: 12, default: 2 },
          { type: 'select', name: 'area', label: 'Seating', options: ['Inside', 'Terrace', 'At the bar'] },
        ],
        actions: [
          { id: 'book', label: 'Book', submit: true },
          { id: 'call', label: 'I would rather call', variant: 'outline', reply: 'Please give me the phone number.' },
        ],
      },
      brief: {
        version: 1,
        id: 'brief',
        title: 'Project brief',
        body: [
          {
            type: 'questionnaire',
            title: 'Project brief',
            steps: [
              {
                id: 'kind',
                title: 'What are we building?',
                fields: [
                  {
                    type: 'radio',
                    name: 'kind',
                    label: 'Kind',
                    required: true,
                    options: [
                      { value: 'site', label: 'A website' },
                      { value: 'app', label: 'An app', goto: 'platforms' },
                    ],
                    other: 'Something else',
                  },
                ],
              },
              {
                id: 'pages',
                title: 'About how many pages?',
                next: 'budget',
                fields: [{ type: 'number', name: 'pages', label: 'Pages', min: 1, required: true }],
              },
              {
                id: 'platforms',
                title: 'Which platforms?',
                fields: [
                  { type: 'checkbox', name: 'platforms', label: 'Platforms', options: ['iOS', 'Android', 'Web'] },
                ],
              },
              {
                id: 'budget',
                title: 'Your budget',
                fields: [
                  {
                    type: 'currency',
                    name: 'budget',
                    label: 'Budget',
                    currency: 'USD',
                    locale: 'en-US',
                    required: true,
                  },
                ],
              },
            ],
          },
        ],
        actions: [{ id: 'send', label: 'Send the brief', submit: true }],
      },
      feedback: {
        version: 1,
        id: 'feedback',
        title: 'How did I do?',
        body: [
          { type: 'rating', name: 'score', label: 'Your rating', required: true },
          {
            type: 'checkbox',
            name: 'helped',
            label: 'What helped?',
            options: ['Fast', 'Clear', 'Friendly'],
            other: 'Something else',
          },
          { type: 'textarea', name: 'comment', label: 'Comment', lines: 2 },
        ],
        actions: [{ id: 'send', label: 'Send', submit: true }],
      },
      plans: {
        version: 1,
        id: 'plans',
        body: [{ type: 'text', text: 'Which plan suits your team?' }],
        actions: [
          { id: 'starter', label: 'Starter', reply: 'The Starter plan' },
          { id: 'team', label: 'Team', reply: 'The Team plan', variant: 'secondary' },
          { id: 'compare', label: 'Compare them', reply: 'Compare the plans for me', variant: 'outline' },
        ],
      },
      request: {
        version: 1,
        id: 'request',
        title: 'Equipment request',
        body: [
          { type: 'input', name: 'email', label: 'Email', inputType: 'email', required: true },
          { type: 'select', name: 'device', label: 'Device', options: ['Laptop', 'Monitor', 'Phone'], required: true },
          { type: 'currency', name: 'budget', label: 'Budget', currency: 'EUR', locale: 'de-DE' },
          { type: 'checkbox', name: 'extras', label: 'Extras', options: ['Dock', 'Keyboard', 'Mouse'] },
          { type: 'switch', name: 'urgent', label: 'Urgent' },
          { type: 'slider', name: 'share', label: 'Team share', min: 0, max: 100, step: 10, default: 50, unit: '%' },
          { type: 'date', name: 'needed', label: 'Needed by' },
        ],
        actions: [{ id: 'send', label: 'Send request', submit: true }],
      },
    };
    // what the demo model says when a card's answer comes back
    const AFTER = {
      deploy: (a) =>
        `Scheduled for 22:00: ${(a.answers.steps || []).length} steps. I will post here when the canary is live.`,
      budget: () => 'Good - I will draft a plan within that budget and send it tomorrow.',
      booking: (a) =>
        a.reply ? 'Call us on +49 30 1234 5678 - between 11:00 and 22:00.' : 'Booked - a confirmation is on its way.',
      brief: () => 'Thanks for the brief. A designer and a developer will look at it and reply within two days.',
      feedback: () => 'Thank you - that helps us get better.',
      plans: (a) =>
        a.action === 'compare'
          ? 'Starter: one workspace, 5 GB. Team: shared projects, 100 GB, admin roles.'
          : 'Done - switched. You can change it any time.',
      request: () => 'Your request is with purchasing - you hear back within three working days.',
    };
    // -- Chat Scripts: conversations without a language model (the Examples group runs them)
    const SCRIPTS = {
      support: {
        bot: 'Ada (script)',
        script: {
          version: 1,
          start: 'hello',
          fallback: 'Pick one of the buttons above - or tell me in a few words.',
          nodes: {
            hello: {
              say: [
                'Hi, I am Ada from Northwind support - a scripted bot, no language model.',
                'What can I help you with?',
              ],
              ask: {
                version: 1,
                id: 'topic',
                actions: [
                  { id: 'billing', label: 'An invoice', reply: 'A question about an invoice' },
                  { id: 'refund', label: 'A refund', reply: 'I would like a refund', variant: 'secondary' },
                  { id: 'other', label: 'Something else', reply: 'Something else', variant: 'outline' },
                ],
              },
              match: [
                { pattern: 'refund|money back', goto: 'refund' },
                { pattern: 'invoice|bill', goto: 'invoice' },
              ],
              branches: [
                { when: { field: 'topic', value: 'billing' }, goto: 'invoice' },
                { when: { field: 'topic', value: 'refund' }, goto: 'refund' },
              ],
              next: 'other',
            },
            invoice: { say: 'Sure. What is the invoice number?', input: 'invoice', next: 'invoiceDone' },
            invoiceDone: {
              say: 'Thanks - invoice **{{invoice}}** is with our billing team. You get an answer by email today.',
              next: 'again',
            },
            refund: {
              say: 'I can start a refund right here.',
              ask: {
                version: 1,
                id: 'refundCard',
                title: 'Refund',
                body: [
                  { type: 'input', name: 'order', label: 'Order number', required: true, placeholder: 'NW-1234' },
                  {
                    type: 'currency',
                    name: 'amount',
                    label: 'Amount',
                    currency: 'EUR',
                    locale: 'de-DE',
                    required: true,
                  },
                  {
                    type: 'select',
                    name: 'reason',
                    label: 'Reason',
                    options: ['Damaged', 'Wrong item', 'Changed my mind'],
                  },
                ],
                actions: [{ id: 'request', label: 'Request refund', submit: true }],
              },
              branches: [{ when: { field: 'amount', op: 'gte', value: 100 }, goto: 'manager' }],
              next: 'refundDone',
            },
            manager: {
              say: 'Refunds of 100 € or more need a manager - Jonas emails you about order {{order}} within a day.',
              next: 'again',
            },
            refundDone: {
              say: 'Done: the refund for order {{order}} is on its way (3 to 5 working days).',
              next: 'again',
            },
            other: { say: 'Tell me in a sentence - I will pass it on.', input: 'issue', next: 'otherDone' },
            otherDone: { say: 'Got it. A colleague picks this up and replies by email.', next: 'again' },
            again: {
              say: 'Anything else?',
              ask: { version: 1, id: 'again', actions: [{ id: 'yes', label: 'Start over', reply: 'Start over' }] },
              next: 'hello',
            },
          },
        },
      },
      pizza: {
        bot: 'Forno (script)',
        script: {
          version: 1,
          start: 'size',
          nodes: {
            size: {
              say: 'Welcome to Forno! What size?',
              ask: {
                version: 1,
                id: 'sizeCard',
                body: [
                  {
                    type: 'radio',
                    name: 'size',
                    label: 'Size',
                    required: true,
                    options: [
                      { value: 'small', label: 'Small', description: '26 cm - 8 €' },
                      { value: 'large', label: 'Large', description: '32 cm - 11 €' },
                    ],
                  },
                ],
                actions: [{ id: 'next', label: 'Next', submit: true }],
              },
              next: 'toppings',
            },
            toppings: {
              say: 'Toppings? Pick as many as you like.',
              ask: {
                version: 1,
                id: 'toppingsCard',
                body: [
                  {
                    type: 'checkbox',
                    name: 'toppings',
                    label: 'Toppings',
                    options: ['Basil', 'Mushrooms', 'Olives', 'Chili'],
                    other: 'Something else',
                  },
                  { type: 'number', name: 'count', label: 'How many pizzas?', min: 1, max: 10, default: 1 },
                ],
                actions: [{ id: 'next', label: 'Next', submit: true }],
              },
              next: 'confirm',
            },
            confirm: {
              say: '{{count}} × {{size}} with {{toppings}}. Shall I send it to the kitchen?',
              ask: {
                version: 1,
                id: 'confirmCard',
                actions: [
                  { id: 'yes', label: 'Order', reply: 'Order it' },
                  { id: 'change', label: 'Change', reply: 'Let me change it', variant: 'outline' },
                ],
              },
              branches: [{ when: { field: 'confirmCard', value: 'change' }, goto: 'size' }],
              next: 'done',
            },
            done: {
              say: 'In the oven - about 20 minutes. Buon appetito!',
              ask: { version: 1, id: 'again', actions: [{ id: 'again', label: 'Order again', reply: 'Order again' }] },
              next: 'size',
            },
          },
        },
      },
    };
    const example = (id, title, at, messages, extra = {}) => ({
      id,
      title,
      example: true,
      pinned: false,
      model: 'lumen-8b',
      at,
      // an answer names the model that wrote it
      messages: messages.map((m) => (m.role === 'assistant' ? { model: 'lumen-8b', ...m } : m)),
      ...extra,
    });
    const examples = () => [
      example('ex-deploy', 'Confirm a release plan', now - 1000, [
        msg('user', 'Deploy release 2.4 tonight', now - 1000),
        msg(
          'assistant',
          'Here is the plan - confirm it and I will schedule it:\n\n' + fenceOf(CARDS.deploy),
          now - 990,
          { forms: { 0: { action: 'confirm', answers: { steps: ['backup', 'migrate', 'canary'] } } } },
        ),
        msg('user', 'Steps: Back up the database, Run the migrations, Canary to 5 % of traffic', now - 980, {
          answer: { id: 'deploy', action: 'confirm' },
        }),
        msg('assistant', 'Scheduled for 22:00: 3 steps. I will post here when the canary is live.', now - 970),
      ]),
      example('ex-budget', 'Budget for the redesign', now - 2000, [
        msg('user', 'Can you start the redesign?', now - 2000),
        msg(
          'assistant',
          'Yes. Two things first - the budget and when to start:\n\n' + fenceOf(CARDS.budget),
          now - 1990,
        ),
      ]),
      example('ex-booking', 'Book a table', now - 3000, [
        msg('user', 'Book a table for Friday', now - 3000),
        msg('assistant', fenceOf(CARDS.booking), now - 2990),
      ]),
      example('ex-brief', 'A project brief, step by step', now - 4000, [
        msg('user', 'I need a quote for a project', now - 4000),
        msg('assistant', 'Three quick questions, one at a time:\n\n' + fenceOf(CARDS.brief), now - 3990),
      ]),
      example('ex-plans', 'Pick a plan (quick replies)', now - 5000, [
        msg('user', 'Which plan should we take?', now - 5000),
        msg('assistant', fenceOf(CARDS.plans), now - 4990),
      ]),
      example('ex-feedback', 'Feedback, answered', now - 6000, [
        msg('user', 'Thanks, that fixed it!', now - 6000),
        msg('assistant', 'Glad to hear it. Would you rate this chat?\n\n' + fenceOf(CARDS.feedback), now - 5990, {
          forms: { 0: { action: 'send', answers: { score: 5, helped: ['Fast', 'Clear'], comment: 'Spot on.' } } },
        }),
        msg('user', 'Your rating: 5 of 5; What helped?: Fast, Clear; Comment: Spot on.', now - 5980, {
          answer: { id: 'feedback', action: 'send' },
        }),
        msg('assistant', 'Thank you - that helps us get better.', now - 5970),
      ]),
      example('ex-support', 'Support bot (Chat Script)', now - 7000, [], { script: 'support' }),
      example('ex-pizza', 'Pizza order (Chat Script)', now - 8000, [], { script: 'pizza' }),
    ];
    const seed = () => [
      ...examples(),
      {
        id: 'welcome',
        title: 'What can Lumen do?',
        pinned: true,
        model: 'lumen-8b',
        at: now - 2 * DAY,
        messages: [
          msg('user', 'What can Lumen do?', now - 2 * DAY),
          msg(
            'assistant',
            'I answer questions, write and explain code, draft text and compare options - **streamed as I write**.\n\n- Pick a **model** at the top.\n- Open **Controls** for the system prompt, temperature and other sampling settings - or connect any **OpenAI-compatible API**.\n- Hover an answer to copy, regenerate, read aloud or rate it; hover your message to edit it.',
            now - 2 * DAY + 4000,
            { model: 'lumen-8b', stats: { tokens: 74, seconds: 1.1 } },
          ),
        ],
      },
      {
        id: 'sql',
        title: 'Window functions in SQL',
        pinned: false,
        model: 'lumen-coder',
        at: now - 3 * 3600000,
        messages: [
          msg('user', 'How do I number rows per customer in SQL?', now - 3 * 3600000),
          msg(
            'assistant',
            "Use the window function `row_number()` with a partition:\n\n```sql\nselect customer_id, order_id,\n       row_number() over (partition by customer_id order by ordered_at) as nth\nfrom orders;\n```\n\nEach customer's orders count up from 1 in the order they were placed.",
            now - 3 * 3600000 + 5000,
            { model: 'lumen-coder', stats: { tokens: 61, seconds: 1.3 } },
          ),
        ],
      },
      {
        id: 'haiku',
        title: 'A haiku about autumn rain',
        pinned: false,
        model: 'lumen-70b',
        at: now - DAY - 3600000,
        messages: [
          msg('user', 'Write a haiku about autumn rain', now - DAY - 3600000),
          msg(
            'assistant',
            'Grey roofs drink the rain\na red leaf rides the gutter\nhome before the dark',
            now - DAY - 3600000 + 3000,
            { model: 'lumen-70b', stats: { tokens: 18, seconds: 0.9 } },
          ),
        ],
      },
      {
        id: 'sleep',
        title: 'Sleep tips for night shifts',
        pinned: false,
        model: 'lumen-8b',
        at: now - 4 * DAY,
        messages: [
          msg('user', 'Any sleep tips for night shifts?', now - 4 * DAY),
          msg(
            'assistant',
            '1. Keep the same sleep window, also on days off where you can.\n2. Make the bedroom **dark and cool** - blackout curtains help most.\n3. Stop caffeine six hours before you plan to sleep.\n4. Eat a light meal before sleeping, not a heavy one.',
            now - 4 * DAY + 4000,
            { model: 'lumen-8b', stats: { tokens: 58, seconds: 1.2 } },
          ),
        ],
      },
      {
        id: 'regex',
        title: 'Regex for dates',
        pinned: false,
        model: 'lumen-coder',
        at: now - 21 * DAY,
        messages: [
          msg('user', 'A regex for ISO dates?', now - 21 * DAY),
          msg(
            'assistant',
            '`^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$` matches `2026-11-20` - it checks the ranges, not the length of each month.',
            now - 21 * DAY + 3000,
            { model: 'lumen-coder', stats: { tokens: 40, seconds: 0.8 } },
          ),
        ],
      },
    ];
    const chats = $.store.persisted('lumen:chats', seed(), { validate: (v) => Array.isArray(v) });
    // the seed reaches only an empty store: chats kept from an earlier visit get the examples once per
    // EXAMPLES version (VERIFIED: a browser with older chats never showed the Examples group); one deleted stays deleted
    const EXAMPLES = 1;
    const examplesSeen = $.store.persisted('lumen:examples', 0, { validate: (v) => Number.isInteger(v) });
    if (examplesSeen.value < EXAMPLES) {
      const have = new Set((Array.isArray(chats.value) ? chats.value : []).map((c) => c.id));
      const missing = examples().filter((c) => !have.has(c.id));
      if (missing.length) chats.set([...missing, ...(Array.isArray(chats.value) ? chats.value : [])]);
      examplesSeen.set(EXAMPLES);
    }
    const prefs = $.store.persisted('lumen:settings', DEFAULTS, {
      validate: (v) => !!v && typeof v === 'object' && !Array.isArray(v),
    });
    const conf = () => ({ ...DEFAULTS, ...prefs.value });
    const setConf = (patch) => prefs.set({ ...conf(), ...patch });
    const list = () => (Array.isArray(chats.value) ? chats.value : []);
    const save = (next) => chats.set(next);
    const find = (id) => list().find((c) => c.id === id);
    const update = (id, fn) => save(list().map((c) => (c.id === id ? fn(structuredClone(c)) : c)));

    if (list().some((c) => c.messages.some((m) => m.streaming)))
      save(
        list().map((c) => ({
          ...c,
          messages: c.messages.map((m) => (m.streaming ? { ...m, streaming: false, stopped: true } : m)),
        })),
      );

    let current = null; // the shown chat id, null = a new chat
    let signedIn = true;
    let run = null; // the running generation: { chatId, messageId, abort }
    let attachments = [];

    // -- Markdown: marked, loaded once; its HTML is cleaned before it enters the page (answers may come from any API)
    let markedP = null;
    const loadMarked = () => (markedP ??= import(MARKED_URL).then((m) => m.marked).catch(() => null));
    const ALLOWED = new Set([
      'P',
      'BR',
      'HR',
      'STRONG',
      'EM',
      'B',
      'I',
      'DEL',
      'S',
      'CODE',
      'PRE',
      'BLOCKQUOTE',
      'UL',
      'OL',
      'LI',
      'H1',
      'H2',
      'H3',
      'H4',
      'H5',
      'H6',
      'A',
      'TABLE',
      'THEAD',
      'TBODY',
      'TR',
      'TH',
      'TD',
      'SPAN',
      'SUP',
      'SUB',
      'KBD',
      'INPUT',
    ]);
    const clean = (html) => {
      // cleaned in an inert document (nothing loads or runs there), then moved into this one
      const parsed = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/html').body.firstElementChild;
      for (const el of [...parsed.querySelectorAll('*')]) {
        if (!ALLOWED.has(el.tagName)) {
          el.replaceWith(
            ...(['SCRIPT', 'STYLE', 'IFRAME', 'OBJECT', 'EMBED', 'TEMPLATE'].includes(el.tagName) ? [] : el.childNodes),
          );
          continue;
        }
        for (const a of [...el.attributes]) {
          const keep =
            (el.tagName === 'A' && a.name === 'href' && /^(https?:|mailto:|#)/i.test(a.value.trim())) ||
            (el.tagName === 'CODE' && a.name === 'class' && /^language-[\w-]+$/.test(a.value)) ||
            (el.tagName === 'INPUT' && ['type', 'checked', 'disabled'].includes(a.name)) ||
            (/^T[HD]$/.test(el.tagName) && a.name === 'align');
          if (!keep) el.removeAttribute(a.name);
        }
        if (el.tagName === 'INPUT' && el.getAttribute('type') !== 'checkbox') el.remove();
        if (el.tagName === 'A') {
          el.setAttribute('target', '_blank');
          el.setAttribute('rel', 'noopener noreferrer');
          el.className = 'link';
        }
      }
      const root = document.createElement('div');
      root.append(...parsed.childNodes);
      // tables become the Table component, code blocks Code mockups with a copy button
      for (const t of $(root).find('table').toArray()) {
        t.className = 'table';
        $(t).find('tr').attr('class', 'table-row');
        $(t).find('th').attr('class', 'table-head');
        $(t).find('td').attr('class', 'table-cell');
        const box = document.createElement('div');
        box.className = 'table-container';
        t.replaceWith(box);
        box.append(t);
      }
      for (const pre of $(root).find('pre').toArray()) {
        const code = $(pre).find('code').get(0);
        const language = (code?.className.match(/language-([\w-]+)/) || [])[1] || 'text';
        const wrap = document.createElement('div');
        wrap.className = 'ac-code';
        $(wrap).html(
          `<div class="ac-code-head"><span>${esc(language)}</span><button class="btn" data-variant="ghost" data-size="icon-xs" type="button" data-ac-copy-code aria-label="${esc(tr('copyCode'))}">${ICON.copy}</button></div><div class="mockup-code" data-chrome="none"></div>`,
        );
        const box = $(wrap).find('.mockup-code').get(0);
        for (const line of (code?.textContent ?? pre.textContent).replace(/\n$/, '').split('\n')) {
          const p = document.createElement('pre');
          const c = document.createElement('code');
          c.textContent = line;
          p.append(c);
          box.append(p);
        }
        pre.replaceWith(wrap);
      }
      return $(root).html();
    };
    const plain = (text) => `<p>${esc(text).replace(/\n/g, '<br>')}</p>`;
    const toHtml = (md, marked) => (marked ? clean(marked.parse(md, { gfm: true, breaks: true })) : plain(md));

    // -- markup of one turn
    const time = (at) => new Intl.DateTimeFormat(lang(), { hour: '2-digit', minute: '2-digit' }).format(at);
    const footBtn = (act, icon, label, extra = '') =>
      `<button class="btn" data-variant="ghost" data-size="icon-xs" type="button" data-ac-msg="${act}" aria-label="${esc(label)}" title="${esc(label)}"${extra}>${icon}</button>`;
    const userTurn = (m) =>
      `<div class="message ac-turn" data-align="end" data-avatar="none"><div class="message-content">${
        m.files?.length ? `<div class="ac-files">${m.files.map(fileView).join('')}</div>` : ''
      }${
        shownText(m)
          ? `<div class="bubble" data-variant="secondary"><div class="bubble-content">${esc(shownText(m)).replace(/\n/g, '<br>')}</div></div>`
          : ''
      }${m.script ? '' : `<div class="message-footer" data-reveal="hover">${footBtn('edit', ICON.edit, tr('edit'))}${footBtn('copy', ICON.copy, tr('copy'))}${footBtn('delete', ICON.remove, tr('remove'))}</div>`}</div></div>`;
    const mdBubble = (md, marked, extra = '') =>
      md.trim() || extra
        ? `<div class="bubble" data-variant="ghost"><div class="bubble-content ac-md">${md.trim() ? toHtml(md, marked) : ''}${extra}</div></div>`
        : '';
    // an answer's Markdown and its cards: text in ghost bubbles, each closed fence a Chat Components element
    const answerBody = (m, marked) => {
      const cc = df$.shadcn.chatComponents;
      const text = m.content || '';
      const parts = [];
      let at = 0;
      cc.fences(text).forEach((f, i) => {
        parts.push({ md: text.slice(at, f.start) });
        if (!f.closed)
          parts.push({
            html: `<div class="marker" role="status"><span class="marker-content" data-shimmer>${esc(tr('preparingCard'))}</span></div>`,
          });
        else if (!f.spec)
          parts.push({
            html: `<div class="alert" data-variant="destructive" role="alert"><div class="alert-content"><p class="alert-description">${esc(tr('cardError', f.error))}</p></div></div>`,
          });
        else parts.push({ html: cc.markup(f.spec, { id: `${m.id}-f${i}`, answers: m.forms?.[i] ?? null }) });
        at = f.end;
      });
      parts.push({ md: text.slice(at) });
      // "Stopped" ends the last text, as it ends a plain answer
      const stopped = m.stopped ? `<p class="ac-info">${esc(tr('stopped'))}</p>` : '';
      const last = parts.map((p) => 'md' in p && p.md.trim()).lastIndexOf(true);
      const out = parts
        .map((p, i) => ('html' in p ? p.html : mdBubble(p.md, marked, i === last ? stopped : '')))
        .join('');
      return (last < 0 ? mdBubble('', marked, stopped) : '') + out || mdBubble('', marked, ' ');
    };
    const thinkBlock = (m) =>
      m.thinking
        ? `<details class="ac-think"${m.streaming === 'think' ? ' open' : ''}><summary class="marker"><span class="marker-icon" aria-hidden="true">${ICON.spark}</span><span class="marker-content"${m.streaming === 'think' ? ' data-shimmer' : ''}>${esc(m.streaming === 'think' ? tr('thinking') : tr('thought', Math.max(1, Math.round(m.thinkSeconds || 1))))}</span></summary><div class="ac-think-body">${esc(m.thinking)}</div></details>`
        : '';
    const assistantTurn = (m, marked) => {
      const model = MODELS[m.model]?.name || m.modelName || m.model;
      const waiting = m.streaming && !m.content && m.streaming !== 'think';
      const error = m.error
        ? `<div class="alert" data-variant="destructive" role="alert"><div class="alert-content"><h5 class="alert-title">${esc(tr('failed'))}</h5><p class="alert-description">${esc(m.error)}</p></div></div>`
        : '';
      const footer =
        m.streaming || m.script
          ? ''
          : `<div class="message-footer" data-reveal="hover">${footBtn('copy', ICON.copy, tr('copy'))}${footBtn('read', ICON.read, tr('readAloud'))}${footBtn('info', ICON.info, tr('info'), ` aria-expanded="${m.showInfo ? 'true' : 'false'}"`)}${footBtn('good', ICON.good, tr('good'), ` aria-pressed="${m.rating === 'good'}"`)}${footBtn('bad', ICON.bad, tr('bad'), ` aria-pressed="${m.rating === 'bad'}"`)}${footBtn('regenerate', ICON.regenerate, tr('regenerate'))}</div>${
              m.showInfo && m.stats
                ? `<div class="ac-info" data-ac-info>${esc(model)} · ${esc(tr('tokens', m.stats.tokens, Math.round(m.stats.tokens / Math.max(m.stats.seconds, 0.05)), m.stats.seconds.toFixed(1)))}</div>`
                : ''
            }`;
      return `<div class="message ac-turn"><div class="message-avatar"><span class="avatar" data-size="sm"><span class="avatar-fallback ac-mark">${ICON.spark}</span></span></div><div class="message-content"><div class="message-header"><span class="message-name">${esc(model)}</span><time class="message-time" datetime="${new Date(m.at).toISOString()}">${time(m.at)}</time></div>${thinkBlock(m)}${
        waiting
          ? `<div class="marker" role="status"><span class="marker-content" data-shimmer>${esc(tr('thinking'))}</span></div>`
          : ''
      }${m.content || !m.streaming ? answerBody(m, marked) : ''}${error}${footer}</div></div>`;
    };
    const turn = (m, marked) => (m.role === 'user' ? userTurn(m) : assistantTurn(m, marked));

    // -- files: any kind attaches; images are kept (scaled to 1280px, WebP) with the chat, the rest for this visit
    const blobs = new Map(); // attachment id -> object URL
    const urlOf = (a) => a.url || blobs.get(a.id) || '';
    const kindOf = (file) =>
      file.type.startsWith('image/')
        ? 'image'
        : file.type.startsWith('audio/')
          ? 'audio'
          : file.type.startsWith('video/')
            ? 'video'
            : /^text\/|json|xml|csv|markdown|yaml|javascript/.test(file.type) ||
                /\.(txt|md|csv|json|ya?ml|js|ts|py|html|css|log)$/i.test(file.name)
              ? 'text'
              : 'file';
    const clock = (sec) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`;
    const bytes = (n) =>
      new Intl.NumberFormat(lang(), {
        style: 'unit',
        unit: n < 1e6 ? 'kilobyte' : 'megabyte',
        maximumFractionDigits: 1,
      }).format(n < 1e6 ? Math.max(1, n / 1e3) : n / 1e6);
    const hex = (r, g, b) => '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
    const readImage = async (file) => {
      const bmp = await createImageBitmap(file);
      const scale = Math.min(1, 1280 / Math.max(bmp.width, bmp.height));
      const canvas = document.createElement('canvas');
      canvas.width = Math.round(bmp.width * scale);
      canvas.height = Math.round(bmp.height * scale);
      canvas.getContext('2d').drawImage(bmp, 0, 0, canvas.width, canvas.height);
      // the average colour of the picture
      const dot = document.createElement('canvas');
      dot.width = dot.height = 16;
      const ctx = dot.getContext('2d', { willReadFrequently: true });
      ctx.imageSmoothingQuality = 'high';
      ctx.drawImage(canvas, 0, 0, 16, 16);
      const px = ctx.getImageData(0, 0, 16, 16).data;
      const sum = [0, 0, 0];
      for (let i = 0; i < px.length; i += 4) for (let c = 0; c < 3; c++) sum[c] += px[i + c];
      const [r, g, b] = sum.map((v) => Math.round(v / 256));
      return { url: canvas.toDataURL('image/webp', 0.85), width: bmp.width, height: bmp.height, color: hex(r, g, b) };
    };
    const readMedia = (url, kind) =>
      new Promise((resolve) => {
        const el = document.createElement(kind);
        el.preload = 'metadata';
        el.muted = true;
        const done = () =>
          resolve({
            duration: Number.isFinite(el.duration) ? el.duration : undefined,
            width: el.videoWidth || undefined,
            height: el.videoHeight || undefined,
          });
        el.addEventListener('loadedmetadata', done, { once: true });
        el.addEventListener('error', () => resolve({}), { once: true });
        setTimeout(done, 4000);
        el.src = url;
      });
    const addFiles = async (files, extra = {}) => {
      for (const file of files) {
        const a = {
          id: 'a' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
          name: file.name || tr('image'),
          type: file.type,
          size: file.size,
          kind: kindOf(file),
        };
        try {
          if (a.kind === 'image') Object.assign(a, await readImage(file));
          else {
            blobs.set(a.id, URL.createObjectURL(file));
            if (a.kind === 'text') a.text = (await file.text()).slice(0, 20000);
            if (a.kind === 'audio' || a.kind === 'video') Object.assign(a, await readMedia(blobs.get(a.id), a.kind));
          }
        } catch {
          // a picture the browser cannot decode is a plain file
          a.kind = 'file';
          blobs.set(a.id, URL.createObjectURL(file));
        }
        a.duration ??= extra.duration;
        // the store refuses a value holding undefined (the write fails, and every later one with it) - VERIFIED
        for (const k of Object.keys(a)) if (a[k] === undefined) delete a[k];
        attachments.push(a);
      }
      renderAttachments();
      if (files.length) toast(tr('attached', files.length));
    };
    const metaOf = (a) =>
      a.kind === 'image'
        ? `${a.width} × ${a.height}`
        : (a.kind === 'audio' || a.kind === 'video') && a.duration
          ? clock(a.duration)
          : bytes(a.size);
    const kindIcon = (a) => (a.kind === 'audio' ? ICON.audio : a.kind === 'video' ? ICON.video : ICON.file);
    // two icons per toggle: the player shows the one its aria-pressed asks for
    const ctl = (attr, act, label, a, b) =>
      `<button class="btn" data-variant="ghost" data-size="icon-sm" type="button" ${attr}="${act}" aria-pressed="false" aria-label="${esc(label)}">${a}${b}</button>`;
    const fileView = (a) => {
      const url = urlOf(a);
      const card = (href) =>
        `<${href ? `a href="${href}" download="${esc(a.name)}"` : 'div data-ac-gone'} class="message-attachment"><span class="message-attachment-icon" aria-hidden="true">${kindIcon(a)}</span><span class="message-attachment-body"><span class="message-attachment-name">${esc(a.name)}</span><span class="message-attachment-meta">${esc(href ? metaOf(a) : tr('gone'))}</span></span>${href ? ICON.download : ''}</${href ? 'a' : 'div'}>`;
      if (!url) return card('');
      if (a.kind === 'image')
        return `<div class="bubble" data-variant="secondary"><button type="button" class="bubble-content ac-image" data-media data-ac-preview="${a.id}" aria-label="${esc(tr('openImage', a.name))}"><img src="${url}" alt="${esc(a.name)}" width="${a.width}" height="${a.height}" /></button></div>`;
      const max = Math.max(1, Math.ceil(a.duration || 1));
      const seek = (attr) =>
        `<output class="${attr}-time" data-${attr}-output="time">0:00</output><input class="slider" data-size="sm" type="range" min="0" max="${max}" step="0.1" value="0" data-${attr}-action="seek" aria-label="${esc(tr('seek'))}" /><output class="${attr}-time" data-${attr}-output="duration">${clock(a.duration || 0)}</output>`;
      if (a.kind === 'video')
        return `<figure class="video" aria-label="${esc(a.name)}"><div class="video-frame"><video preload="metadata" playsinline src="${url}"></video></div><div class="video-controls">${ctl('data-video-action', 'toggle', tr('play'), ICON.play, ICON.pause)}${seek('video')}${ctl('data-video-action', 'mute', tr('mute'), ICON.volume, ICON.muted)}${ctl('data-video-action', 'fullscreen', tr('fullscreen'), ICON.maximize, ICON.minimize)}</div></figure>`;
      if (a.kind === 'audio')
        return `<div class="audio" role="group" aria-label="${esc(a.name)}"><audio preload="metadata" src="${url}"></audio>${ctl('data-audio-action', 'toggle', tr('play'), ICON.play, ICON.pause)}<div class="audio-body"><span class="audio-title">${esc(a.name)}</span><div class="audio-progress">${seek('audio')}</div></div>${ctl('data-audio-action', 'mute', tr('mute'), ICON.volume, ICON.muted)}</div>`;
      return card(url);
    };

    // -- the transcript: the whole chat on a switch, one row on a change
    const renderChat = async () => {
      const marked = await loadMarked();
      const c = current && find(current);
      const messages = c ? c.messages : [];
      chat.toggleAttribute('data-empty', !messages.length);
      // new rows, never a morph of the old ones: a morph would strip the players' runtime marks (data-init)
      $(content).html('');
      $(content).html(
        messages
          .map(
            (m) =>
              `<div class="session-item" data-message-id="${m.id}"${m.role === 'user' && !c?.script ? ' data-anchor' : ''}>${turn(m, marked)}</div>`,
          )
          .join(''),
      );
      $('[data-ac-model-name]').text(c?.script ? SCRIPTS[c.script].bot : modelName(c?.model || conf().model));
      if (c?.script) startScript(c);
      requestAnimationFrame(() => session.scrollToEnd(chat, { smooth: false }));
    };
    const renderMessage = async (chatId, messageId) => {
      if (chatId !== current) return;
      const marked = await loadMarked();
      const m = find(chatId)?.messages.find((x) => x.id === messageId);
      const row = $(content).find(`[data-message-id="${messageId}"]`).get(0);
      if (!m || !row) return;
      $(row).html(turn(m, marked));
    };
    const modelName = (id) => (id === 'api' ? conf().apiModel : MODELS[id]?.name || id);

    // -- the chat list: grouped by day, filtered by the search
    const groupOf = (c) => {
      if (c.example) return 'examples';
      if (c.pinned) return 'pinned';
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      const t = start.getTime();
      if (c.at >= t) return 'today';
      if (c.at >= t - DAY) return 'yesterday';
      if (c.at >= t - 7 * DAY) return 'week';
      return 'older';
    };
    const renderList = () => {
      const q = $('[data-ac-search]').val().trim().toLowerCase();
      const shown = list()
        .filter(
          (c) => !q || c.title.toLowerCase().includes(q) || c.messages.some((m) => m.content.toLowerCase().includes(q)),
        )
        .sort((a, b) => b.at - a.at);
      $('[data-ac-group]').each((_i, g) => {
        const key = g.dataset.acGroup;
        const rows = shown.filter((c) => groupOf(c) === key);
        g.hidden = !rows.length;
        $(g)
          .find('.sidebar-nav')
          .html(
            rows
              .map(
                (c) =>
                  `<div class="ac-chat" data-ac-chat="${c.id}"><a class="sidebar-link" href="#/c/${c.id}" data-router-link${c.id === current ? ' aria-current="page"' : ''}><span>${esc(c.title)}</span></a><button class="btn ac-chat-more" data-variant="ghost" data-size="icon-xs" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="ac-menu-${c.id}" data-dropdown-trigger="ac-menu-${c.id}" aria-label="${esc(tr('more'))}">${ICON.more}</button><div id="ac-menu-${c.id}" role="menu" popover class="dropdown-content" aria-label="${esc(tr('more'))}"><button role="menuitem" class="dropdown-item" tabindex="-1" data-ac-chat-act="pin">${ICON.pin} ${esc(tr(c.pinned ? 'unpin' : 'pin'))}</button><button role="menuitem" class="dropdown-item" tabindex="-1" data-ac-chat-act="rename">${ICON.edit} ${esc(tr('rename'))}</button><div class="dropdown-separator" role="separator"></div><button role="menuitem" class="dropdown-item" data-variant="destructive" tabindex="-1" data-ac-chat-act="delete">${ICON.remove} ${esc(tr('remove'))}</button></div></div>`,
              )
              .join(''),
          );
      });
      $('[data-ac-none]').get(0).hidden = !!shown.length || !q;
    };

    // -- answers: the demo model writes Markdown from the question; the API streams Server-Sent Events
    // what the demo model can tell about a file: sizes, lengths, colours, lines - not what a picture shows
    const colourName = (h) => {
      const [r, g, b] = [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
      const max = Math.max(r, g, b);
      const min = Math.min(r, g, b);
      const l = (max + min) / 2;
      if (max - min < 0.08) return l > 0.85 ? 'white' : l < 0.15 ? 'black' : 'grey';
      const d = max - min;
      const hue = (max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4) * 60;
      const H = (hue + 360) % 360;
      return H < 15
        ? 'red'
        : H < 45
          ? 'orange'
          : H < 70
            ? 'yellow'
            : H < 160
              ? 'green'
              : H < 200
                ? 'teal'
                : H < 255
                  ? 'blue'
                  : H < 290
                    ? 'purple'
                    : H < 340
                      ? 'pink'
                      : 'red';
    };
    const describe = (a) => {
      if (a.kind === 'image')
        return `- **${a.name}** - an image, ${a.width} × ${a.height} px, mostly ${colourName(a.color)} (\`${a.color}\`)`;
      if (a.kind === 'audio')
        return `- **${a.name}** - audio, ${a.duration ? clock(a.duration) + ' long' : 'of unknown length'}`;
      if (a.kind === 'video')
        return `- **${a.name}** - a video, ${a.width && a.height ? `${a.width} × ${a.height}, ` : ''}${a.duration ? clock(a.duration) + ' long' : 'of unknown length'}`;
      if (a.kind === 'text') {
        const lines = a.text.split('\n');
        const first =
          lines
            .find((x) => x.trim())
            ?.trim()
            .slice(0, 80) || '';
        return `- **${a.name}** - text, ${lines.length} lines and ${a.text.split(/\s+/).filter(Boolean).length} words${first ? `, starting "${first}"` : ''}`;
      }
      return `- **${a.name}** - ${a.type || 'a file'}, ${bytes(a.size)}; the demo model cannot open this kind of file`;
    };
    const CARD_FOR = [
      [/\b(deploy|release|migrat\w*)\b/, 'deploy'],
      [/\b(budget|quote|cost)\b/, 'budget'],
      [/\b(book|reserv\w*)\b/, 'booking'],
      [/\b(brief|project|questionnaire|survey)\b/, 'brief'],
      [/\b(rate|rating|feedback)\b/, 'feedback'],
      [/\b(which plan|pricing|subscription)\b/, 'plans'],
      [/\b(form|card|request|equipment)\b/, 'request'],
    ];
    const demoAnswer = (model, question, system, files = [], answer = null) => {
      if (answer && model !== 'echo')
        return {
          thinking: 'The user answered the card. Confirm what was chosen and say what happens next.',
          text: `${tr('noted', question.split('\n')[0])}\n\n${AFTER[answer.id]?.(answer) ?? 'I will take it from here.'}`,
        };
      const card =
        model === 'echo' || files.length ? null : CARD_FOR.find(([re]) => re.test(question.toLowerCase()))?.[1];
      if (card)
        return {
          thinking: `A structured answer helps here - show a card (${card}) instead of asking in prose.`,
          text: `Let us settle it in one card:\n\n${fenceOf(CARDS[card])}`,
        };
      if (files.length) {
        const about = `${files.length === 1 ? 'One attachment' : `${files.length} attachments`}:\n\n${files.map(describe).join('\n')}`;
        if (model === 'echo')
          return {
            text: [question, ...files.map((a) => a.name)].filter(Boolean).join('\n'),
            thinking: 'Echo repeats the message and names its files.',
          };
        const rest =
          question &&
          !/\b(this|these|that|those|it|them|attach\w*|files?|images?|pictures?|photos?|audio|video|recording)\b/i.test(
            question,
          )
            ? demoAnswer(model, question, system)
            : null;
        return {
          thinking: `The message carries ${files.length} file(s). Describe what can be measured - sizes, lengths, colours, lines - and say what the demo cannot see.`,
          text: `${about}\n\n${files.some((a) => a.kind === 'image') ? 'The demo model measures pictures but does not see them - connect a vision model in **Controls** to ask about what is in them.' : 'Ask about them, or connect a model in **Controls** that can read them.'}${rest ? `\n\n---\n\n${rest.text}` : ''}`,
        };
      }
      const q = question.toLowerCase();
      if (model === 'echo') return { text: question, thinking: 'Echo repeats the message as it was written.' };
      const persona = /pirate/i.test(system) ? 'Arr - ' : '';
      if (model === 'lumen-coder' || /\b(code|function|debounce|javascript|python|script|regex)\b/.test(q))
        return {
          thinking:
            'The user wants code. A debounce delays a call until the input has been quiet for a while - a timer that every new call restarts. Show it in JavaScript, then explain the parts.',
          text: `${persona}Here is a small, dependency-free **debounce** in JavaScript:\n\n\`\`\`js\nfunction debounce(fn, wait = 250) {\n  let timer;\n  return function (...args) {\n    clearTimeout(timer);\n    timer = setTimeout(() => fn.apply(this, args), wait);\n  };\n}\n\nconst onResize = debounce(() => console.log('resized'), 200);\naddEventListener('resize', onResize);\n\`\`\`\n\n- Every call **restarts** the timer, so \`fn\` runs once the calls stop for \`wait\` ms.\n- \`fn.apply(this, args)\` keeps the caller's \`this\` and the last arguments.\n- For the *first* call to run at once, add a \`leading\` flag.`,
        };
      if (/\b(compare|table|versus|vs)\b/.test(q))
        return {
          thinking:
            'Three databases, a few dimensions a reader decides on: where it runs, what it is best at, concurrency. A table fits.',
          text: `${persona}| | SQLite | Postgres | DuckDB |\n|---|---|---|---|\n| Runs | in your process | as a server | in your process |\n| Best at | small apps, files | many users, transactions | analytics over columns |\n| Writers at once | one | many | one |\n| Typical size | MB to GB | GB to TB | GB, read fast |\n\n**In short:** SQLite to embed, Postgres to share, DuckDB to analyse.`,
        };
      if (/\b(plan|trip|steps|list|itinerary)\b/.test(q))
        return {
          thinking:
            'A three-day plan: one area per day keeps the walking short. Lisbon: Baixa and Alfama, Belém, then Sintra as a day trip.',
          text: `${persona}### Three days in Lisbon\n\n1. **Baixa and Alfama** - Praça do Comércio in the morning, tram 28 up to the Miradouro de Santa Luzia, fado in Alfama at night.\n2. **Belém** - the Jerónimos Monastery, the tower, and *pastéis de nata* where they were first baked.\n3. **Sintra** - a day trip by train: Pena Palace early, before the crowds.\n\n> Buy a *Viva Viagem* card on day one - it covers trams, metro and the Sintra train.`,
        };
      return {
        thinking: `The question is "${question.slice(0, 80)}". Answer plainly: what happens first, then the steps, then one sentence to remember.`,
        text: `${persona}${/transformer/.test(q) ? 'A transformer reads a whole sentence **at once**, not word by word:' : `Here is a short answer to *${question.slice(0, 80)}*:`}\n\n1. **Tokens** - the text is cut into pieces and each becomes a vector.\n2. **Attention** - every piece looks at every other piece and weighs how much it matters to it.\n3. **Layers** - this repeats a few dozen times; each layer refines what the pieces mean in context.\n4. **Output** - the last layer predicts the next token, which is added and the loop runs again.\n\nThis answer comes from the demo model in the page - connect an OpenAI-compatible API in **Controls** for real ones.`,
      };
    };
    // tokens as a reader sees them: words with their spaces
    const tokens = (s) => s.match(/\s*\S+|\s+/g) || [];
    const wait = (ms, signal) =>
      new Promise((resolve, reject) => {
        const t = setTimeout(resolve, ms);
        signal.addEventListener('abort', () => (clearTimeout(t), reject(new DOMException('Aborted', 'AbortError'))), {
          once: true,
        });
      });
    async function* demoStream(model, history, settings, signal) {
      const last = [...history].reverse().find((m) => m.role === 'user');
      const { text, thinking } = demoAnswer(
        model,
        last?.display ?? last?.content ?? '',
        settings.systemPrompt,
        last?.files || [],
        last?.answer || null,
      );
      const pace = Math.round((MODELS[model]?.pace || 14) * (0.6 + settings.temperature * 0.3));
      await wait(350, signal);
      if (settings.enableThinking) for (const t of tokens(thinking)) yield (await wait(pace, signal), { think: t });
      const limit = Math.max(16, settings.maxTokens);
      for (const t of tokens(text).slice(0, limit)) yield (await wait(pace, signal), { text: t });
    }
    const apiContent = (m) => {
      if (m.role === 'user' && m.answer)
        return `${m.display ?? m.content}\n\n\`\`\`json\n${JSON.stringify(m.answer)}\n\`\`\``;
      if (m.role !== 'user' || !m.files?.length) return m.content;
      const text = [
        m.content,
        ...m.files.filter((a) => a.kind === 'text').map((a) => `--- ${a.name} ---\n${a.text}`),
        ...m.files.filter((a) => a.kind !== 'text' && a.kind !== 'image').map((a) => `[${a.kind}: ${a.name}]`),
      ]
        .filter(Boolean)
        .join('\n\n');
      const images = m.files.filter((a) => a.kind === 'image' && a.url);
      return images.length
        ? [{ type: 'text', text }, ...images.map((a) => ({ type: 'image_url', image_url: { url: a.url } }))]
        : text;
    };
    async function* apiStream(history, settings, signal) {
      const url = settings.baseUrl.replace(/\/+$/, '') + '/chat/completions';
      const cc = df$.shadcn.chatComponents;
      const cards = settings.componentTool
        ? `\n\nWhen a structured answer from the user helps (confirming a plan, an amount, choices, a date, a short form, several questions), show a card: call the show_components tool, or write a fenced block whose info string is ${cc.fence} with a Component Schema document - JSON: { "version": 1, "title", "body": [nodes], "actions": [{ "id", "label", "submit" | "reply" | "cancel" }] }. Nodes: text, list, table, facts, plan, alert, divider; fields input, textarea, number, currency, select, radio, checkbox, switch, slider, rating, date (each with a name and a label); one questionnaire with steps. The user's answers arrive as the next message.`
        : '';
      const system = (settings.systemPrompt || '') + cards;
      const messages = [
        ...(system ? [{ role: 'system', content: system }] : []),
        ...history.map((m) => ({ role: m.role, content: apiContent(m) })),
      ];
      const res = await fetch(url, {
        method: 'POST',
        signal,
        headers: {
          'Content-Type': 'application/json',
          ...(settings.apiKey ? { Authorization: `Bearer ${settings.apiKey}` } : {}),
        },
        body: JSON.stringify({
          model: settings.apiModel,
          messages,
          stream: true,
          temperature: settings.temperature,
          top_p: settings.topP,
          top_k: settings.topK,
          repetition_penalty: settings.repetitionPenalty,
          presence_penalty: settings.presencePenalty,
          max_tokens: settings.maxTokens,
          chat_template_kwargs: { enable_thinking: settings.enableThinking },
          ...(settings.componentTool ? { tools: [cc.tool()] } : {}),
        }),
      });
      if (!res.ok || !res.body) throw new Error(`${res.status} ${res.statusText || 'error'} - ${url}`);
      const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
      let buffer = '';
      let inThink = false;
      // tool calls stream in pieces: name and arguments per index, written as a fence at the end
      const calls = [];
      const flush = function* () {
        for (const c of calls)
          if (c?.name === 'show_components') yield { text: `\n\n\`\`\`${cc.fence}\n${c.args}\n\`\`\`\n` };
      };
      for (;;) {
        const { done, value } = await reader.read();
        if (done) return yield* flush();
        buffer += value;
        let nl;
        while ((nl = buffer.indexOf('\n')) >= 0) {
          const line = buffer.slice(0, nl).trim();
          buffer = buffer.slice(nl + 1);
          if (!line.startsWith('data:')) continue;
          const data = line.slice(5).trim();
          if (data === '[DONE]') return yield* flush();
          let delta;
          try {
            delta = JSON.parse(data).choices?.[0]?.delta;
          } catch {
            continue;
          }
          if (delta?.reasoning_content || delta?.reasoning) yield { think: delta.reasoning_content || delta.reasoning };
          for (const tc of delta?.tool_calls || []) {
            const c = (calls[tc.index ?? 0] ??= { name: '', args: '' });
            c.name += tc.function?.name || '';
            c.args += tc.function?.arguments || '';
          }
          // a model that thinks inline wraps it in think tags
          let text = delta?.content || '';
          while (text) {
            const tag = inThink ? text.indexOf('</think>') : text.indexOf('<think>');
            const part = tag < 0 ? text : text.slice(0, tag);
            if (part) yield inThink ? { think: part } : { text: part };
            if (tag < 0) break;
            inThink = !inThink;
            text = text.slice(tag + (inThink ? 7 : 8));
          }
        }
      }
    }

    // -- one generation: streams into the assistant message, the Session follows it
    const generate = async (chatId, assistantId) => {
      const c = find(chatId);
      if (!c) return;
      const index = c.messages.findIndex((m) => m.id === assistantId);
      const history = c.messages.slice(0, index);
      const settings = conf();
      const model = c.model;
      const abort = new AbortController();
      run = { chatId, messageId: assistantId, abort };
      sendBtn.toggleAttribute('data-streaming', true);
      sendBtn.setAttribute('aria-label', tr('stop'));
      if (chatId === current) chat.api.setState('streaming');
      let text = '';
      let thinking = '';
      let count = 0;
      const started = performance.now();
      let thinkStart = 0;
      let thinkSeconds = 0;
      let frame = 0;
      const patch = (extra) =>
        update(
          chatId,
          (x) => ((x.messages = x.messages.map((m) => (m.id === assistantId ? { ...m, ...extra } : m))), x),
        );
      // the store (and its storage) is written once a frame, not once a token
      let pending = null;
      const paint = (extra) => {
        pending = { ...pending, ...extra };
        if (frame) return;
        frame = requestAnimationFrame(() => {
          frame = 0;
          patch(pending);
          pending = null;
          renderMessage(chatId, assistantId);
        });
      };
      try {
        const stream =
          model === 'api'
            ? apiStream(history, settings, abort.signal)
            : demoStream(model, history, settings, abort.signal);
        for await (const part of stream) {
          count++;
          if (part.think) {
            thinkStart ||= performance.now();
            thinking += part.think;
            paint({ thinking, streaming: 'think' });
          } else {
            if (thinkStart && !thinkSeconds) thinkSeconds = (performance.now() - thinkStart) / 1000;
            text += part.text;
            paint({ content: text, thinking, thinkSeconds, streaming: 'text' });
          }
        }
        patch({
          content: text,
          thinking,
          thinkSeconds: thinkSeconds || (thinkStart ? (performance.now() - thinkStart) / 1000 : 0),
          streaming: false,
          stats: { tokens: count, seconds: (performance.now() - started) / 1000 },
        });
      } catch (err) {
        const stopped = err?.name === 'AbortError';
        patch({
          content: text,
          thinking,
          streaming: false,
          stopped,
          error: stopped ? '' : String(err?.message || err),
          stats: { tokens: count, seconds: (performance.now() - started) / 1000 },
        });
      } finally {
        cancelAnimationFrame(frame);
        run = null;
        sendBtn.removeAttribute('data-streaming');
        sendBtn.setAttribute('aria-label', tr('send'));
        await renderMessage(chatId, assistantId);
        if (chatId === current) chat.api.setState(session.isAtEnd(chat) ? 'default' : 'detached');
        // a new chat takes its title from the first question
        update(chatId, (x) => ((x.title = x.title || titleFrom(x.messages[0]?.content || tr('untitled'))), x));
        renderList();
      }
    };
    const titleFrom = (s) => {
      const t = s.replace(/\s+/g, ' ').trim();
      return t.length > 42 ? t.slice(0, 40).trimEnd() + '...' : t;
    };
    const stop = () => run?.abort.abort();

    // -- sending: a new chat is made on the first message, the question anchors, the answer streams
    const send = async (text, cardAnswer = null) => {
      text = text.trim();
      if ((!text && !attachments.length) || run) return;
      const scripted = current && find(current)?.script;
      if (scripted) {
        $(input).val('');
        input.dispatchEvent(new Event('input', { bubbles: true }));
        return scripts.get(current)?.run.reply(text);
      }
      const files = attachments;
      attachments = [];
      renderAttachments();
      let id = current;
      if (!id || !find(id)) {
        id = 'c' + Date.now().toString(36);
        save([
          {
            id,
            title: titleFrom(text || files[0]?.name || tr('untitled')),
            pinned: false,
            model: conf().model,
            at: Date.now(),
            messages: [],
          },
          ...list(),
        ]);
      }
      const at = Date.now();
      const question = {
        id: 'm' + at.toString(36) + 'u',
        role: 'user',
        content: text,
        display: text,
        files,
        at,
        ...(cardAnswer ? { answer: cardAnswer } : {}),
      };
      const answer = {
        id: 'm' + at.toString(36) + 'a',
        role: 'assistant',
        content: '',
        model: find(id).model,
        at: at + 1,
        streaming: 'wait',
      };
      update(id, (c) => ((c.messages = [...c.messages, question, answer]), (c.at = at), c));
      $(input).val('');
      input.dispatchEvent(new Event('input', { bubbles: true }));
      if (id !== current) {
        current = id;
        go('/c/' + id, true);
        await renderChat();
      } else {
        const marked = await loadMarked();
        chat.removeAttribute('data-empty');
        session.append(chat, turn(question, marked), { id: question.id, anchor: true });
        session.append(chat, turn(answer, marked), { id: answer.id });
      }
      renderList();
      generate(id, answer.id);
    };
    // -- a card's answer: stored on its message (it renders answered), then the reader's turn or the script's
    $(chat).on('chat-components-answer', (e) => {
      const card = e.target;
      const row = card.closest('[data-message-id]');
      const c = current && find(current);
      if (!row || !c) return;
      const index = Number(card.id.split('-f').pop());
      const result = JSON.parse(JSON.stringify(card.api.getState().config));
      update(
        c.id,
        (x) => (
          (x.messages = x.messages.map((m) =>
            m.id === row.dataset.messageId ? { ...m, forms: { ...(m.forms || {}), [index]: result } } : m,
          )),
          x
        ),
      );
      const d = e.detail;
      if (c.script) return scripts.get(c.id)?.run.answer(d);
      send(d.summary, { id: d.id, action: d.action, answers: d.answers, ...(d.reply ? { reply: d.reply } : {}) });
    });

    // -- Chat Scripts: a run per script chat writes its turns into the chat through hooks
    const scripts = new Map();
    let typing = null;
    let typingOff = 0;
    const dropTyping = () => {
      clearTimeout(typingOff);
      typing?.remove();
      typing = null;
    };
    function startScript(c) {
      if (scripts.has(c.id)) return;
      const { bot, script } = SCRIPTS[c.script];
      const chatId = c.id;
      const keep = () => queueMicrotask(() => update(chatId, (x) => ((x.scriptState = entry.run.state()), x)));
      // synchronous: a turn lands in the order the script writes it (an awaited append put the typing row
      // above the reader's answer - VERIFIED: removing it moved the anchored answer and the view with it)
      const push = (m) => {
        update(chatId, (x) => ((x.messages = [...x.messages, m]), (x.at = Math.max(x.at, m.at)), x));
        keep();
        if (chatId !== current) return;
        chat.removeAttribute('data-empty');
        // a script answers at once and in short turns: the transcript follows its end, so the window stays
        // filled (an anchored answer at the top left most of it empty - the maintainer 2026-11-21);
        // the reader's own turn brings them to the end, the bot's turns follow from there
        session.append(chat, turn(m, entry.marked), { id: m.id });
        dropTyping();
        if (m.role === 'user') session.scrollToEnd(chat);
      };
      let n = 0;
      const id = (role) => 'm' + Date.now().toString(36) + (n++).toString(36) + role[0];
      const entry = {
        run: df$.shadcn.chatScript.create(
          script,
          {
            say: (text) =>
              push({
                id: id('assistant'),
                role: 'assistant',
                content: text,
                model: 'script',
                modelName: bot,
                script: true,
                at: Date.now(),
              }),
            ask: (spec) =>
              push({
                id: id('assistant'),
                role: 'assistant',
                content: fenceOf(spec),
                model: 'script',
                modelName: bot,
                script: true,
                at: Date.now(),
              }),
            user: (text) => push({ id: id('user'), role: 'user', content: text, script: true, at: Date.now() }),
            typing: (on) => {
              if (chatId !== current) return;
              // off: the next turn takes the indicator's place in the same task (removed a task earlier, the
              // transcript dipped by its height for a frame); a short timer drops it when no turn follows
              clearTimeout(typingOff);
              if (!on) {
                typingOff = setTimeout(dropTyping, 100);
                return;
              }
              typing?.remove();
              typing = on
                ? session.append(
                    chat,
                    `<div class="message ac-turn"><div class="message-avatar"><span class="avatar" data-size="sm"><span class="avatar-fallback ac-mark">${ICON.spark}</span></span></div><div class="message-content"><div class="bubble" data-variant="secondary"><div class="bubble-content" role="status" aria-label="${esc(bot)}"><span class="bubble-typing" aria-hidden="true"><span></span><span></span><span></span></span></div></div></div></div>`,
                  )
                : null;
            },
            rewind: (rows) => {
              update(chatId, (x) => ((x.messages = x.messages.slice(0, rows)), x));
              keep();
              if (chatId === current) renderChat();
            },
          },
          c.scriptState || null,
        ),
      };
      scripts.set(chatId, entry);
      // Markdown first, so every turn after it appends at once
      loadMarked().then((marked) => {
        entry.marked = marked;
        entry.run.start();
      });
    }

    // a user turn shows what was typed; the attached files ride along to the model
    const shownText = (m) => m.display ?? m.content;

    // -- routes: #/ a new chat, #/c/:id a chat, #/auth the sign-in
    const routes = [
      { id: 'home', path: '/' },
      { id: 'chat', path: '/c/:id' },
      { id: 'auth', path: '/auth' },
      { id: 'missing', path: '*' },
    ];
    let router = null;
    let following = false;
    const go = (path, replace = false) => {
      if (router && !following) router.navigate('#' + path, { replace });
      else if (replace) history.replaceState(null, '', '#' + path);
      else location.hash = path;
    };
    const show = (to) => {
      const auth = to.routeId === 'auth' || !signedIn;
      $('[data-ac-auth]').get(0).hidden = !auth;
      if (auth) return;
      if (to.routeId === 'chat' && find(to.params.id)) current = to.params.id;
      else current = null;
      if (to.routeId === 'chat' && !find(to.params.id)) go('/', true);
      if (run && run.chatId !== current) stop();
      renderChat();
      renderList();
      if (narrow()) nav.api.setState('collapsed');
    };

    // -- events: composer, turns, the list, the menus, the settings
    $(composer).on('submit', (e) => {
      e.preventDefault();
      if (run) return stop();
      send($(input).val());
    });
    $(input).on('keydown', (e) => {
      if (e.key !== 'Enter' || e.isComposing) return;
      if (conf().enterSends ? e.shiftKey : !(e.metaKey || e.ctrlKey)) return;
      e.preventDefault();
      if (!run) send($(input).val());
    });
    $(app).on('click', (e) => {
      const t = e.target instanceof Element ? e.target : null;
      if (!t) return;
      const prompt = t.closest('[data-ac-prompt]');
      if (prompt) return send(prompt.dataset.acPrompt);
      const scrim = t.closest('[data-ac-scrim]');
      if (scrim) {
        if (nav.dataset.state === 'expanded') nav.api.setState('collapsed');
        if (controls.dataset.state === 'expanded') controls.api.setState('collapsed');
        return;
      }
      const codeCopy = t.closest('[data-ac-copy-code]');
      if (codeCopy)
        return copy(
          $(codeCopy)
            .closest('.ac-code')
            .find('.mockup-code pre')
            .toArray()
            .map((line) => line.textContent)
            .join('\n'),
        );
      const preview = t.closest('[data-ac-preview]');
      if (preview) return openPreview(preview.dataset.acPreview);
      const act = t.closest('[data-ac-msg]');
      if (act) return onMessage(act.dataset.acMsg, act);
      const chatAct = t.closest('[data-ac-chat-act]');
      if (chatAct) return onChat(chatAct.dataset.acChatAct, chatAct.closest('[data-ac-chat]').dataset.acChat);
      const action = t.closest('[data-ac-action]');
      if (action) return onAction(action.dataset.acAction);
      if (t.closest('[data-ac-attach]')) $('[data-ac-file]').get(0).click();
      if (t.closest('[data-ac-reset]')) {
        setConf({ ...DEFAULTS, model: conf().model, enterSends: conf().enterSends });
        fillSettings();
      }
    });
    const copy = async (text) => {
      try {
        await navigator.clipboard.writeText(text);
      } catch {
        // the clipboard may be refused (a sandboxed frame): the toast still tells what was meant
      }
      toast(tr('copied'));
    };
    const messageOf = (el) => {
      const id = el.closest('[data-message-id]')?.dataset.messageId;
      return { id, m: find(current)?.messages.find((x) => x.id === id) };
    };
    const onMessage = (act, el) => {
      const { id, m } = messageOf(el);
      if (!m || run) return;
      if (act === 'copy') return copy(m.role === 'user' ? shownText(m) : m.content);
      if (act === 'good' || act === 'bad') {
        const rating = m.rating === act ? null : act;
        update(current, (c) => ((c.messages = c.messages.map((x) => (x.id === id ? { ...x, rating } : x))), c));
        renderMessage(current, id);
        if (rating) toast(tr('thanks'));
        return;
      }
      if (act === 'info') {
        update(
          current,
          (c) => ((c.messages = c.messages.map((x) => (x.id === id ? { ...x, showInfo: !x.showInfo } : x))), c),
        );
        return renderMessage(current, id);
      }
      if (act === 'read') {
        const say = globalThis.speechSynthesis;
        if (!say) return;
        say.cancel();
        const u = new SpeechSynthesisUtterance(m.content.replace(/[`*#>|_-]+/g, ' '));
        u.lang = lang();
        say.speak(u);
        return;
      }
      if (act === 'regenerate') {
        update(current, (c) => {
          const i = c.messages.findIndex((x) => x.id === id);
          c.messages = [
            ...c.messages.slice(0, i),
            {
              ...m,
              content: '',
              thinking: '',
              rating: null,
              stats: null,
              showInfo: false,
              stopped: false,
              error: '',
              streaming: 'wait',
              at: Date.now(),
              model: c.model,
            },
          ];
          return c;
        });
        renderChat().then(() => generate(current, id));
        return;
      }
      if (act === 'delete') {
        return confirm(tr('delMsgTitle'), tr('delMsgDesc'), () => {
          update(
            current,
            (c) => (
              (c.messages = c.messages.slice(
                0,
                c.messages.findIndex((x) => x.id === id),
              )),
              c
            ),
          );
          renderChat();
          renderList();
        });
      }
      if (act === 'edit') return editMessage(el.closest('[data-message-id]'), m);
    };
    // editing a question: the bubble becomes a composer; sending drops what followed and asks again
    const editMessage = (row, m) => {
      const bubble = $(row).find('.message-content > .bubble').get(0) || $(row).find('.message-footer').get(0);
      const form = document.createElement('form');
      form.className = 'textarea-group ac-edit';
      $(form).html(
        `<textarea class="textarea" data-rows="2" data-max-rows="10" aria-label="${esc(tr('edit'))}"></textarea><div class="textarea-group-actions"><span class="textarea-group-spacer"></span><button class="btn" data-variant="ghost" data-size="sm" type="button" data-ac-edit-cancel>${esc(tr('cancel'))}</button><button class="btn" data-size="sm" type="submit">${esc(tr('save'))}</button></div>`,
      );
      if (bubble.matches('.message-footer')) bubble.before(form);
      else bubble.replaceWith(form);
      $(row).find('.message-footer').get(0).hidden = true;
      const area = $(form).find('textarea').get(0);
      area.value = shownText(m);
      area.focus();
      $(form)
        .find('[data-ac-edit-cancel]')
        .on('click', () => renderChat());
      form.addEventListener('submit', (e) => {
        e.preventDefault();
        const text = area.value.trim();
        if (!text && !m.files?.length) return;
        const at = Date.now();
        const answer = {
          id: 'm' + at.toString(36) + 'a',
          role: 'assistant',
          content: '',
          model: find(current).model,
          at,
          streaming: 'wait',
        };
        update(current, (c) => {
          const i = c.messages.findIndex((x) => x.id === m.id);
          c.messages = [...c.messages.slice(0, i), { ...m, content: text, display: text, at }, answer];
          return c;
        });
        renderChat().then(() => generate(current, answer.id));
      });
    };
    const onChat = (act, id) => {
      $(`#ac-menu-${id}`).get(0)?.hidePopover?.();
      const c = find(id);
      if (!c) return;
      if (act === 'pin') {
        update(id, (x) => ((x.pinned = !x.pinned), x));
        return renderList();
      }
      if (act === 'delete') {
        return confirm(tr('delChatTitle', c.title || tr('untitled')), tr('delChatDesc'), () => {
          save(list().filter((x) => x.id !== id));
          toast(tr('deleted'));
          if (current === id) go('/');
          renderList();
        });
      }
      if (act === 'rename') {
        const link = $(`[data-ac-chat="${id}"] .sidebar-link`).get(0);
        const field = document.createElement('input');
        field.className = 'input ac-rename';
        field.dataset.size = 'sm';
        field.value = c.title;
        field.setAttribute('aria-label', tr('rename'));
        link.replaceWith(field);
        field.focus();
        field.select();
        let done = false;
        const finish = (keep) => {
          if (done) return;
          done = true;
          const title = field.value.trim();
          if (keep && title) update(id, (x) => ((x.title = title), x));
          renderList();
        };
        field.addEventListener('keydown', (e) => {
          if (e.key === 'Enter') finish(true);
          if (e.key === 'Escape') finish(false);
        });
        field.addEventListener('blur', () => finish(true));
      }
    };
    const onAction = (act) => {
      $('#ac-user-menu').get(0).hidePopover?.();
      if (act === 'controls') return controls.api.setState('default');
      if (act === 'sign-out') {
        stop();
        signedIn = false;
        toast(tr('signedOut'));
        return go('/auth');
      }
      if (act === 'clear-all') {
        return confirm(tr('delAllTitle'), tr('delAllDesc'), () => {
          save([]);
          $('#ac-settings').get(0).close();
          go('/');
          renderList();
          renderChat();
        });
      }
    };
    // one Alert Dialog for every deletion
    let confirmed = null;
    const confirm = (title, desc, ok) => {
      $('[data-ac-confirm-title]').text(title);
      $('[data-ac-confirm-desc]').text(desc);
      confirmed = ok;
      $('#ac-confirm').get(0).api.setState('open');
    };
    $('[data-ac-confirm-ok]').on('click', () => {
      const ok = confirmed;
      confirmed = null;
      $('#ac-confirm').get(0).api.setState('default');
      ok?.();
    });

    // the model picker: a radio menu; the API model shows while the API connection is chosen
    $('#ac-models').on('dropdown:select', (e) => {
      const model = e.detail.value;
      // a radio menu stays open by default; picking a model is done
      e.currentTarget.hidePopover();
      setConf({ model });
      if (current) update(current, (c) => ((c.model = model), c));
      $('[data-ac-model-name]').text(modelName(model));
    });
    const syncModelMenu = () => {
      const s = conf();
      const api = s.connection === 'api';
      $('[data-ac-api-model]').get(0).hidden = !api;
      $('[data-ac-api-model-name]').text(s.apiModel);
      $('[data-ac-conn-badge]').get(0).hidden = !api;
      if (!api && s.model === 'api') setConf({ model: 'lumen-8b' });
      const model = conf().model;
      $('#ac-models .dropdown-radio').each((_i, b) => {
        b.setAttribute('aria-checked', String(b.dataset.value === model));
      });
      $('[data-ac-model-name]').text(modelName(current ? find(current)?.model || model : model));
      $('[data-ac-fine]').text(api ? tr('fineApi', s.baseUrl) : tr('fine'));
    };

    // -- controls: the form IS the settings - every change is saved and applied to the next answer
    const fillSettings = () => {
      const s = conf();
      for (const el of settingsForm.elements) {
        if (!el.name) continue;
        if (el.type === 'radio') el.checked = s[el.name] === el.value;
        else if (el.type === 'checkbox') el.checked = !!s[el.name];
        else el.value = el.name === 'model' ? s.apiModel : s[el.name];
      }
      $('[data-ac-out]').each((_i, o) => {
        o.textContent = String(s[o.dataset.acOut]);
      });
      $('[data-ac-api]').get(0).disabled = s.connection !== 'api';
      const think = $('[data-ac-think-toggle]').get(0);
      if ((think.api.getState().name === 'pressed') !== !!s.enableThinking)
        think.api.setState(s.enableThinking ? 'pressed' : 'default');
      $('[data-ac-enter]').get(0).checked = s.enterSends;
      syncModelMenu();
    };
    $(settingsForm).on('input', (e) => {
      const el = e.target;
      if (!el.name) return;
      const value =
        el.type === 'checkbox' ? el.checked : el.type === 'range' || el.type === 'number' ? Number(el.value) : el.value;
      setConf({ [el.name === 'model' ? 'apiModel' : el.name]: value });
      if (el.type === 'range') $(`[data-ac-out="${el.name}"]`).text(String(value));
      if (el.name === 'connection') {
        const model = value === 'api' ? 'api' : 'lumen-8b';
        setConf({ model });
        if (current) update(current, (c) => ((c.model = model), c));
      }
      if (el.name === 'connection' || el.name === 'model' || el.name === 'baseUrl') {
        $('[data-ac-api]').get(0).disabled = conf().connection !== 'api';
        syncModelMenu();
      }
      if (el.name === 'enableThinking') fillSettings();
    });
    $('[data-ac-think-toggle]')
      .get(0)
      .store.subscribe(({ name }) => {
        if ((name === 'pressed') === !!conf().enableThinking) return;
        setConf({ enableThinking: name === 'pressed' });
        fillSettings();
      });
    $('[data-ac-enter]').on('change', (e) => setConf({ enterSends: e.currentTarget.checked }));
    // light / dark: the sidebar's Swap and the Settings switch write the one class every token reads
    const showMode = () => {
      const dark = document.documentElement.classList.contains('dark');
      $('[data-ac-dark], [data-ac-mode]').each((_i, el) => {
        el.checked = dark;
      });
    };
    $('[data-ac-dark], [data-ac-mode]').on('change', (e) => {
      document.documentElement.classList.toggle('dark', e.currentTarget.checked);
      showMode();
      dispatchEvent(new CustomEvent('defuss-theme-change'));
    });
    showMode();
    $('[data-ac-search]').on('input', renderList);

    // -- attachments: chips above the text; the + button, a paste, a drop on the conversation or a voice message add them
    const renderAttachments = () => {
      $(composer)
        .find('.file-drop-list')
        .html(
          attachments
            .map(
              (a, i) =>
                `<li class="file-drop-item" data-kind="${a.kind}"><span class="file-drop-thumb" aria-hidden="true">${a.kind === 'image' ? `<img src="${urlOf(a)}" alt="" />` : kindIcon(a)}</span><div class="file-drop-name">${esc(a.name)}<span class="file-drop-meta">${esc(metaOf(a))}</span></div><button type="button" class="file-drop-remove" data-ac-unattach="${i}" aria-label="${esc(tr('remove'))} ${esc(a.name)}">✕</button></li>`,
            )
            .join(''),
        );
    };
    $('[data-ac-file]').on('change', async (e) => {
      const files = [...e.currentTarget.files];
      e.currentTarget.value = '';
      await addFiles(files);
    });
    $(input).on('paste', (e) => {
      const files = [...(e.clipboardData?.files || [])];
      if (!files.length) return;
      e.preventDefault();
      addFiles(files);
    });
    $(chat).on('session-drop', (e) => addFiles(e.detail.files));
    $(composer).on('click', (e) => {
      const b = e.target instanceof Element && e.target.closest('[data-ac-unattach]');
      if (!b) return;
      attachments.splice(Number(b.dataset.acUnattach), 1);
      renderAttachments();
    });
    // a voice message: MediaRecorder on the microphone; its length is counted here (a recorded WebM has none)
    const recordBtn = $('[data-ac-record]').get(0);
    let recorder = null;
    let recTimer = 0;
    $(recordBtn).on('click', async () => {
      if (recorder) return recorder.state === 'recording' && recorder.stop();
      let stream;
      try {
        stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      } catch {
        return toast(tr('noMic'));
      }
      const chunks = [];
      const started = Date.now();
      recorder = new MediaRecorder(stream);
      recorder.addEventListener('dataavailable', (e) => e.data.size && chunks.push(e.data));
      recorder.addEventListener('stop', async () => {
        stream.getTracks().forEach((t) => t.stop());
        clearInterval(recTimer);
        recorder = null;
        recordBtn.setAttribute('aria-pressed', 'false');
        $('[data-ac-recording]').get(0).hidden = true;
        const type = chunks[0]?.type || 'audio/webm';
        const ext = type.includes('ogg') ? 'ogg' : type.includes('mp4') ? 'm4a' : 'webm';
        const file = new File(chunks, `${tr('voiceName')} ${time(Date.now())}.${ext}`, { type });
        await addFiles([file], { duration: (Date.now() - started) / 1000 });
      });
      recorder.start();
      recordBtn.setAttribute('aria-pressed', 'true');
      $('[data-ac-recording]').get(0).hidden = false;
      const tick = () => $('[data-ac-rec-time]').text(clock((Date.now() - started) / 1000));
      tick();
      recTimer = setInterval(tick, 250);
    });
    // a picture in a message opens in a Dialog
    const openPreview = (id) => {
      const a = find(current)
        ?.messages.flatMap((m) => m.files || [])
        .find((x) => x.id === id);
      if (!a) return;
      $('[data-ac-preview-title]').text(a.name);
      $('[data-ac-preview-meta]').text(metaOf(a));
      $('[data-ac-preview-img]').attr('src', urlOf(a)).attr('alt', a.name);
      $('[data-ac-preview-download]').attr('href', urlOf(a)).attr('download', a.name);
      $('#ac-preview').get(0).api.setState('open');
    };
    const dropLabel = () => (chat.dataset.dropLabel = tr('dropLabel'));
    dropLabel();

    // -- sign-in: the demo account (the example's pre-auth screen)
    $('[data-ac-signin]').on('submit', (e) => {
      e.preventDefault();
      const data = new FormData(e.currentTarget);
      const ok =
        String(data.get('email')).trim().toLowerCase() === 'ada@example.com' && data.get('password') === 'lumen';
      $('[data-ac-auth-error]').get(0).hidden = ok;
      if (!ok) return;
      signedIn = true;
      e.currentTarget.reset();
      toast(tr('welcome'));
      go('/');
    });

    // the language and the narrow layout change what the script wrote
    locale.subscribe(() => {
      dropLabel();
      renderAttachments();
      renderList();
      renderChat();
      syncModelMenu();
    });
    const narrow = () => app.clientWidth < 832;
    if (narrow()) nav.api.setState('collapsed');
    // a chat picked in the narrow layout closes the sidebar over it
    $(nav).on('click', (e) => {
      if (narrow() && e.target instanceof Element && e.target.closest('a.sidebar-link, [data-ac-new]'))
        nav.api.setState('collapsed');
    });

    fillSettings();
    loadMarked();

    router = createRouter({ mode: 'hash', routes, prepare: ({ to }) => ({ commit: () => show(to) }) });
    router.attachLinks(app);
    if ((await router.start()).status === 'rejected') {
      // no address the router may own - a docs preview is an about:srcdoc frame: the same routes match its hash
      router = null;
      following = true;
      const preview = createRouter({ mode: 'hash', routes, baseUrl: 'https://preview.invalid/' });
      const follow = () => show(preview.resolve(location.hash.startsWith('#/') ? location.hash : '#/'));
      addEventListener('hashchange', follow);
      follow();
    }
  });
</script>
```

<h2 id="how-it-works" class="h2-display">How it works</h2>

<DocText>A page, not a component: it composes the library and keeps its own glue small. It adapts the <a href="https://github.com/kyr0/defuss/tree/main/examples/ai-chat" target="_blank" rel="noopener">ai-chat example</a> of defuss - conversations, streaming, message actions, the settings sidebar and the sign-in - to the shipped components, in the look of Open WebUI.</DocText>

<ul class="text-sm" style="display:grid;gap:0.5rem;max-width:46rem;padding-inline-start:1.25rem">
  <li><strong>Layout</strong> - the <DocLink href="sidebar.html">Sidebar</DocLink> twice in one <code>.sidebar-layout</code>: the chats on the start side, Controls on the end side (<code>data-side="right"</code>). Their state (<code>default</code> / <code>collapsed</code>) opens and closes them; below 52rem of width they lie over the conversation and a scrim closes them.</li>
  <li><strong>Chats</strong> - grouped into Pinned, Today, Yesterday, Previous 7 days and Older; the search filters titles and messages. Each row has a <DocLink href="dropdown.html">Dropdown Menu</DocLink> to pin, rename in place or delete (an <DocLink href="alert-dialog.html">Alert Dialog</DocLink> asks first).</li>
  <li><strong>Conversation</strong> - the <DocLink href="session.html">Session</DocLink>: every question is a <code>data-anchor</code> turn that settles near the top, the answer streams under the <code>streaming</code> state and the window follows it while you are at the end. Turns are <DocLink href="message.html">Messages</DocLink> with <DocLink href="bubble.html">Bubbles</DocLink>; "Thinking..." and the folded reasoning are <DocLink href="marker.html">Markers</DocLink> with the shimmer.</li>
  <li><strong>Answers</strong> - Markdown through <a href="https://marked.js.org" target="_blank" rel="noopener">marked</a> (pinned), cleaned before it enters the page; tables become the <DocLink href="table.html">Table</DocLink>, code blocks a <DocLink href="mockup-code.html">Code mockup</DocLink> with a copy button. Hover an answer to copy, read it aloud (<code>speechSynthesis</code>), show its tokens per second, rate it or regenerate it; hover a question to edit it (what followed is dropped and asked again) or delete it.</li>
  <li><strong>Models</strong> - four demo models answer in the page (Markdown with code, a table, a plan, prose; Echo repeats), at their own pace. Controls › Connection switches to any OpenAI-compatible API: <code>POST {"{base}"}/chat/completions</code> with <code>stream: true</code>, the Server-Sent Events read as they arrive, reasoning from <code>reasoning_content</code> or <code>&lt;think&gt;</code> tags; the stop button aborts the request (<code>AbortController</code>).</li>
  <li><strong>Controls</strong> - the system prompt and the sampling parameters of the example (temperature, top P, top K, repetition and presence penalty, max tokens, thinking) as <DocLink href="slider.html">Sliders</DocLink> with <code>&lt;output&gt;</code>, a number <DocLink href="input.html">Input</DocLink> and a <DocLink href="switch.html">Switch</DocLink>; the form is the settings store.</li>
  <li><strong>Composer</strong> - the <DocLink href="textarea.html">Textarea</DocLink> group grows with the text; <kbd class="kbd">↵</kbd> sends, <kbd class="kbd">⇧</kbd> <kbd class="kbd">↵</kbd> breaks the line (Settings can swap it); the <DocLink href="toggle.html">Toggle</DocLink> turns thinking on.</li>
  <li><strong>Attachments</strong> - any file, from the + button, a paste or a drop on the conversation (the Session's <code>data-drop</code> and its <code>session-drop</code> event), shows as a <DocLink href="file-input.html">File Input</DocLink> chip with a thumbnail and its size or length. Sent, a picture is a media <DocLink href="bubble.html">Bubble</DocLink> (<code>data-media</code>) that opens in a <DocLink href="dialog.html">Dialog</DocLink>, audio and video play in the <DocLink href="audio.html">Audio</DocLink> and <DocLink href="video.html">Video</DocLink> players, documents are <DocLink href="message.html">Message</DocLink> attachment cards that download. The microphone button records a voice message with <code>MediaRecorder</code>. The demo model measures what it gets (size, length, the average colour of a picture, the lines of a text); an API gets pictures as <code>image_url</code> parts, text files as text. Pictures are kept with the chat (scaled to 1280 px, WebP); audio, video and other files live for the visit and say so after a reload.</li>
  <li><strong>Chat Components</strong> - an answer can ask with a card: a <DocLink href="component-schema.html">Component Schema</DocLink> document in a <code>ui::component-schema</code> fence becomes <DocLink href="chat-components.html">Chat Components</DocLink> (amounts, choices, dates, a plan to confirm, a questionnaire, quick replies). Answering it stores the answer on the message - the card renders answered from then on - and sends your turn: the answer's sentence, and for an API the JSON too. The demo model answers card-shaped questions with one (try "book a table" or "deploy release 2.4"); in API mode the system prompt describes the fence and the request offers the <code>show_components</code> tool - a tool call is stored as the same fence, so the history replays on any server. Controls › Connection turns both off.</li>
  <li><strong>Examples</strong> - the sidebar's first group holds conversations to try: cards answered and still open, and two <DocLink href="chat-scripts.html">Chat Scripts</DocLink> - a support bot and a pizza order that run without a language model. A script runs through <code>chatScript.create(script, hooks)</code>, so its turns land in the chat's store like any other and the run continues after a reload.</li>
  <li><strong>State</strong> - chats and settings are <code>df$.store.persisted</code> stores: kept in the browser on the full-screen page, in memory inside the docs card.</li>
  <li><strong>Routing</strong> - <a href="https://dom-router.defuss.org" target="_blank" rel="noopener">defuss-dom-router</a> in hash mode: <code>#/</code> a new chat, <code>#/c/:id</code> a chat, <code>#/auth</code> the sign-in (Sign out leads there; the demo account is on the card). See <DocLink href="routing.html">Client-side Routing</DocLink>.</li>
  <li><strong>Translation</strong> - <a href="https://i18n.defuss.org" target="_blank" rel="noopener">defuss-i18n</a>: Settings › Language switches the chrome between English and German; what the script writes (message actions, chat menus, dialogs) follows from its own table. See <DocLink href="translation.html">Translation</DocLink>.</li>
  <li><strong>Full screen</strong> - <DocLink href="app-ai-chat.html">app-ai-chat.html</DocLink> is generated from this page's example at build time and loads only its own bundle.</li>
</ul>

</DocPage>
