Skip to content

armgit / ALIVE

Public Imported from GitHub
0

ALIVE: Making Streaming Video Models Interactive

Python
402 KB
Raw Blame
<!--
SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ALIVE</title>

    <link rel="icon" type="image/png" href="/images/alive.png">

    <style>
        :root {
            /* Compatibility names for existing controls; alive brand colors. */
            --alive-red: #d51b69;
            --alive-red-dark: #ac1553;
            --alive-red-light: #ee418b;
            --alive-red-soft: rgba(231, 35, 116, 0.12);
            --alive-red-ring: rgba(231, 35, 116, 0.24);
            --alive-red-shadow: rgba(62, 18, 41, 0.32);

            /* Legacy variables kept for existing references */
            --theme-green: var(--alive-red);
            --theme-green-dark: var(--alive-red-dark);
            --theme-green-light: var(--alive-red-light);

            --bg-primary: #15171a;
            --bg-secondary: #1d2024;
            --bg-tertiary: #282c31;
            --text-primary: #f7f8fa;
            --text-secondary: #cbd0d6;
            --text-muted: #a0a7b0;
            --border-color: #3b4149;
            --card-bg: #22262b;
            --card-hover: #30363e;
            --accent-color: #ff82b6;
            --accent-hover: #ffa5ca;
            --primary-blue: var(--accent-color);
            --hover-bg: var(--card-hover);
            --warning-color: #f5b66b;
            --error-color: #f17e86;
        }

        body.light-theme {
            --bg-primary: #ffffff;
            --bg-secondary: #fafafa;
            --bg-tertiary: #f5f6f7;
            --text-primary: #20242a;
            --text-secondary: #525a65;
            --text-muted: #69727e;
            --border-color: #e3e6e9;
            --card-bg: #ffffff;
            --card-hover: #f0f2f4;
            --accent-color: #b91860;
            --accent-hover: #93104a;
            --warning-color: #ae681f;
            --error-color: #b9485b;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            transition: background 0.3s ease, color 0.3s ease;
        }

        /* Code styling for hostname */
        code {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            padding: 2px 2px;
            border-radius: 6px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            font-size: 0.8em;
            color: var(--accent-color);
            white-space: nowrap;
        }

        /* Header */
        .header {
            background:
                radial-gradient(circle at 12% -80%, rgba(255, 143, 190, 0.22), transparent 32%),
                linear-gradient(112deg, #302330 0%, #211820 58%, #3d2032 100%);
            border-bottom: 1px solid rgba(255, 255, 255, 0.18);
            padding: 12px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 28px rgba(4, 21, 32, 0.22);
            color: #ffffff;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .logo {
            width: 50px;
            height: 50px;
            padding: 5px;
            border-radius: 14px;
            background: rgba(255, 255, 255, 0.96);
            box-shadow: 0 8px 22px rgba(3, 23, 36, 0.25);
            line-height: 0;
            cursor: pointer;
        }

        .title-section h1 {
            font-size: 21px;
            font-weight: 780;
            color: #ffffff;
            margin-bottom: 0;
            letter-spacing: -0.03em;
        }

        .title-section h1 span {
            display: block;
            color: #e2b7cc;
            font-size: 11px;
            font-weight: 500;
            letter-spacing: 0.035em;
            line-height: 1.35;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .theme-toggle {
            background: rgba(255, 255, 255, 0.14);
            border: 1px solid rgba(255, 255, 255, 0.24);
            color: #ffffff;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .theme-toggle:hover {
            background: rgba(255, 255, 255, 0.22);
        }

        .settings-btn {
            background: rgba(255, 255, 255, 0.14);
            border: 1px solid rgba(255, 255, 255, 0.24);
            color: #ffffff;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.2s;
            display: flex;
            align-items: center;
        }

        .settings-btn:hover {
            background: rgba(255, 255, 255, 0.22);
        }

        /* Settings Modal */
        .settings-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            justify-content: center;
            align-items: center;
        }

        .settings-modal.show {
            display: flex;
        }

        .settings-dialog {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            width: 90%;
            max-width: 900px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }

        .settings-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .settings-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .settings-close {
            background: none;
            border: none;
            font-size: 24px;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .settings-close:hover {
            background: var(--bg-tertiary);
        }

        .settings-body {
            padding: 24px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 32px;
        }

        .settings-section {
            margin-bottom: 24px;
        }

        .settings-section:last-child {
            margin-bottom: 0;
        }

        /* Full width section for sections that need it */
        .settings-section.full-width {
            grid-column: 1 / -1;
        }

        .settings-section-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 12px;
        }

        .settings-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--border-color);
            gap: 16px;
        }

        .settings-item:last-child {
            border-bottom: none;
        }

        .settings-item-label {
            font-size: 14px;
            color: var(--text-primary);
        }

        .settings-item > div:first-child {
            flex: 1;
            min-width: 0;
        }

        .settings-item-description {
            font-size: 12px;
            color: var(--text-muted);
            margin-top: 4px;
        }

        /* Toggle Switch */
        .toggle-switch {
            position: relative;
            width: 48px;
            height: 26px;
            flex-shrink: 0;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            transition: 0.3s;
            border-radius: 26px;
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: var(--text-secondary);
            transition: 0.3s;
            border-radius: 50%;
        }

        input:checked + .toggle-slider {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
        }

        input:checked + .toggle-slider:before {
            transform: translateX(22px);
            background-color: white;
        }

        /* Settings Dropdown */
        .settings-select {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            width: 180px;
            flex-shrink: 0;
        }

        .settings-select:focus {
            outline: none;
            border-color: var(--accent-color);
        }

        /* Main Layout */
        .container {
            display: flex;
            height: calc(100vh - 75px);
            min-width: 0;
        }

        /* Sidebar */
        .sidebar {
            width: 350px;
            flex: 0 0 350px;
            background: var(--bg-secondary);
            border-right: 1px solid var(--border-color);
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            transition: width 0.25s ease, flex-basis 0.25s ease, padding 0.25s ease;
        }

        .sidebar.docked {
            width: 64px;
            flex-basis: 64px;
            padding: 12px 8px;
        }

        .panel {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 16px;
            overflow: visible;
        }

        .sidebar.docked .panel {
            margin-bottom: 10px;
            overflow: hidden;
        }

        .panel-header {
            padding: 14px 16px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            user-select: none;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background 0.2s;
        }

        .sidebar.docked .panel-header {
            justify-content: center;
            padding: 12px;
            border-bottom: none;
        }

        .panel-header:hover {
            background: var(--card-hover);
        }

        .panel-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .sidebar.docked .panel-title {
            gap: 0;
        }

        .sidebar.docked .panel-title-text,
        .sidebar.docked .panel-toggle {
            display: none;
        }

        .panel-icon {
            font-size: 16px;
        }

        .panel-toggle {
            color: var(--text-muted);
            font-size: 12px;
            transition: transform 0.2s;
        }

        .panel-toggle.collapsed {
            transform: rotate(-90deg);
        }

        .panel-content {
            padding: 16px;
            max-height: 1000px;
            transition: max-height 0.3s ease, opacity 0.3s ease;
            opacity: 1;
            overflow: visible;
        }

        .panel-content.collapsed {
            max-height: 0;
            opacity: 0;
            padding: 0 16px;
            overflow: hidden;
        }

        #apiKeyField {
            max-height: 100px;
            transition: max-height 0.3s ease, opacity 0.3s ease;
            opacity: 1;
            overflow: hidden;
        }

        #apiKeyField.collapsed {
            max-height: 0;
            opacity: 0;
        }

        #apiKeyToggle {
            transition: transform 0.2s;
        }

        #apiKeyToggle.collapsed {
            transform: rotate(-90deg);
        }

        .form-group {
            margin-bottom: 14px;
        }

        .form-group:last-child {
            margin-bottom: 0;
        }

        label {
            display: block;
            font-size: 12px;
            font-weight: 500;
            color: var(--text-secondary);
            margin-bottom: 6px;
            letter-spacing: 0.3px;
        }

        input[type="text"],
        input[type="number"],
        select,
        textarea {
            width: 100%;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 10px 12px;
            border-radius: 6px;
            font-size: 13px;
            font-family: inherit;
            transition: border 0.2s;
        }

        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: var(--primary-blue);
        }

        /* Prevent browser autofill blue background */
        input:-webkit-autofill,
        input:-webkit-autofill:hover,
        input:-webkit-autofill:focus {
            -webkit-box-shadow: 0 0 0 1000px var(--bg-tertiary) inset !important;
            -webkit-text-fill-color: var(--text-primary) !important;
            transition: background-color 5000s ease-in-out 0s;
        }

        /* Disabled input styling */
        input:disabled,
        select:disabled,
        textarea:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background: var(--bg-secondary);
            color: var(--text-muted);
        }

        textarea {
            resize: vertical;
            min-height: 80px;
            line-height: 1.5;
        }

        .btn {
            width: 100%;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            letter-spacing: 0.3px;
        }

        .btn-primary {
            background: var(--accent-color);
            color: white;
            border: 1px solid var(--accent-color);
        }

        .btn-primary:hover {
            background: var(--accent-hover);
            border-color: var(--accent-hover);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px var(--alive-red-ring);
        }

        /* Tab-style underline (for future use) */
        .tab-item {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: border-color 0.2s;
        }

        .tab-item.active {
            border-bottom-color: var(--accent-color);
        }

        .tab-item:hover {
            border-bottom-color: var(--accent-hover);
        }

        .btn-secondary {
            background: var(--bg-tertiary);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }

        .btn-secondary:hover {
            background: var(--card-hover);
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .icon-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 28px;
            height: 28px;
            padding: 0;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: var(--bg-tertiary);
            color: var(--text-primary);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .icon-btn:hover:not(:disabled) {
            background: var(--card-hover);
            border-color: var(--accent-color);
            transform: scale(1.1);
        }

        .icon-btn:active:not(:disabled) {
            transform: scale(0.95);
        }

        .icon-btn:disabled {
            cursor: not-allowed;
            opacity: 0.4;
            background: var(--bg-secondary);
        }

        .input-hint {
            font-size: 11px;
            color: var(--text-muted);
            margin-top: 4px;
        }

        /* Input Source Tabs */
        .input-source-tabs {
            display: flex;
            gap: 0;
            margin-bottom: 16px;
            border-bottom: 2px solid var(--border-color);
        }

        /* Beta Badge - Small and Rotated */
        .beta-badge {
            display: inline-block;
            background: var(--warning-color);
            color: #000;
            font-size: 7px;
            font-weight: 700;
            padding: 1px 1px;
            border-radius: 2px;
            margin-left: -6px;
            vertical-align: super;
            letter-spacing: 0.3px;
            transform: rotate(50deg);
            transform-origin: center;
        }

        .input-source-tab {
            flex: 1;
            padding: 10px 2px;
            background: transparent;
            border: none;
            border-bottom: 2px solid transparent;
            margin-bottom: -2px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            color: var(--text-muted);
            transition: all 0.2s;
        }

        .input-source-tab:hover {
            color: var(--text-primary);
            background: var(--alive-red-soft);
        }

        .input-source-tab.active {
            color: var(--accent-color);
            border-bottom-color: var(--accent-color);
        }

        /* Tooltip */
        .tooltip-wrapper {
            position: relative;
            display: inline-flex;
            align-items: baseline;
            gap: 6px;
        }

        .tooltip-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: var(--border-color);
            color: var(--text-muted);
            font-size: 10px;
            font-weight: 600;
            line-height: 1;
            cursor: help;
            transition: all 0.2s;
            flex-shrink: 0;
            transform: translateY(-1px);
        }

        .tooltip-icon:hover {
            background: var(--accent-color);
            color: white;
        }

        .tooltip-text {
            visibility: hidden;
            opacity: 0;
            position: fixed;
            padding: 12px 16px;
            background: var(--card-bg);
            border: 1px solid var(--accent-color);
            border-radius: 8px;
            font-size: 12px;
            line-height: 1.6;
            color: var(--text-primary);
            white-space: normal;
            width: 380px;
            max-width: calc(100vw - 40px);
            z-index: 10000;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
            transition: opacity 0.2s, visibility 0.2s;
            pointer-events: none;
        }

        .tooltip-text strong {
            color: var(--accent-color);
            font-weight: 600;
        }

        .tooltip-wrapper:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            min-height: 0;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }


        /* Status Badge */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 16px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-badge.connected {
            background: rgba(255, 255, 255, 0.2);
            color: #ffffff;
        }

        .status-badge.disconnected {
            background: rgba(255, 255, 255, 0.12);
            color: rgba(255, 255, 255, 0.76);
        }

        .status-badge.processing {
            background: rgba(255, 255, 255, 0.2);
            color: #ffffff;
        }

        /* Video Display */
        .video-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 20px;
            position: relative;
            display: flex;
            flex-direction: column;
            flex: 0 0 auto;
        }

        .video-card.waiting-for-stream {
            background: #000;
        }

        .video-card.waiting-for-stream video {
            visibility: hidden;
        }

        video {
            width: 100%;
            flex: 1;
            min-height: 240px;
            max-height: 100%;
            display: block;
            background: #000;
            transition: transform 0.3s ease;
            object-fit: contain;
            margin: 0;
            padding: 0;
        }

        /* Video Overlay Text */
        .video-overlay {
            position: absolute;
            left: 0;
            right: 0;
            padding: 16px 20px;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));
            color: white;
            font-size: 16px;
            line-height: 1.5;
            pointer-events: none;
            display: none;
            z-index: 10;
        }

        .video-overlay.top {
            top: 0;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));
        }

        .video-overlay.bottom {
            bottom: 0;
            background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));
        }

        .video-overlay.show {
            display: block;
        }

        video.mirrored {
            transform: scaleX(-1);
        }

        .video-controls {
            position: absolute;
            top: 12px;
            right: 12px;
            display: flex;
            gap: 8px;
            z-index: 10;
        }

        .video-control-btn {
            background: rgba(0, 0, 0, 0.7);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            backdrop-filter: blur(10px);
            transition: all 0.2s;
        }

        .video-control-btn:hover {
            background: rgba(0, 0, 0, 0.9);
            border-color: var(--accent-color);
        }

        .video-control-btn.active {
            background: var(--accent-color);
            border-color: var(--accent-color);
        }

        .fullscreen-prompt-overlay {
            position: absolute;
            bottom: max(18px, env(safe-area-inset-bottom));
            left: 18px;
            width: min(640px, calc(100vw - 36px));
            max-height: 72px;
            display: none;
            z-index: 102;
        }

        .video-card.fullscreen .fullscreen-prompt-overlay {
            display: block;
        }

        .fullscreen-prompt-overlay .chat-prompt-shell {
            background: rgba(255, 255, 255, 0.08);
            border-color: rgba(255, 255, 255, 0.22);
            backdrop-filter: blur(18px) saturate(145%);
            box-shadow: 0 10px 28px rgba(0, 0, 0, 0.12);
        }

        .fullscreen-prompt-overlay .chat-prompt-input {
            color: white;
            max-height: 48px;
            text-shadow: 0 1px 6px rgba(0, 0, 0, 0.7);
        }

        .video-card.fullscreen .fullscreen-prompt-overlay:has(.chat-prompt-shell.mobile-voice-mode) {
            bottom: max(32px, calc(env(safe-area-inset-bottom) + 24px));
            max-height: none;
        }

        .video-card.fullscreen .fullscreen-prompt-overlay.voice-panel-open {
            bottom: max(32px, calc(env(safe-area-inset-bottom) + 24px));
            max-height: none;
        }

        /* Big Start Button (centered on video) */
        .big-start-btn {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: min(140px, 25vh);
            height: min(140px, 25vh);
            max-width: 80%;
            max-height: 80%;
            border-radius: 16px;
            background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 52%, var(--alive-red-dark));
            border: none;
            color: white;
            font-size: 20px;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 12px 30px rgba(82, 24, 53, 0.36);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px;
            z-index: 100;
            opacity: 0.8;
            transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;
        }

        .big-start-btn:hover:not(:disabled):not(.animating) {
            transform: translate(-50%, -50%) scale(1.05);
            box-shadow: 0 16px 38px rgba(82, 24, 53, 0.46);
            opacity: 0.95;
        }

        .big-start-btn:active:not(:disabled):not(.animating) {
            transform: translate(-50%, -50%) scale(0.95);
        }

        .big-start-btn:disabled {
            opacity: 0.8;
            cursor: wait;
            transform: translate(-50%, -50%);
        }

        .big-start-btn i, .big-start-btn svg {
            width: 56px !important;
            height: 56px !important;
            flex-shrink: 0;
        }

        /* Animation to top-left corner when streaming starts */
        .big-start-btn.animating {
            animation: moveToCorner 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
            pointer-events: none;
        }

        @keyframes moveToCorner {
            0% {
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 140px;
                height: 140px;
                border-radius: 16px;
                background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 52%, var(--alive-red-dark));
                font-size: 20px;
                box-shadow: 0 12px 30px rgba(82, 24, 53, 0.36);
            }
            100% {
                top: 16px;
                left: 16px;
                transform: translate(0, 0);
                width: 48px;
                height: 48px;
                border-radius: 8px;
                background: linear-gradient(135deg, #FFA726, #FF9800);
                font-size: 0px;
                box-shadow: 0 4px 12px rgba(255, 152, 0, 0.5);
                opacity: 0;
            }
        }

        /* Hide after animation */
        .big-start-btn.streaming {
            display: none;
        }

        /* Small Stop button (top-left corner when streaming) */
        .small-stop-btn {
            position: absolute;
            top: 16px;
            left: 16px;
            width: 48px;
            height: 48px;
            border-radius: 8px;
            background: linear-gradient(135deg, #EF5350, #D32F2F) !important;
            border: none;
            color: white;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(239, 83, 80, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            transition: transform 0.3s ease, opacity 0.3s ease;
            z-index: 100;
            opacity: 0.7;
        }

        .small-stop-btn.show {
            display: flex;
        }

        .small-stop-btn:hover {
            background: linear-gradient(135deg, #EF5350, #D32F2F) !important;
            transform: scale(1.1);
            opacity: 1 !important;
        }

        .small-stop-btn:active {
            transform: scale(0.95);
        }

        .small-stop-btn i, .small-stop-btn svg {
            width: 30px !important;
            height: 30px !important;
            flex-shrink: 0;
        }

        /* Fullscreen button (top-right corner) */
        .fullscreen-btn {
            position: absolute;
            top: 12px;
            right: 12px;
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            cursor: pointer;
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            z-index: 99;
            opacity: 0.3;
        }

        .fullscreen-btn:hover {
            background: rgba(0, 0, 0, 0.8);
            border-color: var(--accent-color);
            opacity: 0.8;
            transform: scale(1.05);
        }

        .fullscreen-btn svg, .fullscreen-btn i {
            width: 20px !important;
            height: 20px !important;
        }

        .quick-camera-btn {
            position: absolute;
            top: 12px;
            right: 60px;
            min-width: 92px;
            height: 40px;
            padding: 0 12px;
            border-radius: 999px;
            background: rgba(255, 255, 255, 0.14);
            border: 1px solid rgba(255, 255, 255, 0.28);
            color: white;
            cursor: pointer;
            backdrop-filter: blur(12px);
            display: none;
            align-items: center;
            justify-content: center;
            gap: 6px;
            font-size: 12px;
            font-weight: 650;
            z-index: 101;
            opacity: 0.86;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.18);
        }

        .quick-camera-btn svg,
        .quick-camera-btn i {
            width: 16px !important;
            height: 16px !important;
            flex-shrink: 0;
        }

        .quick-camera-btn:hover {
            background: rgba(255, 255, 255, 0.22);
            border-color: rgba(255, 255, 255, 0.4);
        }

        .quick-camera-btn:disabled {
            opacity: 0.45;
            cursor: not-allowed;
        }

        /* Fullscreen mode styles */
        .video-card.fullscreen {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100vw !important;
            height: 100vh !important;
            max-width: 100vw !important;
            max-height: 100vh !important;
            z-index: 9999;
            margin: 0;
            border-radius: 0;
            border: none;
        }

        .video-card.fullscreen video {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .video-card.fullscreen .fullscreen-btn {
            opacity: 0.7;
            background: rgba(0, 0, 0, 0.8);
            z-index: 101;
        }

        .video-card.fullscreen .fullscreen-btn:hover {
            opacity: 1;
            transform: scale(1.1);
        }

        /* Keep controls above VLM overlay in fullscreen so shrink/mirror remain clickable */
        .video-card.fullscreen .video-controls {
            z-index: 101;
        }

        /* Responses overlay in fullscreen mode */
        .fullscreen-vlm-overlay {
            position: absolute;
            top: 76px;
            left: 18px;
            width: min(480px, calc(100vw - 36px));
            padding: 10px 12px;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.18);
            border-radius: 10px;
            backdrop-filter: blur(18px) saturate(145%);
            color: white;
            z-index: 98;
            display: none;
            max-height: calc(1.45em * 4 + 22px);
            overflow: hidden;
            pointer-events: none;
        }

        .video-card.fullscreen .fullscreen-vlm-overlay {
            display: block;
        }

        .fullscreen-vlm-overlay .vlm-title {
            display: none;
            font-size: 12px;
            font-weight: 600;
            color: var(--accent-color);
            margin-bottom: 6px;
            align-items: center;
            gap: 8px;
            text-shadow: 0 1px 6px rgba(0, 0, 0, 0.65);
        }

        .fullscreen-vlm-overlay .vlm-content {
            font-size: 13px;
            line-height: 1.45;
            font-weight: 500;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
            overflow: hidden;
            white-space: pre-line;
            word-break: break-word;
            text-shadow: 0 2px 8px rgba(0, 0, 0, 0.8);
        }

        .fullscreen-vlm-overlay .vlm-metrics {
            display: none;
            font-size: 12px;
            color: rgba(255, 255, 255, 0.7);
            margin-top: 8px;
            gap: 16px;
        }

        /* Generation Result */
        .result-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            transition: opacity 0.3s ease, filter 0.3s ease;
        }

        .result-card.cloud-api {
            opacity: 0.5;
            filter: grayscale(0.3);
        }

        #vlmOutputCard {
            display: flex;
            flex-direction: column;
            flex: 1 1 0;
            min-height: 0;
        }

        .api-preset-item {
            padding: 10px 16px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .api-preset-item:hover {
            background: var(--hover-bg);
        }

        .api-preset-item strong {
            color: var(--text-primary);
            font-size: 13px;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 16px;
            margin-bottom: 16px;
            min-width: 0;
        }

        .result-header-left {
            flex: 1 1 auto;
            min-width: 0;
        }

        .result-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-secondary);
            letter-spacing: 0.3px;
            margin-bottom: 6px;
        }

        .result-subtitle {
            font-size: 12px;
            color: var(--text-muted);
            line-height: 1.4;
        }

        .tts-speaking-line {
            display: none;
            margin-top: 6px;
            font-size: 12px;
            line-height: 1.35;
            color: var(--text-secondary);
            max-width: 100%;
            white-space: normal;
            overflow: hidden;
            overflow-wrap: anywhere;
            max-height: calc(1.35em * 2);
        }

        .tts-speaking-line.show {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
        }

        .tts-speaking-line strong {
            color: var(--accent-color);
            font-weight: 600;
        }

        .vlm-history {
            position: relative;
            height: 420px;
            max-height: 420px;
            overflow-y: auto;
            overflow-x: hidden;
            overscroll-behavior: contain;
            padding-top: 18px;
            padding-right: 4px;
            padding-bottom: 36px;
            scroll-behavior: auto;
            overflow-anchor: none;
            display: block;
            -webkit-overflow-scrolling: touch;
            scrollbar-gutter: stable;
            contain: layout paint;
        }

        /* Stick messages to the bottom: the first real bubble absorbs leftover
           vertical space so content grows upward from the bottom like a chat app. */
        .vlm-history > .result-prompt:first-of-type,
        .vlm-history > .result-text:first-of-type {
            margin-top: auto;
        }

        /* Prevent flex from shrinking bubbles to fit the container — without this,
           items collapse instead of overflowing and the scrollbar never appears. */
        .vlm-history > .result-prompt,
        .vlm-history > .result-text {
            flex-shrink: 0;
        }

        .vlm-history::before {
            content: none;
            position: sticky;
            top: 0;
            display: block;
            height: 44px;
            margin-bottom: -44px;
            background: linear-gradient(to bottom, var(--card-bg), transparent);
            pointer-events: none;
            z-index: 3;
        }

        .result-prompt {
            font-size: 15px;
            line-height: 1.5;
            color: var(--text-primary);
            margin-top: 16px;
            margin-bottom: 12px;
            margin-left: auto;
            margin-right: 0;
            padding: 6px 12px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 16px 16px 4px 16px;
            max-width: 85%;
            word-wrap: break-word;
        }

        .result-text {
            font-size: 15px;
            line-height: 1.5;
            color: var(--text-primary);
            transition: opacity 3s ease, transform 0.3s ease, box-shadow 0.3s ease;
            min-height: 120px;
            margin-top: 12px;
            margin-left: 0;
            margin-right: auto;
            padding: 6px 12px;
            background: linear-gradient(135deg, rgba(231, 35, 116, 0.12) 0%, rgba(82, 24, 53, 0.06) 100%);
            border: 1px solid rgba(231, 35, 116, 0.24);
            border-radius: 16px 16px 16px 4px;
            max-width: 90%;
            word-wrap: break-word;
            position: relative; /* For absolute positioning of button */
        }

        .vlm-history .result-prompt:first-of-type {
            margin-top: 0;
        }

        .result-text-content {
            /* Content wrapper - this is what gets updated, not the parent */
            width: 100%;
        }

        .vlm-history-shell {
            width: 100%;
            max-width: 100%;
            flex: 1 1 auto;
            min-height: 0;
            padding: 0;
            background: transparent;
            border: none;
            border-radius: 0;
            display: flex;
            flex-direction: column;
        }

        .vlm-history .result-text {
            display: block;
            min-height: 0;
            margin-top: 8px;
            margin-bottom: 12px;
            position: static;
        }

        .result-text.background-result {
            width: min(100%, 760px);
            border-color: rgba(255, 167, 38, 0.34);
            background: linear-gradient(135deg, rgba(255, 167, 38, 0.14), rgba(231, 35, 116, 0.06));
        }

        .background-result-shell {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .background-result-header {
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }

        .background-result-icon {
            width: 28px;
            height: 28px;
            flex: 0 0 28px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            color: var(--warning-color);
            background: rgba(255, 167, 38, 0.16);
        }

        .background-result-title {
            flex: 1 1 auto;
            min-width: 0;
            font-weight: 700;
            color: var(--text-primary);
        }

        .background-result-question {
            margin-top: 3px;
            font-size: 13px;
            font-weight: 400;
            color: var(--text-secondary);
            overflow-wrap: anywhere;
        }

        .background-result-action {
            flex: 0 0 auto;
            border: 1px solid rgba(255, 167, 38, 0.34);
            border-radius: 6px;
            padding: 5px 10px;
            background: var(--card-bg);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
        }

        .background-result-action:hover {
            background: var(--card-hover);
        }

        .background-result-action:disabled {
            opacity: 0.55;
            cursor: default;
        }

        .background-origin-action {
            width: 30px;
            height: 30px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .background-origin-action i,
        .background-origin-action svg {
            width: 15px !important;
            height: 15px !important;
        }

        .background-jump-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid rgba(255, 167, 38, 0.18);
        }

        .background-jump-question {
            min-width: 0;
            flex: 1 1 auto;
            display: flex;
            align-items: baseline;
            gap: 6px;
            padding: 6px 9px;
            border-radius: 8px;
            background: rgba(255, 167, 38, 0.10);
            border: 1px solid rgba(255, 167, 38, 0.18);
            color: var(--text-primary);
        }

        .background-jump-question-label {
            flex: 0 0 auto;
            color: var(--warning-color);
            font-size: 12px;
            font-weight: 800;
        }

        .background-jump-question-text {
            min-width: 0;
            overflow-wrap: anywhere;
            color: var(--text-primary);
            font-size: 13px;
            line-height: 1.35;
            font-weight: 700;
        }

        .background-jump-button {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border: 1px solid rgba(255, 167, 38, 0.42);
            border-radius: 999px;
            padding: 6px 11px;
            background: linear-gradient(135deg, rgba(255, 167, 38, 0.18), rgba(231, 35, 116, 0.12));
            color: var(--text-primary);
            cursor: pointer;
            font-size: 13px;
            font-weight: 700;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
            white-space: nowrap;
            flex: 0 0 auto;
        }

        .background-jump-button:hover {
            background: linear-gradient(135deg, rgba(255, 167, 38, 0.25), rgba(231, 35, 116, 0.18));
        }

        .background-jump-button i,
        .background-jump-button svg {
            width: 15px !important;
            height: 15px !important;
        }

        .background-result.jump-highlight {
            box-shadow: 0 0 0 2px rgba(255, 167, 38, 0.58), 0 0 24px rgba(255, 167, 38, 0.22);
        }

        .result-prompt.jump-highlight {
            box-shadow: 0 0 0 2px rgba(255, 167, 38, 0.58), 0 0 24px rgba(255, 167, 38, 0.22);
        }

        .result-text.background-summary-message {
            width: min(100%, 720px);
            background: linear-gradient(135deg, rgba(255, 167, 38, 0.13), rgba(55, 65, 81, 0.08));
            border-color: rgba(255, 167, 38, 0.32);
            box-shadow: inset 3px 0 0 rgba(255, 167, 38, 0.62);
        }

        .background-summary-message {
            display: flex;
            flex-direction: column;
            gap: 9px;
        }

        .background-summary-label {
            display: inline-flex;
            width: fit-content;
            align-items: center;
            gap: 6px;
            border: 1px solid rgba(255, 167, 38, 0.22);
            border-radius: 999px;
            padding: 4px 9px;
            background: rgba(255, 167, 38, 0.12);
            color: var(--warning-color);
            font-size: 12px;
            font-weight: 800;
        }

        .background-summary-label i,
        .background-summary-label svg {
            width: 14px !important;
            height: 14px !important;
        }

        .background-summary-body {
            min-width: 0;
        }

        .background-summary-body > *:first-child {
            margin-top: 0;
        }

        .background-summary-body > *:last-child {
            margin-bottom: 0;
        }

        .standard-rich-response {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .standard-rich-explanation,
        .standard-rich-chart,
        .standard-rich-html {
            min-width: 0;
        }

        .background-rich-content {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .background-rich-tabs {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }

        .background-rich-tab {
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 4px 10px;
            background: var(--bg-tertiary);
            color: var(--text-secondary);
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
        }

        .background-rich-tab.active {
            color: var(--text-primary);
            border-color: rgba(255, 167, 38, 0.42);
            background: rgba(255, 167, 38, 0.14);
        }

        .background-view-shell {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .background-view-toolbar {
            display: flex;
            justify-content: flex-end;
            gap: 6px;
        }

        .background-rich-action {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border: 1px solid rgba(255, 167, 38, 0.34);
            border-radius: 6px;
            padding: 4px 9px;
            background: var(--card-bg);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
        }

        .background-rich-action:hover {
            background: var(--card-hover);
        }

        .background-rich-action i {
            width: 14px;
            height: 14px;
        }

        .background-raw-shell {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .background-raw-toolbar {
            display: flex;
            justify-content: flex-end;
            gap: 6px;
        }

        .background-raw-copy {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border: 1px solid rgba(255, 167, 38, 0.34);
            border-radius: 6px;
            padding: 4px 9px;
            background: var(--card-bg);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
        }

        .background-raw-copy:hover {
            background: var(--card-hover);
        }

        .background-raw-block {
            max-height: calc(1.45em * 7 + 20px);
            margin: 0;
            padding: 10px 12px;
            overflow: auto;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: rgba(12, 10, 10, 0.72);
            color: var(--text-primary);
            font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
            font-size: 13px;
            line-height: 1.45;
            white-space: pre;
        }

        .background-html-frame {
            width: 100%;
            min-height: 420px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: #fff;
        }

        .background-preview-warning {
            padding: 8px 10px;
            border: 1px solid rgba(255, 167, 38, 0.32);
            border-radius: 8px;
            background: rgba(255, 167, 38, 0.12);
            color: var(--text-secondary);
            font-size: 12px;
            line-height: 1.45;
        }

        .background-chart {
            width: 100%;
            height: 280px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-secondary);
        }

        .background-modal-backdrop[hidden] {
            display: none;
        }

        .background-modal-backdrop {
            position: fixed;
            inset: 0;
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
            background: rgba(8, 6, 6, 0.54);
            backdrop-filter: blur(18px) saturate(145%);
            -webkit-backdrop-filter: blur(18px) saturate(145%);
        }

        .background-modal-dialog {
            width: min(1120px, calc(100vw - 48px));
            max-height: calc(100vh - 48px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            border: 1px solid rgba(255, 167, 38, 0.34);
            border-radius: 8px;
            background: rgba(24, 18, 18, 0.96);
            box-shadow: 0 24px 80px rgba(0, 0, 0, 0.48);
        }

        .background-modal-header {
            flex: 0 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            padding: 14px 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .background-modal-title {
            margin: 0;
            font-size: 16px;
            font-weight: 700;
            color: var(--text-primary);
        }

        .background-modal-close {
            width: 34px;
            height: 34px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: var(--card-bg);
            color: var(--text-primary);
            cursor: pointer;
        }

        .background-modal-close:hover {
            background: var(--card-hover);
        }

        .background-modal-body {
            flex: 1 1 auto;
            min-height: 0;
            overflow: auto;
            padding: 16px;
        }

        .background-modal-dialog .background-raw-block {
            max-height: calc(100vh - 180px);
        }

        .background-modal-dialog .background-html-frame {
            min-height: min(760px, calc(100vh - 180px));
            height: calc(100vh - 180px);
        }

        .background-modal-dialog .background-chart {
            height: min(680px, calc(100vh - 200px));
        }

        body.background-modal-open {
            overflow: hidden;
        }

        .prompt-editor-inline {
            margin-top: auto;
            flex: 0 0 auto;
            padding-top: 14px;
            border-top: 1px solid var(--border-color);
        }

        .chat-prompt-shell {
            position: relative;
            display: flex;
            align-items: flex-end;
            gap: 8px;
            padding: 10px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 18px;
            box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03);
        }

        .chat-prompt-shell::before {
            content: "";
            position: absolute;
            inset: -0.5rem;
            border-radius: 24px;
            background:
                linear-gradient(180deg, rgba(9, 31, 45, 0.82), rgba(11, 45, 57, 0.98)),
                radial-gradient(circle at 50% 0, rgba(231, 35, 116, 0.18), transparent 48%);
            opacity: 0;
            pointer-events: none;
            z-index: 0;
            transform: translateY(8px);
            transition: opacity 0.18s ease, transform 0.18s ease;
        }

        .chat-prompt-shell::after {
            content: "";
            position: absolute;
            left: 28px;
            right: 28px;
            bottom: calc(50% - 10px);
            height: 22px;
            opacity: 0;
            pointer-events: none;
            z-index: 1;
            background:
                repeating-linear-gradient(
                    90deg,
                    transparent 0 6px,
                    var(--alive-red-light) 6px 9px,
                    transparent 9px 15px
                );
            mask-image: linear-gradient(
                90deg,
                rgba(0, 0, 0, 0.15) 0%,
                #000 18%,
                #000 82%,
                rgba(0, 0, 0, 0.15) 100%
            );
            -webkit-mask-image: linear-gradient(
                90deg,
                rgba(0, 0, 0, 0.15) 0%,
                #000 18%,
                #000 82%,
                rgba(0, 0, 0, 0.15) 100%
            );
            transform-origin: center;
        }

        .chat-prompt-shell > * {
            position: relative;
            z-index: 2;
        }

        .chat-prompt-shell.voice-ripple-active {
            isolation: isolate;
            background: transparent;
            border-color: rgba(231, 35, 116, 0.28);
            box-shadow: 0 -12px 36px rgba(4, 32, 45, 0.28);
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            user-select: none;
            touch-action: none;
        }

        .chat-prompt-shell.voice-ripple-active::before {
            opacity: 1;
            transform: translateY(0);
        }

        .chat-prompt-shell.voice-ripple-active::after {
            opacity: 1;
            animation: voiceBars 0.82s ease-in-out infinite;
        }

        .video-card.fullscreen .fullscreen-prompt-overlay .chat-prompt-shell.voice-ripple-active::before {
            inset: -1rem -0.5rem -0.5rem;
        }

        @keyframes voiceBars {
            0%, 100% { transform: scaleY(0.42); filter: brightness(0.9); }
            35% { transform: scaleY(1); filter: brightness(1.18); }
            68% { transform: scaleY(0.62); filter: brightness(1); }
        }

        .chat-prompt-shell:focus-within {
            border-color: rgba(231, 35, 116, 0.5);
            box-shadow: 0 0 0 3px rgba(231, 35, 116, 0.13);
        }

        .chat-prompt-action {
            width: 34px;
            height: 34px;
            border-radius: 50%;
            border: 1px solid var(--border-color);
            background: var(--card-bg);
            color: var(--text-secondary);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            flex: 0 0 auto;
            cursor: pointer;
            transition: background 0.2s, border-color 0.2s, color 0.2s, transform 0.2s;
        }

        .chat-prompt-action:hover,
        .chat-prompt-action.active {
            background: var(--card-hover);
            border-color: var(--accent-color);
            color: var(--text-primary);
            transform: translateY(-1px);
        }

        .chat-prompt-action:disabled {
            cursor: not-allowed;
            opacity: 0.45;
            transform: none;
            box-shadow: none;
        }

        .chat-prompt-action .lucide {
            width: 17px;
            height: 17px;
        }

        .chat-prompt-action.send {
            background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 58%, var(--alive-red-dark));
            border-color: rgba(255, 255, 255, 0.12);
            color: white;
            box-shadow: 0 8px 18px rgba(82, 24, 53, 0.28);
        }

        .chat-prompt-action.send:hover {
            background: linear-gradient(135deg, #f6539a, var(--alive-red) 54%, var(--alive-red-dark));
            border-color: rgba(255, 255, 255, 0.18);
            box-shadow: 0 10px 24px rgba(82, 24, 53, 0.36);
        }

        .chat-prompt-action.send .lucide {
            stroke: white;
        }

        .speech-label {
            display: none;
            font-size: 14px;
            font-weight: 600;
            line-height: 1;
            white-space: nowrap;
        }

        .voice-wave {
            display: none;
            align-items: center;
            justify-content: center;
            gap: 2px;
            width: 18px;
            height: 18px;
        }

        .voice-wave span {
            width: 3px;
            height: 6px;
            border-radius: 999px;
            background: currentColor;
            animation: voiceWave 0.72s ease-in-out infinite;
        }

        .voice-wave span:nth-child(2) {
            animation-delay: 0.12s;
        }

        .voice-wave span:nth-child(3) {
            animation-delay: 0.24s;
        }

        .voice-wave span:nth-child(4) {
            animation-delay: 0.36s;
        }

        @keyframes voiceWave {
            0%, 100% {
                height: 5px;
            }
            50% {
                height: 17px;
            }
        }

        .speech-control.recording {
            background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 58%, var(--alive-red-dark));
            border-color: rgba(255, 255, 255, 0.14);
            color: white;
            box-shadow: 0 8px 18px rgba(82, 24, 53, 0.28);
        }

        .speech-control.recording .lucide {
            stroke: white;
        }

        .speech-control.recording .mic-icon {
            display: none;
        }

        .speech-control.recording .voice-wave {
            display: inline-flex;
        }

        .chat-prompt-action.speech:disabled {
            opacity: 0.65;
            transform: none;
        }

        .chat-prompt-input {
            flex: 1;
            min-height: 34px;
            max-height: 120px;
            padding: 7px 4px;
            resize: none;
            border: none !important;
            background: transparent !important;
            box-shadow: none !important;
            color: var(--text-primary);
            font-size: 14px;
            line-height: 1.45;
        }

        .chat-prompt-input:focus {
            outline: none;
            border: none !important;
            box-shadow: none !important;
        }

        .voice-mode-bar {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            padding: 10px 0 4px;
        }
        .voice-mode-button {
            display: inline-flex;
            align-items: center;
            gap: 7px;
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 9px 14px;
            background: var(--bg-secondary);
            color: var(--text-primary);
            font: inherit;
            font-size: 13px;
            cursor: pointer;
        }
        .voice-mode-button[aria-pressed="true"] {
            border-color: var(--accent-color);
            color: var(--accent-color);
        }
        .voice-mode-button:disabled { opacity: 0.5; cursor: default; }
        .voice-mode-button svg { width: 17px; height: 17px; }
        .voice-language-tabs { display: inline-flex; padding: 3px; gap: 2px; border: 1px solid var(--border-color); border-radius: 20px; background: var(--bg-secondary); }
        .voice-language-tab { min-width: 38px; min-height: 34px; padding: 5px 9px; border: 0; border-radius: 16px; background: transparent; color: var(--text-secondary); font: inherit; font-size: 13px; cursor: pointer; }
        .voice-language-tab[aria-checked="true"] { background: var(--bg-primary); color: var(--text-primary); box-shadow: 0 1px 4px #0002; font-weight: 600; }
        .voice-language-tab:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; }
        .voice-mode-status { color: var(--text-secondary); font-size: 12px; }
        .fullscreen-prompt-overlay .voice-mode-bar {
            border-radius: 12px;
            background: var(--card-bg);
            padding: 8px 10px;
        }

        .prompt-popover {
            position: absolute;
            bottom: calc(100% + 8px);
            left: 0;
            right: auto;
            width: min(360px, calc(100vw - 40px));
            max-height: 320px;
            padding: 8px;
            overflow-y: auto;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            box-shadow: 0 16px 38px rgba(0, 0, 0, 0.28);
            z-index: 30;
        }

        .prompt-popover.hidden {
            display: none;
        }

        .prompt-preset-option {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            padding: 9px 10px;
            border: none;
            border-radius: 8px;
            background: transparent;
            color: var(--text-primary);
            font: inherit;
            font-size: 13px;
            text-align: left;
            cursor: pointer;
        }

        .prompt-preset-copy {
            display: flex;
            flex-direction: column;
            gap: 8px;
            min-width: 0;
        }

        .prompt-preset-copy .primary {
            font-size: 15px;
            line-height: 1.35;
            color: var(--text-primary);
        }

        .prompt-preset-copy .secondary {
            font-size: 13px;
            line-height: 1.35;
            color: var(--text-secondary);
        }

        .prompt-preset-option:hover,
        .prompt-preset-option.selected {
            background: var(--hover-bg);
        }

        .prompt-preset-option .check {
            width: 16px;
            color: var(--accent-color);
            opacity: 0;
            flex: 0 0 auto;
        }

        .prompt-preset-option.selected .check {
            opacity: 1;
        }

        /* Embedded markdown toggle button */
        .markdown-toggle-embedded {
            position: absolute;
            top: -1px; /* Overlap balloon's top border */
            right: -1px; /* Overlap balloon's right border */
            background: var(--bg-secondary);
            border-top: 1px solid rgba(231, 35, 116, 0.24);
            border-right: 1px solid rgba(231, 35, 116, 0.24);
            border-left: 1px solid rgba(231, 35, 116, 0.24);
            border-bottom: 1px solid rgba(231, 35, 116, 0.24);
            border-radius: 0 16px 0 0; /* Match top-right corner of balloon */
            color: var(--text-secondary);
            padding: 4px 10px;
            font-size: 11px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            transition: all 0.2s;
            z-index: 10;
            line-height: 1.2;
        }

        .markdown-toggle-embedded:hover {
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }

        .markdown-toggle-embedded .lucide {
            width: 12px;
            height: 12px;
        }

        /* Copy to clipboard button - overlay style in lower right */
        .copy-button-embedded {
            position: absolute;
            bottom: 8px;
            right: 8px;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(8px);
            border: 1px solid rgba(255, 255, 255, 0.25);
            border-radius: 6px;
            color: var(--text-primary);
            padding: 6px 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            z-index: 10;
            opacity: 0.4;
        }

        .copy-button-embedded:hover {
            opacity: 1;
            background: rgba(255, 255, 255, 0.25);
            border-color: rgba(255, 255, 255, 0.4);
            transform: scale(1.05);
        }

        .copy-button-embedded:active {
            transform: scale(0.95);
        }

        .copy-button-embedded .lucide {
            width: 14px;
            height: 14px;
        }

        .copy-button-embedded.copied {
            background: rgba(231, 35, 116, 0.58);
            border-color: rgba(231, 35, 116, 0.38);
        }

        .copy-button-embedded.copied .lucide {
            animation: checkmark 0.3s ease;
        }

        @keyframes checkmark {
            0% { transform: scale(0.8); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }

        /* Markdown styling */
        .result-text-content.markdown-rendered h1,
        .result-text-content.markdown-rendered h2,
        .result-text-content.markdown-rendered h3,
        .result-text.markdown-rendered h1,
        .result-text.markdown-rendered h2,
        .result-text.markdown-rendered h3 {
            color: var(--text-primary);
            margin-top: 16px;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .result-text-content.markdown-rendered h1,
        .result-text.markdown-rendered h1 {
            font-size: 1.5em;
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 8px;
        }

        .result-text-content.markdown-rendered h2,
        .result-text.markdown-rendered h2 {
            font-size: 1.3em;
        }

        .result-text-content.markdown-rendered h3,
        .result-text.markdown-rendered h3 {
            font-size: 1.1em;
        }

        .result-text-content.markdown-rendered p,
        .result-text.markdown-rendered p {
            margin: 8px 0;
        }

        .result-text-content.markdown-rendered ul,
        .result-text-content.markdown-rendered ol,
        .result-text.markdown-rendered ul,
        .result-text.markdown-rendered ol {
            margin: 8px 0;
            padding-left: 24px;
        }

        .result-text-content.markdown-rendered li,
        .result-text.markdown-rendered li {
            margin: 4px 0;
        }

        .result-text-content.markdown-rendered code,
        .result-text.markdown-rendered code {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            font-size: 0.9em;
            color: var(--accent-color);
        }

        .result-text-content.markdown-rendered pre,
        .result-text.markdown-rendered pre {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 12px;
            overflow-x: auto;
            margin: 12px 0;
        }

        .result-text-content.markdown-rendered pre code,
        .result-text.markdown-rendered pre code {
            background: transparent;
            border: none;
            padding: 0;
            color: var(--text-primary);
            font-size: 0.85em;
        }

        .result-text-content.markdown-rendered blockquote,
        .result-text.markdown-rendered blockquote {
            border-left: 4px solid var(--accent-color);
            padding-left: 16px;
            margin: 12px 0;
            color: var(--text-secondary);
            font-style: italic;
        }

        .result-text-content.markdown-rendered table,
        .result-text.markdown-rendered table {
            border-collapse: collapse;
            width: 100%;
            margin: 12px 0;
            font-size: 0.9em;
        }

        .result-text-content.markdown-rendered table th,
        .result-text-content.markdown-rendered table td,
        .result-text.markdown-rendered table th,
        .result-text.markdown-rendered table td {
            border: 1px solid var(--border-color);
            padding: 8px 12px;
            text-align: left;
        }

        .result-text-content.markdown-rendered table th,
        .result-text.markdown-rendered table th {
            background: var(--bg-tertiary);
            font-weight: 600;
            color: var(--text-primary);
        }

        .result-text-content.markdown-rendered table tr:nth-child(even),
        .result-text.markdown-rendered table tr:nth-child(even) {
            background: var(--bg-secondary);
        }

        .result-text-content.markdown-rendered strong,
        .result-text.markdown-rendered strong {
            font-weight: 600;
            color: var(--text-primary);
        }

        .result-text-content.markdown-rendered em,
        .result-text.markdown-rendered em {
            font-style: italic;
        }

        .result-text-content.markdown-rendered a,
        .result-text.markdown-rendered a {
            color: var(--accent-color);
            text-decoration: none;
        }

        .result-text-content.markdown-rendered a:hover,
        .result-text.markdown-rendered a:hover {
            text-decoration: underline;
        }

        .result-text-content.markdown-rendered hr,
        .result-text.markdown-rendered hr {
            border: none;
            border-top: 1px solid var(--border-color);
            margin: 16px 0;
        }

        .result-text-content.markdown-rendered .katex,
        .result-text.markdown-rendered .katex {
            color: var(--text-primary);
            font-size: 1.02em;
        }

        .result-text-content.markdown-rendered .katex-display,
        .result-text.markdown-rendered .katex-display {
            overflow-x: auto;
            overflow-y: hidden;
            margin: 12px 0;
            padding: 4px 0;
        }

        .result-text-content.markdown-rendered .markdown-math-fallback,
        .result-text.markdown-rendered .markdown-math-fallback {
            color: var(--text-primary);
            font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
            white-space: pre-wrap;
        }

        .result-text.fade {
            opacity: 0.4;
        }

        .vlm-history-shell.fade {
            opacity: 1;
        }

        .result-text.new-message {
            animation: popIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        .result-text.new-message.with-glow {
            animation: popInWithGlow 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        @keyframes popIn {
            0% {
                transform: scale(0.95);
                opacity: 0.8;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        @keyframes popInWithGlow {
            0% {
                transform: scale(0.95);
                opacity: 0.8;
                box-shadow: 0 0 0 0 rgba(231, 35, 116, 0.38);
            }
            50% {
                box-shadow: 0 0 20px 4px rgba(231, 35, 116, 0.42);
            }
            100% {
                transform: scale(1);
                opacity: 1;
                box-shadow: 0 0 0 0 rgba(231, 35, 116, 0);
            }
        }

        /* VLM Metrics */
        .metrics-inline {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: var(--text-secondary);
            flex: 0 0 auto;
            white-space: nowrap;
        }

        .result-header-metrics {
            display: flex;
            align-items: center;
            gap: 16px;
            flex: 0 0 auto;
            max-width: 100%;
        }

        .metric-item {
            display: flex;
            align-items: center;
            gap: 4px;
            flex: 0 0 auto;
        }

        .metric-value {
            font-weight: 600;
            color: var(--accent-color);
        }

        /* Info Box */
        .info-box {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 16px;
            font-size: 13px;
            line-height: 1.6;
            color: var(--text-secondary);
        }

        .info-box h3 {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 10px;
        }

        .info-box ul {
            list-style-position: inside;
            padding-left: 0;
        }

        .info-box li {
            margin-bottom: 6px;
        }

        /* Scrollbar styling */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--bg-secondary);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--bg-tertiary);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--border-color);
        }

        /* Lucide icon styling */
        .lucide {
            width: 1em;
            height: 1em;
            vertical-align: middle;
        }

        .logo .lucide,
        .logo svg {
            width: 100%;
            height: 100%;
            filter: none;
        }

        /* Logo color - theme-aware (subtle glow on light background) */
        body.light-theme .logo .lucide,
        body.light-theme .logo svg {
            filter: none;
        }

        .icon-btn .lucide,
        .settings-btn .lucide,
        .video-control-btn .lucide {
            width: 16px;
            height: 16px;
        }

        .panel-icon .lucide {
            width: 18px;
            height: 18px;
        }

        .result-title .lucide {
            width: 20px;
            height: 20px;
            margin-right: 6px;
        }

        /* Default: Neutral icon colors (clean two-tone system) */
        .panel-icon svg,
        .panel-icon .lucide,
        .result-title svg,
        .result-title .lucide {
            stroke: var(--text-secondary) !important;
        }

        /* Colorful icon strokes (only when enabled) - Dark theme */
        body.colorful-focus .panel-icon:has([data-lucide="globe"]) svg,
        body.colorful-focus .panel-icon:has([data-lucide="globe"]) .lucide {
            stroke: rgb(34, 211, 238) !important; /* Softer cyan */
        }

        body.colorful-focus .panel-icon:has([data-lucide="video"]) svg,
        body.colorful-focus .panel-icon:has([data-lucide="video"]) .lucide {
            stroke: rgb(59, 130, 246) !important; /* Blue */
        }

        body.colorful-focus .panel-icon:has([data-lucide="edit-3"]) svg,
        body.colorful-focus .panel-icon:has([data-lucide="edit-3"]) .lucide {
            stroke: rgb(251, 191, 36) !important; /* Yellow/Orange */
        }

        body.colorful-focus .result-title:has([data-lucide="bot"]) svg,
        body.colorful-focus .result-title:has([data-lucide="bot"]) .lucide {
            stroke: rgb(168, 85, 247) !important; /* Purple */
        }


        /* Colorful icon strokes - Light theme (darker variants) */
        body.light-theme.colorful-focus .panel-icon:has([data-lucide="globe"]) svg,
        body.light-theme.colorful-focus .panel-icon:has([data-lucide="globe"]) .lucide {
            stroke: rgb(6, 182, 212) !important; /* Darker cyan */
        }

        body.light-theme.colorful-focus .panel-icon:has([data-lucide="video"]) svg,
        body.light-theme.colorful-focus .panel-icon:has([data-lucide="video"]) .lucide {
            stroke: rgb(37, 99, 235) !important; /* Darker blue */
        }

        body.light-theme.colorful-focus .panel-icon:has([data-lucide="edit-3"]) svg,
        body.light-theme.colorful-focus .panel-icon:has([data-lucide="edit-3"]) .lucide {
            stroke: rgb(217, 119, 6) !important; /* Darker orange */
        }

        body.light-theme.colorful-focus .result-title:has([data-lucide="bot"]) svg,
        body.light-theme.colorful-focus .result-title:has([data-lucide="bot"]) .lucide {
            stroke: rgb(126, 34, 206) !important; /* Darker purple */
        }


        /* Settings icon - theme-aware */
        .settings-btn .lucide {
            stroke: #ffffff;
        }
        body.light-theme .settings-btn .lucide {
            stroke: #ffffff;
        }

        /* Theme toggle icons - Yellow/Gold */
        #themeIcon .lucide {
            stroke: #ffffff;
        }
        body.light-theme #themeIcon .lucide {
            stroke: #ffffff;
        }

        /* Video control buttons - Teal */
        .video-control-btn .lucide {
            stroke: rgb(20, 184, 166);
        }
        body.light-theme .video-control-btn .lucide {
            stroke: rgb(13, 148, 136); /* Darker teal for light mode */
        }

        /* Action button icons (play, stop) - White for contrast on red button */
        .btn-primary .lucide {
            stroke: white !important;
        }
        body.light-theme .btn-primary .lucide {
            stroke: white !important;
        }

        .btn-secondary .lucide {
            stroke: var(--text-primary) !important;
        }

        /* Input fields - Focus and Apply animations */
        #promptText,
        #processEvery,
        #apiBaseUrl,
        #apiKey,
        #modelSelect,
        #cameraSelect,
        #rtspUrl {
            transition: all 0.3s ease;
        }

        /* Default: Neutral white focus glow (when colorful is disabled) */
        #promptText:focus,
        #processEvery:focus,
        #cameraSelect:focus,
        #apiBaseUrl:focus,
        #apiKey:focus,
        #modelSelect:focus,
        #rtspUrl:focus {
            border-color: rgba(200, 200, 200, 0.6) !important;
            box-shadow: 0 0 0 2px rgba(200, 200, 200, 0.15),
                        0 0 8px rgba(200, 200, 200, 0.2) !important;
            outline: none;
        }

        /* Colorful focus glows (only when enabled) */
        body.colorful-focus #promptText:focus {
            border-color: rgb(251, 191, 36) !important;
            box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.3),
                        0 0 12px rgba(251, 191, 36, 0.4) !important;
        }

        body.colorful-focus #processEvery:focus,
        body.colorful-focus #cameraSelect:focus,
        body.colorful-focus #rtspUrl:focus {
            border-color: rgb(59, 130, 246) !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3),
                        0 0 12px rgba(59, 130, 246, 0.4) !important;
        }

        body.colorful-focus #apiBaseUrl:focus,
        body.colorful-focus #apiKey:focus,
        body.colorful-focus #modelSelect:focus {
            border-color: rgb(34, 211, 238) !important;
            box-shadow: 0 0 0 3px rgba(34, 211, 238, 0.25),
                        0 0 12px rgba(34, 211, 238, 0.3) !important;
        }

        /* Bright flash animation when applied (on blur) */
        @keyframes settingApplied {
            0% {
                box-shadow: 0 0 0 0 rgba(231, 35, 116, 0.62),
                           0 0 20px rgba(231, 35, 116, 0.52);
            }
            50% {
                box-shadow: 0 0 0 6px rgba(231, 35, 116, 0.24),
                           0 0 30px rgba(231, 35, 116, 0.38);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(231, 35, 116, 0),
                           0 0 0 rgba(231, 35, 116, 0);
            }
        }

        #promptText.applied,
        #processEvery.applied,
        #apiBaseUrl.applied,
        #apiKey.applied,
        #modelSelect.applied,
        #cameraSelect.applied,
        #rtspUrl.applied {
            animation: settingApplied 0.6s ease-out;
        }


        /* ===== GRADIENT STROKES (Optional - gradients may not work reliably with Lucide) ===== */
        /*
        .panel-icon [data-lucide="globe"] svg {
            stroke: url(#gradient-cyan) !important;
        }

        .panel-icon [data-lucide="video"] svg {
            stroke: url(#gradient-blue) !important;
        }

        .panel-icon [data-lucide="edit-3"] svg {
            stroke: url(#gradient-orange) !important;
        }

        .result-title [data-lucide="bot"] svg {
            stroke: url(#gradient-purple) !important;
        }

        */

        /* Responsive Layout - Side by Side on Wide Screens */
        @media (min-width: 1400px) {
            .main-content {
                display: grid;
                grid-template-columns: 1fr 1fr;
                grid-template-rows: minmax(0, 1fr) auto;
                gap: 20px;
                align-items: start;
                max-height: calc(100vh - 100px);
            }

            /* Video card in left column */
            .video-card {
                grid-column: 1;
                grid-row: 1;
                margin-bottom: 0;
                align-self: stretch;
                max-height: 100%;
            }

            /* Responses card in right column */
            #vlmOutputCard {
                grid-column: 2;
                grid-row: 1;
                margin-bottom: 0;
                max-height: 100%;
                min-height: 0;
                overflow: hidden;
                align-self: stretch;
                display: flex;
                flex-direction: column;
            }

            #vlmOutputCard .vlm-history-shell {
                flex: 1;
                min-height: 0;
                display: flex;
                flex-direction: column;
            }

            #vlmOutputCard .vlm-history {
                flex: 1;
                min-height: 0;
                height: auto;
                max-height: none;
            }

        }

        @media (min-width: 1600px) {
            .main-content {
                grid-template-columns: 1.2fr 1fr;
            }
        }

        /* Responsive adjustments for smaller screens */
        @media (max-width: 1024px) {
            .sidebar {
                width: 280px;
            }

            .header-title {
                font-size: 18px;
            }
        }

        @media (max-width: 768px) {
            body {
                min-height: 100dvh;
                overflow-x: hidden;
            }

            .header {
                padding: 10px 12px;
                gap: 10px;
            }

            .header-left {
                min-width: 0;
                gap: 10px;
            }

            .logo {
                width: 38px;
                height: 38px;
                padding: 4px;
                border-radius: 10px;
                flex: 0 0 auto;
            }

            .title-section h1 {
                font-size: 18px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .header-right {
                gap: 8px;
                flex: 0 0 auto;
            }

            .status-badge {
                max-width: 104px;
                padding: 5px 8px;
                font-size: 10px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .theme-toggle {
                width: 34px;
                height: 34px;
                padding: 0;
                justify-content: center;
            }

            .theme-toggle #themeText {
                display: none;
            }

            .settings-btn {
                width: 34px;
                height: 34px;
                padding: 0;
                justify-content: center;
            }

            .settings-dialog {
                width: calc(100vw - 20px);
                max-height: calc(100dvh - 28px);
                border-radius: 10px;
            }

            .container {
                display: flex;
                flex-direction: column;
                height: auto;
                min-height: calc(100dvh - 59px);
            }

            .main-content {
                order: 1;
                width: 100%;
                height: calc(100dvh - 59px);
                min-height: calc(100dvh - 59px);
                padding: 10px;
                gap: 10px;
                overflow: visible;
                display: flex;
                flex-direction: column;
            }

            .video-card {
                order: 1;
                border-radius: 8px;
                margin-bottom: 0;
                min-height: 0;
                height: clamp(240px, 43dvh, 420px);
                flex: 0 0 auto;
            }

            .video-card video {
                min-height: 0;
                height: 100%;
                flex: 1 1 auto;
            }

            .video-controls {
                top: 54px !important;
                right: 8px;
            }

            .video-card.fullscreen .video-controls {
                top: 56px !important;
                right: 8px;
            }

            .video-control-btn {
                padding: 7px 9px;
                font-size: 12px;
            }

            .fullscreen-btn {
                top: 8px;
                right: 8px;
                width: 36px;
                height: 36px;
                opacity: 0.7;
            }

            .quick-camera-btn {
                display: inline-flex;
                top: 8px;
                right: 52px;
                height: 36px;
                min-width: 62px;
                padding: 0 8px;
            }

            .video-card.fullscreen .quick-camera-btn {
                display: inline-flex;
                top: 8px;
                right: 52px;
                height: 36px;
                min-width: 62px;
                padding: 0 8px;
            }

            .small-stop-btn {
                top: 10px;
                left: 10px;
                width: 42px;
                height: 42px;
            }

            .video-overlay {
                padding: 10px 12px;
                font-size: 13px;
                line-height: 1.45;
            }

            .result-card {
                order: 2;
                border-radius: 8px;
                padding: 12px;
                margin-bottom: 0;
            }

            #vlmOutputCard {
                min-height: 0;
                flex: 1 1 0;
            }

            #vlmOutputCard .result-header {
                margin-bottom: 8px;
                gap: 8px;
            }

            #vlmOutputCard .result-title {
                font-size: 12px;
                margin-bottom: 2px;
            }

            #vlmOutputCard .result-subtitle {
                font-size: 11px;
            }

            .metrics-inline {
                gap: 8px;
                font-size: 10px;
                flex-wrap: wrap;
                justify-content: flex-end;
            }

            .vlm-history-shell {
                flex: 1 1 auto;
            }

            .vlm-history {
                height: clamp(140px, 24dvh, 260px);
                max-height: clamp(140px, 24dvh, 260px);
                padding-top: 8px;
                padding-bottom: 18px;
                scrollbar-gutter: auto;
            }

            .result-prompt,
            .result-text {
                max-width: 94%;
                font-size: 14px;
                padding: 7px 10px;
            }

            .markdown-toggle-embedded {
                padding: 4px 8px;
            }

            .copy-button-embedded {
                bottom: 6px;
                right: 6px;
            }

            .prompt-editor-inline {
                position: sticky;
                bottom: 0;
                z-index: 40;
                margin: auto -12px -12px;
                padding: 8px 10px calc(8px + env(safe-area-inset-bottom));
                background: var(--card-bg);
                border-top: 1px solid var(--border-color);
                box-shadow: 0 -10px 24px rgba(0, 0, 0, 0.16);
            }

            .chat-prompt-shell {
                gap: 6px;
                padding: 8px;
                border-radius: 16px;
            }

            .chat-prompt-action {
                width: 50px;
                height: 50px;
            }

            .chat-prompt-action .lucide {
                width: 24px;
                height: 24px;
            }

            .voice-wave {
                width: 24px;
                height: 24px;
                gap: 3px;
            }

            .voice-wave span {
                width: 4px;
            }

            .voice-wave span {
                animation-name: voiceWaveMobile;
            }

            @keyframes voiceWaveMobile {
                0%, 100% {
                    height: 7px;
                }
                50% {
                    height: 24px;
                }
            }

            .chat-prompt-shell.mobile-voice-mode #promptPresetBtn,
            .chat-prompt-shell.mobile-voice-mode #promptSendBtn,
            .chat-prompt-shell.mobile-voice-mode .chat-prompt-input,
            .chat-prompt-shell.mobile-voice-mode .prompt-popover {
                display: none;
            }

            .chat-prompt-shell.mobile-voice-mode {
                min-height: 156px;
                align-items: center;
                justify-content: center;
                border-radius: 24px;
            }

            .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech {
                position: absolute;
                left: 50%;
                top: 24px;
                width: auto;
                height: auto;
                min-height: 0;
                padding: 0;
                transform: translateX(-50%);
                border-radius: 999px;
                gap: 8px;
                border: none;
                background: transparent;
                box-shadow: none;
                color: rgba(255, 255, 255, 0.72);
                touch-action: none;
                user-select: none;
                -webkit-user-select: none;
                -webkit-touch-callout: none;
            }

            .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .speech-label {
                display: inline;
                font-size: 14px;
                font-weight: 500;
                letter-spacing: 0;
            }

            .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .voice-wave,
            .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .mic-icon {
                display: none;
            }

            .chat-prompt-shell.mobile-voice-mode::after {
                left: 18px;
                right: 18px;
                bottom: 44px;
                height: 28px;
            }

            .chat-prompt-input {
                min-width: 0;
                min-height: 54px;
                max-height: 144px;
                font-size: 15px;
                padding: 12px 2px;
            }

            .prompt-popover {
                width: calc(100vw - 20px);
                max-height: min(320px, 55dvh);
                left: -8px;
            }

            .sidebar {
                order: 2;
                width: 100%;
                flex: 0 0 auto;
                padding: 10px;
                border-right: none;
                border-top: 1px solid var(--border-color);
                overflow: visible;
            }

            .sidebar.docked {
                width: 100%;
                flex-basis: auto;
                padding: 8px 10px;
                display: grid;
                grid-template-columns: repeat(2, minmax(0, 1fr));
                gap: 8px;
            }

            .sidebar .panel {
                margin-bottom: 10px;
            }

            .sidebar.docked .panel {
                margin-bottom: 0;
            }

            .sidebar.docked .panel-header {
                min-height: 44px;
            }

            .panel-content {
                padding: 12px;
            }

            .big-start-btn {
                width: min(96px, 24vw);
                height: min(96px, 24vw);
                font-size: 16px;
            }

            .big-start-btn i, .big-start-btn svg {
                width: min(40px, 8vh) !important;
                height: min(40px, 8vh) !important;
            }
        }

        @media (max-width: 420px) {
            .header {
                padding: 8px 10px;
            }

            .title-section h1 {
                font-size: 16px;
            }

            .status-badge {
                max-width: 86px;
            }

            .main-content {
                padding: 8px;
            }

            .video-card {
                height: clamp(220px, 40dvh, 360px);
            }

            .result-card {
                padding: 10px;
            }

            .prompt-editor-inline {
                margin: auto -10px -10px;
                padding-left: 8px;
                padding-right: 8px;
            }

            .chat-prompt-shell {
                gap: 5px;
                padding: 7px;
            }

            .chat-prompt-action {
                width: 48px;
                height: 48px;
            }

            .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech {
                min-height: 0;
            }

            .chat-prompt-action .lucide {
                width: 23px;
                height: 23px;
            }
        }

        /* ALIVE header surfaces. */
        body, body.light-theme { background: var(--bg-primary); }
        .header {
            min-height: 74px;
            padding: 10px 24px;
            background: #fff;
            color: #20242a;
            border-bottom: 1px solid #e3e6e9;
            box-shadow: none;
            backdrop-filter: none;
        }
        .header-left { min-width: 0; gap: 24px; }
        .title-section { min-width: 0; }
        .title-section h1 { color: #20242a; font-size: 20px; font-weight: 650; }
        .title-section h1 span { color: #69727e; }
        .theme-toggle, .settings-btn {
            border-radius: 9px;
            color: #525a65;
            background: #fff;
            border-color: #e3e6e9;
        }
        .theme-toggle:hover, .settings-btn:hover { background: #f5f6f7; }
        .settings-btn .lucide, body.light-theme .settings-btn .lucide,
        #themeIcon .lucide, body.light-theme #themeIcon .lucide { stroke: currentColor; }
        .status-badge { border: 1px solid #e3e6e9; letter-spacing: 0.035em; }
        .status-badge::before {
            content: "";
            width: 6px; height: 6px; flex: 0 0 auto;
            border-radius: 50%; background: currentColor;
        }
        .status-badge.connected { color: #177245; background: #f4faf6; }
        .status-badge.disconnected { color: #69727e; background: #f7f8f9; }
        .status-badge.processing { color: #956015; background: #fffbf3; }
        .sidebar { background: var(--bg-secondary); }
        .main-content { gap: 18px; padding: 22px; }
        .panel, .settings-dialog { border-radius: 15px; }
        .sidebar.docked .panel { border-radius: 12px; }
        .panel-header { border-radius: 14px 14px 0 0; }
        .panel-title { font-weight: 650; }
        input[type="text"], input[type="number"], select, textarea {
            border-radius: 9px; min-height: 39px;
        }
        .btn, .icon-btn { border-radius: 9px; }
        .input-source-tabs { gap: 6px; border-bottom: 0; }
        .input-source-tab {
            margin: 0; border: 1px solid var(--border-color);
            border-radius: 9px; background: var(--bg-tertiary);
        }
        .input-source-tab.active { border-color: var(--accent-color); background: var(--alive-red-soft); }
        .video-card, .result-card {
            border-radius: 18px;
            border-color: var(--border-color);
            box-shadow: 0 4px 20px rgba(20, 30, 40, 0.045);
        }
        body.light-theme .video-card.waiting-for-stream { background: #f5f6f7; }
        .big-start-btn {
            background: #303640;
            border: 1px solid #444c58;
            box-shadow: 0 8px 24px rgba(20, 30, 40, 0.12);
        }
        .big-start-btn:hover:not(:disabled):not(.animating) {
            box-shadow: 0 12px 28px rgba(20, 30, 40, 0.18);
        }
        .result-title { color: var(--text-primary); font-weight: 650; }
        .result-prompt { background: var(--bg-tertiary); }
        .vlm-history .result-text, body.light-theme .vlm-history .result-text {
            background: var(--bg-secondary); border-color: var(--border-color);
        }
        .chat-prompt-shell { border-radius: 17px; }
        .chat-prompt-shell:focus-within {
            border-color: var(--text-muted); box-shadow: 0 0 0 3px rgba(110, 120, 132, 0.10);
        }
        .chat-prompt-action.send { background: #303640; box-shadow: none; }
        .chat-prompt-action.send:hover:not(:disabled) { background: #444c58; }
        :is(button, input, select, textarea, .logo):focus-visible {
            outline: 2px solid var(--accent-color); outline-offset: 3px;
        }
        @media (max-width: 768px) {
            .header { min-height: 60px; padding: 8px 12px; }
            .header-left { gap: 9px; }
            .title-section h1 span {
                max-width: 32ch; white-space: nowrap; overflow: hidden;
                text-overflow: ellipsis; font-size: 10px;
            }
            .main-content { padding: 10px; gap: 10px; }
            .video-card, .result-card { border-radius: 12px; }
        }
        @media (max-width: 420px) {
            .title-section h1 { font-size: 17px; }
            .title-section h1 span { display: none; }
        }
        /* ALIVE wordmark and voice controls. */
        .logo { flex: 0 0 auto; width: 148px; height: 48px; padding: 0; border-radius: 0; background: transparent; box-shadow: none; }
        .logo img { display: block; width: 100%; height: 100%; object-fit: contain; }
        #speechBtn, .quick-camera-btn[hidden] { display: none !important; }
        .voice-mode-bar { padding: 10px 0 0; gap: 8px; }
        .voice-mode-button { min-height: 44px; padding: 10px 13px; }
        .voice-mode-button[aria-pressed="true"] { background: var(--alive-red-soft); }
        .voice-toggle-icon { display: inline-flex; }
        .voice-toggle-icon svg { width: 19px; height: 19px; }
        .voice-mode-status { flex: 1; min-width: 120px; }
        @media (max-width: 768px) {
            .header { display: grid; grid-template-columns: 1fr auto; gap: 8px 12px; }
            .header-left { display: contents; }
            .logo { grid-column: 1; grid-row: 1; width: 120px; height: 40px; padding: 0; }
            .header-right { grid-column: 2; grid-row: 1; }
            .title-section { grid-column: 1 / -1; grid-row: 2; }
            .title-section h1 { font-size: 18px; }
            .title-section h1 span { display: none; }
            .voice-mode-status { flex-basis: 100%; font-size: 11px; }
        }

        /* ALIVE workspace: independent branding, responsive video + conversation. */
        :root { --alive-red:#a8cd18; --alive-red-dark:#86a510; --alive-red-light:#c7e75c;
            --alive-red-soft:rgba(168,205,24,.12); --alive-red-ring:rgba(168,205,24,.24);
            --alive-red-shadow:rgba(6,36,70,.15); --accent-color:#b5d944; --accent-hover:#d4ed88;
            --bg-primary:#101d2e; --bg-secondary:#14253a; --bg-tertiary:#20344b;
            --card-bg:#14253a; --border-color:#2b415a; --text-primary:#edf3f9; --text-secondary:#bbc8d6; --text-muted:#92a7bb; }
        body.light-theme { --bg-primary:#f5f6f2; --bg-secondary:#f8f9f6; --bg-tertiary:#edf0e8;
            --card-bg:#fff; --card-hover:#eef2e7; --border-color:#e0e5da;
            --text-primary:#102d50; --text-secondary:#53665f; --text-muted:#7a8784;
            --accent-color:#17486c; --accent-hover:#092b50; }
        body { font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif; }
        .header { min-height:82px; padding:12px 36px; background:var(--card-bg); color:var(--text-primary); border-color:var(--border-color); }
        .header-left { gap:26px; }
        .logo { width:156px; height:52px; background:#fff; border-radius:9px; }
        .title-section { border-left:1px solid var(--border-color); padding-left:24px; }
        .title-section h1 { color:var(--text-primary); font-size:14px; letter-spacing:.01em; font-weight:600; }
        .title-section h1 span { color:var(--text-muted); font-size:11px; margin-top:4px; }
        .theme-toggle,.settings-btn { background:var(--bg-secondary); color:var(--text-secondary); border-color:var(--border-color); height:36px; }
        .status-badge { font-size:10px; padding:8px 11px; letter-spacing:.08em; }
        .status-badge.connected { background:#eef5d7; color:#507009; border-color:#dce9b5; }
        .alive-intro { max-width:1700px; margin:auto; padding:32px 36px 26px; display:flex; justify-content:space-between; align-items:center; gap:24px; }
        .alive-eyebrow { font-size:10px; letter-spacing:.16em; font-weight:700; color:var(--text-muted); display:flex; align-items:center; gap:8px; }
        .alive-eyebrow span { background:#a8cd18; width:7px; height:7px; border-radius:50%; }
        .alive-intro h2 { font-size:clamp(26px,2.6vw,38px); line-height:1.15; letter-spacing:-.045em; font-weight:600; margin:11px 0 10px; }
        .alive-intro p { color:var(--text-secondary); font-size:13px; line-height:1.6; }
        .alive-session-chip { display:flex; align-items:center; gap:12px; border:1px solid var(--border-color); padding:13px 18px; border-radius:14px; background:var(--card-bg); }
        .alive-spark { font-size:32px; color:#8eaf12; }
        .alive-session-chip strong { display:block; font-size:12px; letter-spacing:.08em; }
        .alive-session-chip div span { display:block; font-size:11px; color:var(--text-muted); margin-top:5px; }
        .container { max-width:1700px; margin:0 auto; padding:16px 24px 24px; height:calc(100dvh - 82px); min-height:500px; gap:12px; }
        .sidebar { border:1px solid var(--border-color); border-radius:18px; background:var(--card-bg); }
        .sidebar.docked { width:52px; flex-basis:52px; padding:12px 6px; }
        .sidebar.docked .panel { background:var(--bg-secondary); border-color:transparent; }
        .main-content { min-width:0; padding:0; display:grid; grid-template-columns:minmax(0,1.4fr) minmax(350px,1fr); grid-template-rows:minmax(0,1fr); gap:20px; overflow:visible; }
        .video-card,.result-card { border-radius:22px; margin:0; box-shadow:0 8px 24px rgba(17,41,36,.035); }
        .video-card:not(.fullscreen) { height:100%; min-height:360px; width:100%; background:#10283f; border:1px solid #203d57; }
        body.light-theme .video-card.waiting-for-stream { background:#10283f; }
        .video-card video { width:100%; height:100%; object-fit:contain; }
        .alive-view-label { position:absolute; top:22px; left:22px; color:#d5e3e9; z-index:4; font-size:10px; font-weight:600; letter-spacing:.15em; display:flex; align-items:center; gap:7px; pointer-events:none; }
        .alive-view-label span { width:6px; height:6px; background:#a8cd18; border-radius:50%; }
        .alive-camera-note { position:absolute; left:20px; right:20px; top:29%; text-align:center; color:#fff; font-size:clamp(17px,1.5vw,24px); letter-spacing:-.025em; pointer-events:none; z-index:3; }
        .alive-camera-note small { display:block; margin-top:10px; color:#9cb0c2; font-size:12px; letter-spacing:0; }
        .video-card:has(.big-start-btn.streaming) .alive-camera-note,.video-card:has(.big-start-btn.animating) .alive-camera-note { display:none; }
        .big-start-btn { border-radius:40px; background:#b5d933; border:1px solid #b5d933; color:#193218; font-size:14px; padding:17px 27px; gap:9px; box-shadow:0 5px 22px #0002; }
        .big-start-btn:hover:not(:disabled):not(.animating) { background:#c5e658; box-shadow:0 8px 28px #0003; }
        .big-start-btn i,.big-start-btn svg { width:19px; height:19px; }
        .result-card { padding:24px; min-width:0; }
        .result-title { font-size:17px; color:var(--text-primary); letter-spacing:-.02em; }
        .result-subtitle { font-size:11px; margin-top:6px; color:var(--text-muted); }
        #resultText { background:transparent; border:0; margin-top:18px; }
        #resultTextContent:empty::before { content:'A conversation starts with a shared view. Open your camera, then ask ALIVE a question — or tell it what to watch for.'; display:block; max-width:29ch; margin:48px auto; text-align:center; color:var(--text-muted); font-size:14px; line-height:1.85; }
        .vlm-history .result-text,body.light-theme .vlm-history .result-text { border-radius:14px; background:var(--bg-secondary); }
        .prompt-editor-inline { margin:auto -24px -24px; padding:16px; border-top:1px solid var(--border-color); background:var(--card-bg); border-radius:0 0 22px 22px; }
        .chat-prompt-shell { border-radius:16px; background:var(--bg-secondary); border-color:var(--border-color); }
        .chat-prompt-shell:focus-within { border-color:#99b851; box-shadow:0 0 0 3px rgba(168,205,24,.13); }
        .chat-prompt-action.send { background:#102f55; color:white; border-radius:12px; }
        .chat-prompt-action.send:hover:not(:disabled) { background:#204b78; }
        .voice-mode-bar { flex-wrap:wrap; }
        .voice-mode-button { font-size:11px; min-height:34px; padding:7px 9px; border-radius:9px; }
        .voice-mode-status { font-size:10px; color:var(--text-muted); }
        .fullscreen .alive-view-label { display:none; }
        @media (max-width:1100px) and (min-width:769px) { .main-content { grid-template-columns:minmax(0,1fr) minmax(320px,1fr); gap:14px; } .alive-session-chip { display:none; } }
        @media (max-width:768px) {
            .header { display:flex; min-height:66px; padding:9px 16px; gap:8px; }
            .header-left { display:flex; gap:0; } .logo { width:126px; height:42px; } .title-section { display:none; }
            .header-right { display:flex; gap:6px; } .theme-toggle { padding:7px; } #themeText { display:none; }
            .status-badge { font-size:8px; padding:7px; } .alive-intro { padding:22px 18px 20px; }
            .alive-intro h2 { font-size:29px; } .alive-intro p { font-size:12px; max-width:34ch; } .alive-eyebrow { font-size:8px; }
            .alive-session-chip { display:none; } .container { height:auto; min-height:0; padding:0 12px 20px; display:flex; flex-direction:column; gap:10px; }
            .sidebar.docked { width:100%; flex:0 0 auto; height:46px; padding:4px 7px; border-radius:12px; }
            .main-content { display:flex; flex-direction:column; padding:0; gap:12px; overflow:visible; }
            .video-card:not(.fullscreen) { height:clamp(260px,43dvh,420px); min-height:260px; border-radius:18px; }
            .alive-camera-note { top:26%; font-size:18px; } .big-start-btn { padding:14px 23px; }
            #vlmOutputCard { min-height:420px; flex:0 0 auto; padding:18px; border-radius:18px; }
            .prompt-editor-inline { margin:auto -18px -18px; padding:12px; border-radius:0 0 18px 18px; }
            .voice-mode-status { flex-basis:100%; } .alive-view-label { top:17px; left:17px; }
        }
        @media (prefers-reduced-motion:reduce) { *,*::before,*::after { animation-duration:.01ms!important; transition-duration:.01ms!important; } }


        #bigStartBtn:not(.streaming):not(.animating) { width:auto; height:auto; min-width:166px; min-height:52px; flex-direction:row; border-radius:40px; font-size:14px; padding:15px 24px; }
        #bigStartBtn:not(.streaming):not(.animating) svg { width:20px; height:20px; }
        .video-card:has(#bigStartBtn:not(.streaming):not(.animating)) video { background:transparent; }
        #resultTextContent:has(> .alive-empty) { display:flex; align-items:center; justify-content:center; }
        .alive-empty { max-width:30ch; color:var(--text-muted); text-align:center; font-size:14px; line-height:1.85; padding:25px 10px; }
        @media (max-width:768px) {
            .main-content { height:auto; min-height:0; }
            #vlmOutputCard { min-height:440px; }
            #vlmOutputCard .result-title { font-size:17px; }
            .alive-camera-note { top:23%; }
            #bigStartBtn:not(.streaming):not(.animating) { top:59%; }
            .prompt-editor-inline { position:static!important; bottom:auto; box-shadow:none; }
            #resultText { min-height:180px; flex:1; }
        }


        /* Compact workspace: the viewport is devoted to camera and conversation. */
        .conversation-brand { display:block; width:126px; height:42px; object-fit:contain; background:#fff; border-radius:6px; }
        #modelName[hidden] { display:none!important; }
        @media (max-width:768px) {
            .container { padding-top:12px; }
            .conversation-brand { width:114px; height:38px; }
        }

    
        /* Icon-only ALIVE brand mark, cropped from the original logo. */
        .alive-mark {
            display: inline-block;
            width: 24px;
            height: 24px;
            flex: 0 0 auto;
            overflow: hidden;
            background: #fff;
            border-radius: 4px;
            vertical-align: middle;
        }
        .background-summary-label .alive-mark {
            width: 18px !important;
            height: 18px !important;
        }
        .background-result-icon .alive-mark {
            width: 22px;
            height: 22px;
        }

    
        /* Demo production palette: film/src/FilmV8.tsx. */
        body {
            font-family: "Helvetica Neue", "PingFang SC", -apple-system, sans-serif;
        }
        body.light-theme {
            --bg-primary: #EDF2F7;
            --bg-secondary: #F5F8FC;
            --bg-tertiary: #EDF3FB;
            --card-bg: #FFFFFF;
            --card-hover: #EAF3FF;
            --border-color: #E0E7EF;
            --text-primary: #092B57;
            --text-secondary: #617287;
            --text-muted: #617287;
            --accent-color: #092B57;
            --accent-hover: #173F71;
            --alive-red-soft: rgba(9,43,87,.07);
            --alive-red-ring: rgba(9,43,87,.18);
        }
        body.light-theme .header { background: #EDF2F7; }
        body.light-theme .logo { background: transparent; }
        body.light-theme .logo img { mix-blend-mode: multiply; }
        body.light-theme .video-card,
        body.light-theme .video-card.waiting-for-stream {
            background: #081321;
            border-color: #173454;
            box-shadow: 0 18px 45px #17345416;
        }
        body.light-theme .result-card {
            background: #FFFFFF;
            border-color: #E0E7EF;
            box-shadow: 0 18px 45px #1734540A;
        }
        body.light-theme .result-prompt {
            background: #EAF3FF;
            color: #092B57;
            border-color: #99BCE6;
        }
        body.light-theme .vlm-history > .result-text:not(.background-result):not(.background-summary-message) {
            background: #092B57;
            color: #FFFFFF;
            border-color: #173F71;
            --text-primary: #FFFFFF;
            --text-secondary: #DCE8F6;
            --text-muted: #CBD7E5;
            --accent-color: #B7D6FA;
            --bg-tertiary: #173F71;
            --border-color: #456387;
        }
        body.light-theme .chat-prompt-shell:focus-within {
            border-color: #99BCE6;
            box-shadow: 0 0 0 3px #6A95C522;
        }
        body.light-theme .chat-prompt-action.send { background: #092B57; }
        body.light-theme .chat-prompt-action.send:hover:not(:disabled) { background: #173F71; }
        body.light-theme .theme-toggle:hover,
        body.light-theme .settings-btn:hover { background: #EAF3FF; }
        body.light-theme .voice-mode-button[aria-pressed="true"],
        body.light-theme .input-source-tab.active {
            background: #EAF3FF;
            border-color: #99BCE6;
            color: #092B57;
        }
        body.light-theme .status-badge.disconnected {
            background: #F5F8FC; color: #617287; border-color: #E0E7EF;
        }
        body.light-theme .alive-mark { mix-blend-mode: multiply; }

    /* UI language and per-browser TTS voice selection. */
.ui-language-control { display:inline-flex; align-items:center; padding:3px; border:1px solid var(--border-color); border-radius:10px; background:var(--bg-secondary); flex-shrink:0; }
.ui-language-control button { border:0; background:transparent; color:var(--text-secondary); padding:5px 8px; min-height:28px; border-radius:7px; cursor:pointer; font:600 11px "Helvetica Neue","PingFang SC",sans-serif; }
.ui-language-control button[aria-pressed="true"] { background:var(--card-bg); color:var(--text-primary); box-shadow:0 1px 4px #092B5718; }
.tts-voice-control { display:inline-flex; align-items:center; gap:6px; color:var(--text-secondary); font-size:11px; margin:0; }
.tts-voice-control select { min-height:34px; width:112px; padding:6px 8px; border:1px solid var(--border-color); border-radius:9px; background:var(--bg-secondary); color:var(--text-primary); font-size:11px; cursor:pointer; }
.tts-voice-control select:disabled { opacity:.6; cursor:wait; }
html[lang="zh-CN"] .status-badge { letter-spacing:0; }
@media(max-width:768px) {
    .header { flex-wrap:wrap; }
    .header-right { flex-wrap:wrap; justify-content:flex-end; }
    .ui-language-control button { padding:4px 6px; }
    .header .logo { width:105px; height:35px; }
    .voice-mode-status { flex-basis:100%; }
}
@media(max-width:360px) { .header { padding-left:12px; padding-right:12px; } .header .logo { width:90px; } .header-right { gap:4px; } .ui-language-control button { padding:4px; } }

.admission-status { font-size:10px; font-weight:600; color:#507009; background:#eef5d7; border:1px solid #dce9b5; border-radius:999px; padding:8px 10px; white-space:nowrap; }
.admission-status[data-busy="true"] { color:#895818; background:#fff4df; border-color:#ead4ad; }
@media(max-width:768px) { .admission-status { font-size:9px; padding:6px 8px; } .header-right { max-width:100%; } }

</style>

    <!-- SVG Gradient Definitions (for gradient strokes) -->
    <svg width="0" height="0" style="position: absolute;">
        <defs>
            <!-- Cyan gradient -->
            <linearGradient id="gradient-cyan" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:rgb(34, 211, 238);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(6, 182, 212);stop-opacity:1" />
            </linearGradient>

            <!-- Blue gradient -->
            <linearGradient id="gradient-blue" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:rgb(96, 165, 250);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(59, 130, 246);stop-opacity:1" />
            </linearGradient>

            <!-- Orange/Yellow gradient -->
            <linearGradient id="gradient-orange" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:rgb(251, 191, 36);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(245, 158, 11);stop-opacity:1" />
            </linearGradient>

            <!-- Purple gradient -->
            <linearGradient id="gradient-purple" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:rgb(192, 132, 252);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(168, 85, 247);stop-opacity:1" />
            </linearGradient>

            <!-- alive brand gradient -->
            <linearGradient id="gradient-green" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:rgb(255, 143, 190);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(213, 27, 105);stop-opacity:1" />
            </linearGradient>
        </defs>
    </svg>

    <!-- Lucide Icons - Load before body scripts -->
    <script src="https://unpkg.com/lucide@latest"></script>
    <!-- Markdown rendering libraries -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
    <script>
        const demoStorage = {
            getItem: key => localStorage.getItem('alive-demo:' + key),
            setItem: (key, value) => localStorage.setItem('alive-demo:' + key, value),
            removeItem: key => localStorage.removeItem('alive-demo:' + key)
        };

        document.title = 'ALIVE';

        // Initialize Lucide icons immediately when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => lucide.createIcons());
        } else {
            lucide.createIcons();
        }
    </script>
</head>
<body class="light-theme">
    <!-- Header -->
    <div class="header">
        <div class="header-left">
            <div class="logo" id="jdLogo" role="button" tabindex="0" aria-label="Refresh page">
                <img src="/images/alive.png?v=1" alt="ALIVE" width="2048" height="683">
            </div>
        </div>
        <div class="header-right">
            <span class="status-badge disconnected" id="connectionStatus">Disconnected</span>
            <button class="settings-btn" id="settingsBtn" title="Settings">
                <i data-lucide="settings"></i>
            </button>
            <button class="theme-toggle" id="themeToggle">
                <span id="themeIcon">
                    <i data-lucide="moon"></i>
                </span>
                <span id="themeText">Dark</span>
            </button>
        </div>
    </div>

    <!-- Settings Modal -->
    <div class="settings-modal" id="settingsModal">
        <div class="settings-dialog">
            <div class="settings-header">
                <div class="settings-title">
                    <i data-lucide="settings"></i> Settings
                </div>
                <button class="settings-close" id="settingsClose">×</button>
            </div>
            <div class="settings-body">
                <!-- Column 1: Layout & Visual Effects -->
                <div>
                    <div class="settings-section">
                        <div class="settings-section-title">Layout</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Main Content Order</div>
                                <div class="settings-item-description">Choose which element appears at the top</div>
                            </div>
                            <select id="layoutOrder" class="settings-select">
                                <option value="video-first">Camera → Conversation</option>
                                <option value="vlm-first" selected>Conversation → Camera</option>
                            </select>
                        </div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Responses on Camera View</div>
                                <div class="settings-item-description">Show text overlay directly on video feed</div>
                            </div>
                            <select id="overlayPosition" class="settings-select">
                                <option value="none">None</option>
                                <option value="top">At the top</option>
                                <option value="bottom">At the bottom</option>
                            </select>
                        </div>
                    </div>

                    <div class="settings-section">
                        <div class="settings-section-title">Visual Effects</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Pop-in Animation</div>
                                <div class="settings-item-description">Scale animation when new VLM response arrives</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="popInToggle" checked>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Green Glow Effect</div>
                                <div class="settings-item-description">Border glow on new VLM response</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="glowToggle" checked>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Fade Effect</div>
                                <div class="settings-item-description">Gradually fade response after 2 seconds</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="fadeToggle" checked>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Column 2: Input Colors & WebRTC -->
                <div>
                    <div class="settings-section">
                        <div class="settings-section-title">Visual Style</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Colorful UI Accents</div>
                                <div class="settings-item-description">Color-coded icons and input focus glows</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="colorfulFocusToggle">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="settings-section">
                        <div class="settings-section-title">WebRTC</div>

                        <div class="settings-item">
                            <div style="flex: 1; min-width: 0;">
                                <div class="settings-item-label">Max Video Latency (seconds)</div>
                                <div class="settings-item-description">Drop old frames if delay exceeds this (0 = no intervention)</div>
                            </div>
                            <input type="number" id="maxLatency" value="0" min="0" max="10.0" step="0.1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">
                        </div>
                    </div>

                    <div class="settings-section">
                        <div class="settings-section-title">Voice</div>

                        <div class="settings-item-description">Use Auto / 中 / 英 below the message box to switch both speech input and output. Auto detects your speech language and reads replies in their original language.</div>
                        <div class="settings-item">
                            <div>
                                <label class="settings-item-label" for="fullDuplexToggle">Full duplex (experimental)</label>
                                <div id="fullDuplexDescription" class="settings-item-description">Keep listening while replies play; speak to interrupt. Off on every page load. Turn on Mic and Sound below. Headphones recommended; if speaker echo triggers interruptions, turn this off.</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="fullDuplexToggle" aria-describedby="fullDuplexDescription">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        <div id="voiceStatus" class="settings-item-description" role="status">Checking voice service…</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Speak replies</div>
                                <div class="settings-item-description">Off by default. Read replies in English or Chinese when enabled</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="ttsEnabledToggle">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="settings-section">
                        <div class="settings-section-title">Background Model</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Enable delegation solver</div>
                                <div class="settings-item-description">Use ALIVE for delegated questions, visual reasoning, and chart tasks in the background</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="backgroundEnabledToggle" checked>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div class="settings-item">
                            <div style="flex: 1; min-width: 0;">
                                <div class="settings-item-label">Frame multiplier</div>
                                <div class="settings-item-description">Background frames per second relative to foreground streaming FPS</div>
                            </div>
                            <input type="number" id="backgroundFrameMultiplier" value="2" min="1" max="10" step="1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">
                        </div>

                        <div class="settings-item">
                            <div style="flex: 1; min-width: 0;">
                                <div class="settings-item-label">Max background frames</div>
                                <div class="settings-item-description">Recent background frame cache cap; default and maximum are 100</div>
                            </div>
                            <input type="number" id="backgroundMaxFrames" value="100" min="1" max="100" step="1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">
                        </div>
                    </div>

                    <div class="settings-section">
                        <div class="settings-section-title">Debug</div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Show request payload</div>
                                <div class="settings-item-description">Include request JSON (image + prompt) under the prompt area; collapsed by default</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="debugShowRequestPayload">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Show response payload</div>
                                <div class="settings-item-description">Include API response JSON under the VLM output; collapsed by default</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="debugShowResponsePayload">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div class="settings-item">
                            <div>
                                <div class="settings-item-label">Show memory state</div>
                                <div class="settings-item-description">Display mid-term and long-term memory content below VLM output</div>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" id="debugShowMemoryState">
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<div class="container">
        <!-- Left Sidebar -->
        <div class="sidebar docked" id="sidebar">
            <!-- Internal API controls retained for server configuration only. -->
            <div class="panel" style="display: none;">
                <div class="panel-header" onclick="togglePanel('vlmConfig')">
                    <div class="panel-title">
                        <span class="panel-icon">
                            <i data-lucide="globe"></i>
                        </span>
                        <span class="panel-title-text">VLM API Configuration</span>
                    </div>
                    <span class="panel-toggle collapsed" id="vlmConfigToggle">▼</span>
                </div>
                <div class="panel-content collapsed" id="vlmConfig">
                    <div class="form-group">
                        <div style="display: flex; align-items: center; gap: 4px; margin-bottom: 8px;">
                            <label style="margin-bottom: 0; flex: 1;">API Base URL</label>
                            <div style="display: none; position: relative;">
                                <button class="icon-btn" id="apiPresetsBtn" title="Select preset API endpoint">
                                    <i data-lucide="clipboard"></i>
                                </button>
                                <div id="apiPresetsMenu" style="display: none; position: absolute; right: 0; top: 100%; margin-top: 4px; background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); min-width: 280px; z-index: 9999;">
                                    <div style="padding: 8px 0;">
                                        <div class="api-preset-item" data-url="http://localhost:11434/v1">
                                            <strong>Ollama</strong><br>
                                            <span style="font-size: 11px; color: var(--text-muted);">http://localhost:11434/v1</span>
                                        </div>
                                        <div class="api-preset-item" data-url="http://localhost:8000/v1">
                                            <strong>vLLM</strong><br>
                                            <span style="font-size: 11px; color: var(--text-muted);">http://localhost:8000/v1</span>
                                        </div>
                                        <div class="api-preset-item" data-url="http://localhost:30000/v1">
                                            <strong>SGLang</strong><br>
                                            <span style="font-size: 11px; color: var(--text-muted);">http://localhost:30000/v1</span>
                                        </div>
                                        <div style="border-top: 1px solid var(--border-color); margin: 4px 0;"></div>
                                        <div class="api-preset-item" data-url="https://api.openai.com/v1">
                                            <strong>OpenAI</strong><br>
                                            <span style="font-size: 11px; color: var(--text-muted);">https://api.openai.com/v1</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="text" id="apiBaseUrl" value="http://127.0.0.1:8070/v1" placeholder="http://localhost:8000/v1">
                        <div class="input-hint" id="apiBaseHint">Current VLM endpoint</div>
                    </div>
                    <div class="form-group" id="apiKeyGroup">
                        <div style="display: flex; align-items: center; cursor: pointer; margin-bottom: 8px;" onclick="toggleApiKeyField()">
                            <label style="margin-bottom: 0; flex: 1;">API Key (Optional)</label>
                            <span id="apiKeyToggle" style="font-size: 12px; color: var(--text-secondary);">▼</span>
                        </div>
                        <div id="apiKeyField">
                            <input type="text" id="apiKey" placeholder="sk-..." autocomplete="off">
                            <div class="input-hint">Leave empty for local deployment.</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                            <label style="margin-bottom: 0;">Model Selection</label>
                            <div style="display: flex; gap: 6px;">
                                <button class="icon-btn" id="refreshModelsBtn" title="Refresh available models">
                                    <i data-lucide="refresh-cw"></i>
                                </button>
                            </div>
                        </div>
                        <select id="modelSelect">
                            <option value="">Loading models...</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Video Source -->
            <div class="panel">
                <div class="panel-header" onclick="togglePanel('cameraConfig')">
                    <div class="panel-title">
                        <span class="panel-icon">
                            <i data-lucide="video"></i>
                        </span>
                        <span class="panel-title-text">Video Source</span>
                    </div>
                    <span class="panel-toggle collapsed" id="cameraConfigToggle">▼</span>
                </div>
                <div class="panel-content collapsed" id="cameraConfig">
                    <!-- Input Source Tabs -->
                    <div class="input-source-tabs" style="display: none;">
                        <button class="input-source-tab active" data-source="webcam">
                            <i data-lucide="video" style="width: 14px; height: 14px; margin-right: 4px;"></i>
                            Webcam
                        </button>
                        <button class="input-source-tab" data-source="rtsp" title="RTSP IP Camera (Beta - Tested with Reolink RLC-811A)">
                            <i data-lucide="cast" style="width: 14px; height: 14px; margin-right: 4px;"></i>
                            RTSP Stream
                            <span class="beta-badge">BETA</span>
                        </button>
                    </div>

                    <!-- Webcam Controls -->
                    <div id="webcamControls">
                        <div class="form-group">
                            <label>Camera Selection</label>
                            <select id="cameraSelect">
                                <option value="">Detecting cameras...</option>
                            </select>
                            <div class="input-hint" style="margin-bottom: 11px;">Select camera device to use for VLM analysis</div>
                        </div>
                    </div>

                    <!-- RTSP Controls -->
                    <div id="rtspControls" style="display: none;">
                        <div class="form-group">
                            <div style="display: flex; align-items: center; gap: 4px; margin-bottom: 8px;">
                                <div class="tooltip-wrapper" style="margin-bottom: 0; flex: 1;">
                                    <label style="margin-bottom: 0;">RTSP Stream URL</label>
                                    <span class="tooltip-icon">ℹ</span>
                                    <div class="tooltip-text">
                                        <strong>Format:</strong> rtsp://[user:pass@]ip:port/path<br><br>
                                        <strong>Examples:</strong><br>
                                        • rtsp://192.168.1.100:554/stream<br>
                                        • rtsp://admin:[email protected]:554/h264Preview_01_main
                                    </div>
                                </div>
                                <button class="icon-btn" id="testRtspBtn" title="Test Connection">
                                    <i data-lucide="test-tube-diagonal"></i>
                                </button>
                            </div>
                            <input type="text" id="rtspUrl" placeholder="rtsp://192.168.1.100:554/stream" style="margin-bottom: 16px;">
                            <div id="rtspStatus" class="input-hint" style="margin-top: -8px; margin-bottom: 12px; display: none;"></div>
                        </div>
                    </div>
                    <div class="form-group">
                        <!-- RTSP Beta Warning (shown only when RTSP tab is active) -->
                        <div id="rtspBetaWarning" class="input-hint" style="margin-top: 12px; color: var(--warning-color); display: none; align-items: center; gap: 4px;">
                            <span><strong>Beta:</strong> Optional IP camera input.</span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Processing Interval</label>
                        <input type="number" id="processEvery" value="1" min="0.1" max="60" step="0.1">
                        <div class="input-hint">Seconds between each VLM inference (default: 1s)</div>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label>Frames per Batch</label>
                        <input type="number" id="framesPerBatch" value="1" min="1" max="30" step="1">
                        <div class="input-hint">Number of frames batched per inference (default: 1)</div>
                    </div>
                </div>
            </div>

        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Video Feed -->
            <div class="video-card" id="videoCard">
                <div class="alive-view-label"><span></span> YOUR VIEW</div>
                <div class="alive-camera-note">A shared view, a new perspective.<small>Start your camera to begin.</small></div>
                <!-- Big Start Button (centered overlay) -->
                <button id="bigStartBtn" class="big-start-btn" onclick="start()">
                    <i data-lucide="play"></i>
                    Open camera
                </button>

                <!-- Small Stop Button (top-left corner when streaming) -->
                <button id="smallStopBtn" class="small-stop-btn" onclick="stop({ clearConversation: true })">
                    <i data-lucide="square"></i>
                </button>

                <!-- Fullscreen Button (top-right corner) -->
                <button class="fullscreen-btn" onclick="toggleFullscreen()" title="Toggle fullscreen">
                    <i data-lucide="maximize" id="fullscreenIcon"></i>
                </button>

                <button class="quick-camera-btn" id="quickCameraBtn" hidden title="Switch front/rear camera" type="button">
                    <i data-lucide="camera"></i>
                    <span id="quickCameraLabel">Rear</span>
                </button>

                <div class="fullscreen-prompt-overlay" id="fullscreenPromptOverlay"></div>

                <!-- Responses Overlay (shown in fullscreen mode) -->
                <div class="fullscreen-vlm-overlay" id="fullscreenVlmOverlay">
                    <div class="vlm-title">
                        <i data-lucide="bot"></i>
                        Responses
                    </div>
                    <div class="vlm-content" id="fullscreenVlmContent">Ready</div>
                    <div class="vlm-metrics" id="fullscreenVlmMetrics"></div>
                </div>

                <!-- Legacy controls (kept for mirror functionality) -->
                <div class="video-controls" style="top: 64px;">
                    <button class="video-control-btn" id="mirrorBtn" title="Mirror video">
                        <i data-lucide="flip-horizontal"></i> Mirror
                    </button>
                </div>

                <video id="videoElement" autoplay playsinline muted></video>
                <div class="video-overlay" id="videoOverlay"></div>
            </div>

            <!-- Generation Result -->
            <div class="result-card" id="vlmOutputCard">
                <div class="result-header">
                    <div class="result-header-left">
                        <img class="conversation-brand" src="/images/alive.png?v=1" alt="ALIVE" width="126" height="42">
                        <span id="modelName" hidden aria-hidden="true"></span>
                        <div class="tts-speaking-line" id="ttsSpeakingLine">
                            <strong>Speaking:</strong> <span id="ttsSpeakingText"></span>
                        </div>
                    </div>
                    <div class="result-header-metrics">
                        <div class="metrics-inline" id="metricsInline" style="display: none;">
                            <div class="metric-item">
                                <span title="Model processing time; excludes ASR, TTS, and public network delay">Model:</span>
                                <span class="metric-value" id="latencyValue">--</span>
                                <span>ms</span>
                            </div>
                            <div class="metric-item">
                                <span>Avg:</span>
                                <span class="metric-value" id="avgLatencyValue">--</span>
                                <span>ms</span>
                            </div>
                            <div class="metric-item">
                                <span>Count:</span>
                                <span class="metric-value" id="countValue">--</span>
                            </div>
                        </div>
                    </div>
            </div>

                <div class="result-prompt" id="currentPrompt" style="display: none;"></div>
                <div id="requestPayloadDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">
                    <details style="margin: 0;">
                        <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Request payload (debug)</summary>
                        <pre id="requestPayloadContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 240px; white-space: pre-wrap; word-break: break-all;"></pre>
                    </details>
                </div>
                <div class="result-text vlm-history-shell" id="resultText">
                    <button class="markdown-toggle-embedded" id="markdownToggle" title="Toggle Markdown Rendering">
                        <span id="markdownIcon"><i data-lucide="code"></i></span>
                        <span id="markdownText">Markdown</span>
                    </button>
                    <button class="copy-button-embedded" id="copyButton" title="Copy to clipboard">
                        <i data-lucide="copy"></i>
                    </button>
                    <div class="result-text-content vlm-history" id="resultTextContent"></div>
                </div>
                <div id="responsePayloadDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">
                    <details style="margin: 0;">
                        <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Response payload (debug)</summary>
                        <pre id="responsePayloadContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 240px; white-space: pre-wrap; word-break: break-all;"></pre>
                    </details>
                </div>
                <div id="memoryStateDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">
                    <details open style="margin: 0;">
                        <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Mid-term memory</summary>
                        <pre id="midTermMemoryContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 300px; white-space: pre-wrap; word-break: break-all;"></pre>
                    </details>
                    <details open style="margin: 4px 0 0;">
                        <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Long-term memory</summary>
                        <pre id="longTermMemoryContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 300px; white-space: pre-wrap; word-break: break-all;"></pre>
                    </details>
                </div>
                <div class="prompt-editor-inline">
                    <div class="chat-prompt-shell" id="promptEditor">
                        <button class="chat-prompt-action" id="promptPresetBtn" title="Quick prompts" type="button">
                            <svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg>
                        </button>
                        <div class="prompt-popover hidden" id="promptPresetMenu">
                            <button class="prompt-preset-option" type="button" data-label="Describe the scene" data-prompt="Describe the current scene in one sentence. Answer in English.">
                                <span class="prompt-preset-copy">
                                    <span class="primary">Describe the current scene in one sentence</span>
                                    <span class="secondary">Describe the scene</span>
                                </span>
                                <span class="check">✓</span>
                            </button>
                            <button class="prompt-preset-option" type="button" data-label="Identify an object" data-prompt="What am I holding? Give a short answer in English.">
                                <span class="prompt-preset-copy">
                                    <span class="primary">Identify the object I am holding</span>
                                    <span class="secondary">Identify an object</span>
                                </span>
                                <span class="check">✓</span>
                            </button>
                            <button class="prompt-preset-option" type="button" data-label="Clothing color" data-prompt="What color are my clothes? Give a short answer in English.">
                                <span class="prompt-preset-copy">
                                    <span class="primary">Tell me the color of my clothing</span>
                                    <span class="secondary">Clothing color</span>
                                </span>
                                <span class="check">✓</span>
                            </button>
                            <button class="prompt-preset-option" type="button" data-label="Describe my action" data-prompt="What am I doing? Give a short answer in English.">
                                <span class="prompt-preset-copy">
                                    <span class="primary">Describe what I am doing</span>
                                    <span class="secondary">Describe my action</span>
                                </span>
                                <span class="check">✓</span>
                            </button>
                        </div>
                        <textarea class="chat-prompt-input" id="promptText" rows="1" placeholder="Ask about what you see…"></textarea>
                        <button class="chat-prompt-action speech speech-control" id="speechBtn" title="Start the video to speak" type="button" disabled>
                            <i class="mic-icon" data-lucide="mic"></i>
                            <span class="voice-wave" aria-hidden="true"><span></span><span></span><span></span><span></span></span>
                            <span class="speech-label">Hold to speak</span>
                        </button>
                        <button class="chat-prompt-action send" id="promptSendBtn" title="Start the video to send" type="button" disabled>
                            <i data-lucide="send"></i>
                        </button>
                    </div>
                    <div class="voice-mode-bar" id="voiceModeBar" aria-label="Voice controls">
                        <button id="voiceModeBtn" class="voice-mode-button" type="button" aria-pressed="false"
                            aria-label="Turn microphone on" title="Turn microphone on" disabled>
                            <span id="voiceModeIcon" class="voice-toggle-icon" aria-hidden="true"></span>
                            <span id="voiceModeLabel">Mic off</span>
                        </button>
                        <button id="ttsToggleBtn" class="voice-mode-button" type="button" aria-pressed="false"
                            aria-label="Turn spoken replies on" title="Turn spoken replies on" disabled>
                            <span id="ttsToggleIcon" class="voice-toggle-icon" aria-hidden="true"></span>
                            <span id="ttsToggleLabel">Sound off</span>
                        </button>
                        <div id="voiceLanguageTabs" class="voice-language-tabs" role="radiogroup" aria-label="Speech input and output language">
                            <button type="button" class="voice-language-tab" role="radio" data-language="auto" aria-checked="true" tabindex="0" title="Detect speech and reply language">Auto</button>
                            <button type="button" class="voice-language-tab" role="radio" data-language="zh" aria-checked="false" tabindex="-1" title="Chinese speech input and output">中</button>
                            <button type="button" class="voice-language-tab" role="radio" data-language="en" aria-checked="false" tabindex="-1" title="English speech input and output">英</button>
                        </div>
                        <span id="voiceModeStatus" class="voice-mode-status" role="status">Microphone and sound are off</span>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <script>
        // ASR parameters
        const ASR_TARGET_SAMPLE_RATE = 16000;
        const ASR_SILENCE_AUTO_STOP_MS = 2000;
        const ASR_SILENCE_RMS_THRESHOLD = 0.012;
        const ASR_AUDIO_BUFFER_SIZE = 4096;
        const ASR_FINAL_FALLBACK_MS = 6000;
        const ASR_WS_PATH = '/ws/asr';
        // Applied after browser echo cancellation. Short clicks do not interrupt.
        const DUPLEX_ONSET_RMS = 0.018;
        const DUPLEX_ONSET_SAMPLES = ASR_TARGET_SAMPLE_RATE * 0.18;
        const DUPLEX_PREROLL_SAMPLES = ASR_TARGET_SAMPLE_RATE * 0.30;

        // Elements
        const themeToggle = document.getElementById('themeToggle');
        const themeIcon = document.getElementById('themeIcon');
        const themeText = document.getElementById('themeText');
        const jdLogo = document.getElementById('jdLogo');
        const videoElement = document.getElementById('videoElement');
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const connectionStatus = document.getElementById('connectionStatus');
        const resultText = document.getElementById('resultText');
        const currentPrompt = document.getElementById('currentPrompt');
        const metricsInline = document.getElementById('metricsInline');
        const markdownToggle = document.getElementById('markdownToggle');
        const markdownIcon = document.getElementById('markdownIcon');
        const markdownText = document.getElementById('markdownText');
        const copyButton = document.getElementById('copyButton');
        const latencyValue = document.getElementById('latencyValue');
        const avgLatencyValue = document.getElementById('avgLatencyValue');
        const countValue = document.getElementById('countValue');
        const promptPresetBtn = document.getElementById('promptPresetBtn');
        const promptPresetMenu = document.getElementById('promptPresetMenu');
        const promptPresetOptions = document.querySelectorAll('.prompt-preset-option');
        const promptEditor = document.getElementById('promptEditor');
        const promptEditorHome = document.querySelector('.prompt-editor-inline');
        const fullscreenPromptOverlay = document.getElementById('fullscreenPromptOverlay');
        const promptText = document.getElementById('promptText');
        const speechBtn = document.getElementById('speechBtn');
        const voiceModeBtn = document.getElementById('voiceModeBtn');
        const voiceModeLabel = document.getElementById('voiceModeLabel');
        const voiceModeStatus = document.getElementById('voiceModeStatus');
        const ttsToggleBtn = document.getElementById('ttsToggleBtn');
        const ttsToggleLabel = document.getElementById('ttsToggleLabel');
        const voiceIcon = paths => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;
        const voiceIcons = {
            mic: voiceIcon('<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3M8 22h8"/>'),
            micOff: voiceIcon('<path d="m2 2 20 20M9 9v3a3 3 0 0 0 5.1 2.1M9 5V5a3 3 0 0 1 6 0v5M5 10v2a7 7 0 0 0 12 4.9M19 10v2M12 19v3M8 22h8"/>'),
            sound: voiceIcon('<path d="m11 5-6 4H2v6h3l6 4V5ZM15.5 8.5a5 5 0 0 1 0 7M19 5a10 10 0 0 1 0 14"/>'),
            soundOff: voiceIcon('<path d="m11 5-6 4H2v6h3l6 4V5ZM17 9l5 6M22 9l-5 6"/>')
        };
        const speechButtons = [speechBtn].filter(Boolean);
        const promptSendBtn = document.getElementById('promptSendBtn');
        const modelSelect = document.getElementById('modelSelect');
        const refreshModelsBtn = document.getElementById('refreshModelsBtn');
        const processEvery = document.getElementById('processEvery');
        const framesPerBatch = document.getElementById('framesPerBatch');
        const maxLatency = document.getElementById('maxLatency');
        const mirrorBtn = document.getElementById('mirrorBtn');
        const quickCameraBtn = document.getElementById('quickCameraBtn');
        const quickCameraLabel = document.getElementById('quickCameraLabel');
        const ttsEnabledToggle = document.getElementById('ttsEnabledToggle');
        const fullDuplexToggle = document.getElementById('fullDuplexToggle');
        const voiceLanguageTabs = [...document.querySelectorAll('#voiceLanguageTabs [data-language]')];
        let voiceCapabilities = { asr: false, tts: false };
        const ttsSpeakingLine = document.getElementById('ttsSpeakingLine');
        const ttsSpeakingText = document.getElementById('ttsSpeakingText');
        const backgroundEnabledToggle = document.getElementById('backgroundEnabledToggle');
        const backgroundFrameMultiplier = document.getElementById('backgroundFrameMultiplier');
        const backgroundMaxFrames = document.getElementById('backgroundMaxFrames');

        let peerConnection = null;
        let localStream = null;
        let cameraWebsocket = null;
        let cameraCaptureTimer = null;
        let websocket = null;
        let serverConfigApplied = false;
        let fadeTimeout = null;
        let lastText = '';
        let lastTtsEventKey = '';
        let ttsEventSequence = 0;
        let ttsRequestToken = 0;
        let ttsWs = null;
        let ttsWsReadyPromise = null;
        let ttsAudioContext = null;
        let ttsNextPlayTime = 0;
        let ttsSources = [];
        let ttsPcmRemainder = null;
        let ttsSpeaking = false;
        let pendingTtsQueue = [];
        let currentTtsItem = null;
        let ttsFinishTimer = null;
        let currentPromptText = '';
        let vlmHistory = [];
        let backgroundTaskEntries = new Map();
        let backgroundSummaryEntries = new Map();
        let lastReadyBackgroundTaskId = '';
        let backgroundConfig = null;
        let lastHistoryKey = null;
        let lastLoggedInferenceCount = 0;
        let pendingPromptEntry = null;
        let streamStartToken = 0;
        let revealVideoAfterMetricsToken = null;
        let revealVideoFallbackTimeout = null;
        let asrWs = null;
        let asrStream = null;
        let asrAudioContext = null;
        let asrSource = null;
        let asrProcessor = null;
        let asrSilence = null;
        let asrStarting = false;
        let asrRecording = false;
        let asrFinalText = '';
        let asrPartialText = '';
        let asrLastFinalText = '';
        let asrLastVoiceTime = 0;
        let asrSendPromptWhenFinal = false;
        let asrStopMode = 'auto';
        let asrPointerId = null;
        let ignoreNextSpeechClick = false;
        let ignoreSpeechClickTimeout = null;
        let asrStartToken = 0;
        let asrFinalFallbackTimer = null;
        let asrStopRequested = false;
        let asrHeardVoice = false;
        let asrUsesServerVad = false;
        let asrRenewTimer = null;
        let duplexUserSpeaking = false;
        let duplexOnsetSamples = 0;
        let duplexPreroll = [];
        let duplexPrerollSamples = 0;
        // Until the new question is answered, late replies may display but not speak.
        let duplexReplyGate = { prompt: null, waiting: false };
        let voiceModeEnabled = false;
        let voiceModeStarting = false;
        let voiceModeGeneration = 0;
        let voiceListenTimer = null;
        let voiceReplyTimer = null;
        let voiceAwaitingPrompt = null;
        let mobileVoiceMode = false;
        // Multi-session: one ID per page/tab; sent in WebSocket and /offer so this tab gets only its VLM output
        let sessionId = crypto.randomUUID ? crypto.randomUUID() : 'tab-' + Date.now() + '-' + Math.random().toString(36).slice(2);
        let gatewaySessionBlocked = false;
        let isAnalysisRunning = false;
        let selectedCameraId = null;
        let videoDevices = [];
        let preferredCameraFacing = 'environment';
        let rtspSessionId = 'default';  // For RTSP mode
        // Enable markdown by default (user can disable if they prefer raw text)
        let markdownEnabled = demoStorage.getItem('markdownEnabled') !== 'false';

        function getCameraFacing(device, index = 0) {
            const label = (device?.label || '').toLowerCase();
            if (/front|user|face|前/.test(label)) {
                return 'user';
            }
            if (/back|rear|environment|world|后/.test(label)) {
                return 'environment';
            }
            return index === 0 ? 'user' : 'environment';
        }

        function syncQuickCameraButton() {
            const activeDevice = videoDevices.find(device => device.deviceId === selectedCameraId);
            const activeIndex = activeDevice ? videoDevices.indexOf(activeDevice) : 0;
            const facing = getCameraFacing(activeDevice, activeIndex);
            preferredCameraFacing = facing;

            if (quickCameraLabel) {
                quickCameraLabel.textContent = facing === 'user' ? 'Front' : 'Rear';
            }
            if (quickCameraBtn) {
                quickCameraBtn.disabled = videoDevices.length < 2;
                quickCameraBtn.hidden = videoDevices.length < 2;
            }
        }

        // Enumerate and list available cameras
        async function enumerateCameras() {
            try {
                // Request permission first to get device labels
                const tempStream = await navigator.mediaDevices.getUserMedia({ video: true });
                tempStream.getTracks().forEach(track => track.stop());

                // Now enumerate with labels
                const devices = await navigator.mediaDevices.enumerateDevices();
                videoDevices = devices.filter(device => device.kind === 'videoinput');

                const cameraSelect = document.getElementById('cameraSelect');
                cameraSelect.innerHTML = '';

                if (videoDevices.length === 0) {
                    cameraSelect.innerHTML = '<option value="">No cameras found</option>';
                    return;
                }

                videoDevices.forEach((device, index) => {
                    const option = document.createElement('option');
                    option.value = device.deviceId;
                    option.text = device.label || `Camera ${index + 1}`;
                    cameraSelect.appendChild(option);
                });

                // Select first camera by default
                selectedCameraId = videoDevices[0].deviceId;
                syncQuickCameraButton();
                console.log(`Found ${videoDevices.length} camera(s)`);
            } catch (err) {
                console.error('Error enumerating cameras:', err);
                document.getElementById('cameraSelect').innerHTML = '<option value="">Error detecting cameras</option>';
            }
        }

        // Handle camera selection change
        document.getElementById('cameraSelect').addEventListener('change', async (e) => {
            selectedCameraId = e.target.value;
            syncQuickCameraButton();
            console.log('Selected camera:', selectedCameraId);

            // If already running, switch camera
            if (isAnalysisRunning && localStream) {
                try {
                    // Reset session for fresh inference
                    //resetSession();

                    // Stop current stream
                    localStream.getTracks().forEach(track => track.stop());

                    // Get new stream with selected camera
                localStream = await navigator.mediaDevices.getUserMedia({
                    video: {
                            deviceId: { exact: selectedCameraId },
                        width: { ideal: 1280 },
                        height: { ideal: 720 }
                        }
                    });

                    showProcessedVideoStream(localStream, streamStartToken);

                    // Replace track in peer connection
                    const videoTrack = localStream.getVideoTracks()[0];
                    const sender = peerConnection?.getSenders().find(s => s.track && s.track.kind === 'video');
                    if (sender) {
                        await sender.replaceTrack(videoTrack);
                        console.log('Camera switched successfully');
                    }
                } catch (err) {
                    console.error('Error switching camera:', err);
                    alert('Failed to switch camera: ' + err.message);
                }
            }

            // Trigger flash animation
            const cameraSelect = document.getElementById('cameraSelect');
            cameraSelect.classList.add('applied');
            setTimeout(() => {
                cameraSelect.classList.remove('applied');
            }, 600);
        });

        // Also trigger flash on blur (when dropdown closes)
        document.getElementById('cameraSelect').addEventListener('blur', () => {
            const cameraSelect = document.getElementById('cameraSelect');
            if (cameraSelect.value) {
                // Trigger flash animation
                cameraSelect.classList.add('applied');
                setTimeout(() => {
                    cameraSelect.classList.remove('applied');
                }, 600);
            }
        });

        function findCameraByFacing(facing) {
            return videoDevices.find((device, index) => getCameraFacing(device, index) === facing);
        }

        async function switchCameraByFacing(facing) {
            const cameraSelect = document.getElementById('cameraSelect');
            let targetDevice = findCameraByFacing(facing);

            if (!targetDevice && videoDevices.length > 1) {
                const currentIndex = Math.max(0, videoDevices.findIndex(device => device.deviceId === selectedCameraId));
                targetDevice = videoDevices[(currentIndex + 1) % videoDevices.length];
            }

            if (!targetDevice || targetDevice.deviceId === selectedCameraId) {
                return;
            }

            preferredCameraFacing = getCameraFacing(targetDevice, videoDevices.indexOf(targetDevice));
            selectedCameraId = targetDevice.deviceId;
            if (cameraSelect) {
                cameraSelect.value = selectedCameraId;
                cameraSelect.dispatchEvent(new Event('change', { bubbles: true }));
            }
            syncQuickCameraButton();
        }

        quickCameraBtn?.addEventListener('click', () => {
            const nextFacing = preferredCameraFacing === 'user' ? 'environment' : 'user';
            switchCameraByFacing(nextFacing);
        });

        // Tooltip positioning (for fixed position tooltips)
        document.querySelectorAll('.tooltip-wrapper').forEach(wrapper => {
            const icon = wrapper.querySelector('.tooltip-icon');
            const tooltip = wrapper.querySelector('.tooltip-text');

            if (icon && tooltip) {
                wrapper.addEventListener('mouseenter', () => {
                    const rect = icon.getBoundingClientRect();
                    tooltip.style.left = `${rect.left}px`;
                    tooltip.style.top = `${rect.bottom + 8}px`;
                });
            }
        });

        // Handle input source tabs (Webcam vs RTSP)
        document.querySelectorAll('.input-source-tab').forEach(tab => {
            tab.addEventListener('click', () => {
                const source = tab.getAttribute('data-source');
                const webcamControls = document.getElementById('webcamControls');
                const rtspControls = document.getElementById('rtspControls');
                const rtspBetaWarning = document.getElementById('rtspBetaWarning');
                const startBtn = document.getElementById('startBtn');

                // Update active tab
                document.querySelectorAll('.input-source-tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                // Show/hide controls
                if (source === 'webcam') {
                    webcamControls.style.display = 'block';
                    rtspControls.style.display = 'none';
                    rtspBetaWarning.style.display = 'none';
                } else if (source === 'rtsp') {
                    webcamControls.style.display = 'none';
                    rtspControls.style.display = 'block';
                    rtspBetaWarning.style.display = 'flex';
                }
            });
        });

        // Clear RTSP status message when user types
        const rtspUrlInput = document.getElementById('rtspUrl');
        rtspUrlInput.addEventListener('input', () => {
            const statusDiv = document.getElementById('rtspStatus');
            statusDiv.style.display = 'none';
        });

        // Green flash animation when RTSP URL is set (same as API Base URL)
        rtspUrlInput.addEventListener('blur', () => {
            if (rtspUrlInput.value.trim()) {
                rtspUrlInput.classList.add('applied');
                setTimeout(() => {
                    rtspUrlInput.classList.remove('applied');
                }, 600);
            }
        });

        // Test RTSP connection
        document.getElementById('testRtspBtn').addEventListener('click', async () => {
            const rtspUrl = document.getElementById('rtspUrl').value.trim();
            const statusDiv = document.getElementById('rtspStatus');
            const testBtn = document.getElementById('testRtspBtn');

            if (!rtspUrl) {
                statusDiv.textContent = '⚠️ Please enter an RTSP URL';
                statusDiv.style.display = 'block';
                statusDiv.style.color = '#ff6b35';
                return;
            }

            testBtn.disabled = true;
            statusDiv.textContent = '🔄 Testing connection...';
            statusDiv.style.display = 'block';
            statusDiv.style.color = '#76b900';

            try {
                const response = await fetch('/api/rtsp/start', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        rtsp_url: rtspUrl,
                        session_id: 'test-' + Date.now()
                    })
                });

                const data = await response.json();

                if (response.ok) {
                    const info = data.stream_info;
                    statusDiv.innerHTML = `✅ Connected!<br>${info.codec} ${info.width}x${info.height} @${info.fps}fps`;
                    statusDiv.style.color = '#76b900';

                    // Stop the test connection after 2 seconds
                    setTimeout(async () => {
                        await fetch('/api/rtsp/stop', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ session_id: data.session_id })
                        });
                    }, 2000);
                } else {
                    statusDiv.textContent = '❌ ' + (data.error || 'Connection failed');
                    statusDiv.style.color = '#ff6b35';
                }
            } catch (err) {
                console.error('RTSP test error:', err);
                statusDiv.textContent = '❌ Connection failed: ' + err.message;
                statusDiv.style.color = '#ff6b35';
            } finally {
                testBtn.disabled = false;
            }
        });

        // Tooltip positioning - dynamically position tooltip to avoid clipping
        document.querySelectorAll('.tooltip-wrapper').forEach(wrapper => {
            const icon = wrapper.querySelector('.tooltip-icon');
            const tooltip = wrapper.querySelector('.tooltip-text');

            if (icon && tooltip) {
                icon.addEventListener('mouseenter', () => {
                    const rect = icon.getBoundingClientRect();
                    const tooltipWidth = 380; // Match CSS width

                    // Position below the icon
                    let left = rect.left - 10; // Slight offset to left
                    let top = rect.bottom + 8;

                    // Ensure tooltip doesn't go off right edge of viewport
                    if (left + tooltipWidth > window.innerWidth - 20) {
                        left = window.innerWidth - tooltipWidth - 20;
                    }

                    // Ensure tooltip doesn't go off left edge
                    if (left < 20) {
                        left = 20;
                    }

                    tooltip.style.left = left + 'px';
                    tooltip.style.top = top + 'px';
                });
            }
        });

        function getVlmDisplayText(text) {
            if (!text) return '';

            const rawText = String(text);
            const lowerText = rawText.toLowerCase();
            if (rawText.trim() === 'Initializing...') {
                return '';
            }

            if (lowerText.includes('</silence>')) {
                return '';
            }

            const openTag = '<response>';
            const closeTag = '</response>';
            const openIndex = lowerText.lastIndexOf(openTag);

            if (openIndex !== -1) {
                const responseStart = openIndex + openTag.length;
                const closeIndex = lowerText.indexOf(closeTag, responseStart);
                const responseText = closeIndex === -1
                    ? rawText.slice(responseStart)
                    : rawText.slice(responseStart, closeIndex);
                return responseText.trim();
            }

            return rawText.replace(/<\/response>/gi, '').trim();
        }

        function escapeHtml(text) {
            const element = document.createElement('div');
            element.textContent = String(text || '');
            return element.innerHTML;
        }

        function decodeHtmlEntities(text) {
            const element = document.createElement('textarea');
            element.innerHTML = String(text || '');
            return element.value;
        }

        function protectMarkdownCodeSpans(text) {
            const placeholders = [];
            const store = (value) => {
                const token = `@@LIVE_VLM_CODE_${placeholders.length}@@`;
                placeholders.push({ token, value });
                return token;
            };
            const protectedText = String(text || '')
                .replace(/```[\s\S]*?(?:```|$)/g, store)
                .replace(/`[^`\n]+`/g, store);
            return { text: protectedText, placeholders };
        }

        function restoreMarkdownCodeSpans(text, placeholders) {
            let restored = String(text || '');
            placeholders.forEach(({ token, value }) => {
                restored = restored.split(token).join(value);
            });
            return restored;
        }

        function renderMathToHtml(math, displayMode) {
            const source = String(math || '').trim();
            if (!source) return '';
            if (typeof katex === 'undefined' || typeof katex.renderToString !== 'function') {
                return displayMode
                    ? `<div class="markdown-math-fallback">$${escapeHtml(source)}$</div>`
                    : `<span class="markdown-math-fallback">$${escapeHtml(source)}$</span>`;
            }
            try {
                return katex.renderToString(source, {
                    displayMode,
                    throwOnError: false,
                    strict: 'ignore',
                    trust: false,
                    output: 'html'
                });
            } catch (error) {
                console.warn('Error rendering LaTeX:', error);
                return displayMode
                    ? `<div class="markdown-math-fallback">$${escapeHtml(source)}$</div>`
                    : `<span class="markdown-math-fallback">$${escapeHtml(source)}$</span>`;
            }
        }

        function renderMarkdownMath(text) {
            const protectedParts = protectMarkdownCodeSpans(text);
            let source = protectedParts.text;

            source = source.replace(/\$\$([\s\S]+?)\$\$/g, (_match, math) => {
                return renderMathToHtml(math, true);
            });
            source = source.replace(/\\\[([\s\S]+?)\\\]/g, (_match, math) => {
                return renderMathToHtml(math, true);
            });
            source = source.replace(/\\\(([\s\S]+?)\\\)/g, (_match, math) => {
                return renderMathToHtml(math, false);
            });
            source = source.replace(/(^|[^\w\\])\$([^\n$]+?)\$(?!\w)/g, (match, prefix, math) => {
                const trimmed = String(math || '').trim();
                if (!trimmed) return match;
                return `${prefix}${renderMathToHtml(trimmed, false)}`;
            });

            return restoreMarkdownCodeSpans(source, protectedParts.placeholders);
        }

        // Markdown rendering function
        function renderMarkdown(text) {
            if (!text) return '';
            const rawText = String(text);
            // Check if libraries are loaded
            if (typeof marked === 'undefined' || typeof DOMPurify === 'undefined') {
                console.warn('Markdown libraries not loaded, falling back to plain text');
                return escapeHtml(rawText);
            }
            try {
                // Preserve special VLM tokens (e.g. </silence>, </response>) by escaping angle brackets
                text = rawText.replace(/<\/(silence|response)>/g, '&lt;/$1&gt;');
                text = text.replace(/<(silence|response)>/g, '&lt;$1&gt;');
                text = renderMarkdownMath(text);
                // Configure marked options
                marked.setOptions({
                    breaks: true,  // Convert line breaks to <br>
                    gfm: true,     // GitHub Flavored Markdown
                });
                // Parse markdown and sanitize HTML
                const html = marked.parse(text);
                const sanitized = DOMPurify.sanitize(html, {
                    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'code', 'pre', 'blockquote', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'hr', 'a', 'span', 'div', 'math', 'semantics', 'annotation', 'mrow', 'mi', 'mn', 'mo', 'msup', 'msub', 'msubsup', 'mfrac', 'msqrt', 'mroot', 'mtable', 'mtr', 'mtd', 'mtext'],
                    ALLOWED_ATTR: ['href', 'title', 'class', 'style', 'aria-hidden', 'xmlns', 'encoding', 'target', 'rel'],
                });
                return openLinksInNewTabs(sanitized);
            } catch (e) {
                console.error('Error rendering markdown:', e);
                return escapeHtml(rawText); // Fallback to escaped plain text on error
            }
        }

        function openLinksInNewTabs(html) {
            const wrapper = document.createElement('div');
            wrapper.innerHTML = String(html || '');
            wrapper.querySelectorAll('a[href]').forEach((link) => {
                link.setAttribute('target', '_blank');
                link.setAttribute('rel', 'noopener noreferrer');
            });
            return wrapper.innerHTML;
        }

        // Update markdown toggle UI
        function updateMarkdownToggleUI() {
            const contentDiv = document.getElementById('resultTextContent');
            if (markdownEnabled) {
                markdownIcon.innerHTML = '<i data-lucide="code"></i>';
                markdownText.textContent = 'Markdown';
                if (contentDiv) {
                    contentDiv.classList.add('markdown-rendered');
                } else {
                    resultText.classList.add('markdown-rendered');
                }
            } else {
                markdownIcon.innerHTML = '<i data-lucide="file-text"></i>';
                markdownText.textContent = 'Plain Text';
                if (contentDiv) {
                    contentDiv.classList.remove('markdown-rendered');
                } else {
                    resultText.classList.remove('markdown-rendered');
                }
            }
            lucide.createIcons();
        }

        // Markdown toggle handler
        markdownToggle.addEventListener('click', () => {
            markdownEnabled = !markdownEnabled;
            demoStorage.setItem('markdownEnabled', markdownEnabled.toString());
            updateMarkdownToggleUI();

            // Re-render current text with new mode
            renderVlmHistory();
        });

        // Initialize markdown toggle state
        updateMarkdownToggleUI();

        // Copy to clipboard functionality
        copyButton.addEventListener('click', async () => {
            const contentDiv = document.getElementById('resultTextContent');
            let textToCopy = '';

            if (contentDiv) {
                // If markdown is enabled, copy the raw text (not HTML)
                if (markdownEnabled) {
                    // Get the raw text by reading from lastText or extracting from content
                    const latestEntry = vlmHistory[vlmHistory.length - 1] || {};
                    textToCopy = latestEntry.response || latestEntry.error || contentDiv.innerText || contentDiv.textContent;
                } else {
                    const latestEntry = vlmHistory[vlmHistory.length - 1] || {};
                    textToCopy = latestEntry.response || latestEntry.error || contentDiv.textContent || contentDiv.innerText;
                }
            } else {
                textToCopy = resultText.textContent || resultText.innerText;
            }

            if (!textToCopy || textToCopy.trim() === '') {
                return; // Nothing to copy
            }

            try {
                await navigator.clipboard.writeText(textToCopy);

                // Visual feedback
                const originalHTML = copyButton.innerHTML;

                copyButton.classList.add('copied');
                copyButton.innerHTML = '<i data-lucide="check"></i>';
                lucide.createIcons();

                // Reset after 0.8 seconds
                setTimeout(() => {
                    copyButton.classList.remove('copied');
                    copyButton.innerHTML = originalHTML;
                    lucide.createIcons();
                }, 800);
            } catch (err) {
                console.error('Failed to copy text:', err);
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = textToCopy;
                textArea.style.position = 'fixed';
                textArea.style.opacity = '0';
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    copyButton.classList.add('copied');
                    setTimeout(() => copyButton.classList.remove('copied'), 500);
                } catch (e) {
                    console.error('Fallback copy failed:', e);
                }
                document.body.removeChild(textArea);
            }
        });

        function renderTextIntoElement(element, text) {
            if (markdownEnabled) {
                element.innerHTML = renderMarkdown(text);
            } else {
                element.textContent = text;
            }
        }

        function extractFencedBlocks(text, language) {
            return extractFencedBlockCandidates(text, language, { includeUnclosed: false })
                .map(candidate => candidate.text);
        }

        function extractFencedBlockCandidates(text, language, options = {}) {
            const blocks = [];
            const source = String(text || '');
            const pattern = /```[ \t]*([a-zA-Z0-9_-]*)[ \t]*\r?\n?/g;
            const requestedLanguage = String(language || '').toLowerCase();
            let match;
            while ((match = pattern.exec(source)) !== null) {
                const lang = (match[1] || '').toLowerCase();
                const contentStart = pattern.lastIndex;
                const closingIndex = source.indexOf('```', contentStart);
                if (!requestedLanguage || lang === requestedLanguage) {
                    if (closingIndex >= 0) {
                        blocks.push({
                            text: source.slice(contentStart, closingIndex).trim(),
                            incomplete: false
                        });
                    } else if (options.includeUnclosed) {
                        blocks.push({
                            text: source.slice(contentStart).trim(),
                            incomplete: true
                        });
                    }
                }
                if (closingIndex >= 0) {
                    pattern.lastIndex = closingIndex + 3;
                } else {
                    break;
                }
            }
            return blocks;
        }

        function extractInlineJsonObjectCandidates(text, requiredType = '') {
            const source = String(text || '');
            const candidates = [];
            const wantedType = String(requiredType || '').toLowerCase();

            for (let start = 0; start < source.length; start += 1) {
                if (source[start] !== '{') continue;

                let depth = 0;
                let inString = false;
                let escaped = false;

                for (let index = start; index < source.length; index += 1) {
                    const char = source[index];
                    if (inString) {
                        if (escaped) {
                            escaped = false;
                        } else if (char === '\\') {
                            escaped = true;
                        } else if (char === '"') {
                            inString = false;
                        }
                        continue;
                    }

                    if (char === '"') {
                        inString = true;
                    } else if (char === '{') {
                        depth += 1;
                    } else if (char === '}') {
                        depth -= 1;
                        if (depth === 0) {
                            const end = index + 1;
                            const candidate = source.slice(start, end).trim();
                            if (candidate.includes('"type"')) {
                                try {
                                    const parsed = JSON.parse(candidate);
                                    const type = String(parsed?.type || '').toLowerCase();
                                    if (!wantedType || type === wantedType) {
                                        candidates.push({ text: candidate, start, end, parsed });
                                    }
                                } catch (err) {
                                    // This was a brace-balanced object, but not valid JSON.
                                }
                            }
                            start = end - 1;
                            break;
                        }
                    }

                    if (index - start > 160000) {
                        break;
                    }
                }
            }

            return candidates;
        }

        function stripInlineStructuredJsonFromText(text) {
            let source = String(text || '');
            const removable = extractInlineJsonObjectCandidates(source)
                .filter(candidate => {
                    const type = String(candidate.parsed?.type || '').toLowerCase();
                    return type === 'bar_chart' || type === 'html';
                })
                .sort((a, b) => b.start - a.start);

            removable.forEach((candidate) => {
                let start = candidate.start;
                const prefix = source.slice(Math.max(0, start - 12), start);
                const jsonLabel = prefix.match(/(?:^|\s)json\s*$/i);
                if (jsonLabel) {
                    start -= jsonLabel[0].length;
                }
                source = `${source.slice(0, start)}${source.slice(candidate.end)}`;
            });

            return source.replace(/[ \t]{2,}/g, ' ').trim();
        }

        function parseBackgroundChart(text) {
            const candidates = extractFencedBlocks(text, 'json');
            extractInlineJsonObjectCandidates(text, 'bar_chart').forEach(candidate => {
                candidates.push(candidate.text);
            });
            const trimmed = String(text || '').trim();
            if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
                candidates.unshift(trimmed);
            }

            for (const candidate of candidates) {
                try {
                    const parsed = JSON.parse(candidate);
                    if (
                        parsed &&
                        parsed.type === 'bar_chart' &&
                        Array.isArray(parsed.labels) &&
                        Array.isArray(parsed.values)
                    ) {
                        const labels = parsed.labels.map(label => String(label));
                        const values = parsed.values.map(value => Number(value));
                        if (labels.length && labels.length === values.length && values.every(Number.isFinite)) {
                            return {
                                title: String(parsed.title || ''),
                                labels,
                                values
                            };
                        }
                    }
                } catch (err) {
                    // Keep looking for a valid structured block.
                }
            }
            return null;
        }

        function extractBackgroundHtml(text) {
            return extractBackgroundHtmlDetails(text).html;
        }

        function extractBackgroundExplanation(text) {
            let source = String(text || '').trim();
            if (!source) return '';

            source = source
                .replace(/```[ \t]*html[ \t]*\r?\n[\s\S]*?(?:\r?\n```|$)/gi, '')
                .replace(/```[ \t]*json[ \t]*\r?\n\s*\{[\s\S]*?"type"\s*:\s*"(?:html|bar_chart)"[\s\S]*?(?:\r?\n```|$)/gi, '')
                .trim();
            source = stripInlineStructuredJsonFromText(source);

            const doctypeIndex = source.search(/<!doctype html/i);
            const htmlIndex = source.search(/<html[\s>]/i);
            const starts = [doctypeIndex, htmlIndex].filter(index => index >= 0);
            if (starts.length) {
                source = source.slice(0, Math.min(...starts)).trim();
            }

            return source;
        }

        function extractBackgroundHtmlDetails(text) {
            const explicitHtmlCandidates = [];
            const htmlBlocks = extractFencedBlockCandidates(text, 'html', { includeUnclosed: true });
            htmlBlocks.forEach((block) => {
                explicitHtmlCandidates.push({
                    text: block.text,
                    incomplete: block.incomplete
                });
            });

            const candidates = extractFencedBlocks(text, 'json');
            extractInlineJsonObjectCandidates(text, 'html').forEach(candidate => {
                candidates.push(candidate.text);
            });
            const trimmed = String(text || '').trim();
            if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
                candidates.unshift(trimmed);
            }
            for (const candidate of candidates) {
                try {
                    const parsed = JSON.parse(candidate);
                    if (parsed && parsed.type === 'html' && typeof parsed.html === 'string') {
                        explicitHtmlCandidates.push({
                            text: parsed.html,
                            incomplete: false
                        });
                    }
                } catch (err) {
                    // Keep looking.
                }
            }

            const explicitBest = pickBestBackgroundHtmlCandidate(explicitHtmlCandidates);
            if (explicitBest) {
                return explicitBest;
            }

            const fallbackBest = pickBestBackgroundHtmlCandidate([{
                text: trimmed,
                incomplete: false
            }]);
            if (fallbackBest) {
                return fallbackBest;
            }
            return { html: '', incomplete: false };
        }

        function pickBestBackgroundHtmlCandidate(htmlCandidates) {
            let best = null;
            htmlCandidates.forEach((candidate) => {
                const details = normalizeExtractedHtmlDetails(candidate.text, {
                    sourceIncomplete: candidate.incomplete
                });
                if (!details.html) return;
                const scored = {
                    ...details,
                    score: scoreHtmlCandidate(details.html, details.incomplete)
                };
                if (!best || scored.score > best.score) {
                    best = scored;
                }
            });

            if (best) {
                return {
                    html: best.html,
                    incomplete: best.incomplete
                };
            }
            return null;
        }

        function normalizeExtractedHtml(value) {
            return normalizeExtractedHtmlDetails(value).html;
        }

        function normalizeExtractedHtmlDetails(value, options = {}) {
            let html = decodeHtmlEntities(value).trim();
            if (!html) {
                return { html: '', incomplete: false };
            }

            html = html
                .replace(/^```[ \t]*(?:html)?[ \t]*\r?\n?/i, '')
                .replace(/\r?\n?```[ \t]*$/i, '')
                .trim();

            const doctypeIndex = html.search(/<!doctype html/i);
            const htmlIndex = html.search(/<html[\s>]/i);
            const startCandidates = [doctypeIndex, htmlIndex].filter(index => index >= 0);
            if (!startCandidates.length) {
                if (/<(head|body|main|section|style|div|h1|p)\b/i.test(html)) {
                    return {
                        html: completeStaticHtmlDocument(`<!doctype html>\n<html><head><meta charset="UTF-8"></head><body>${html}`),
                        incomplete: Boolean(options.sourceIncomplete || looksIncompleteHtml(html))
                    };
                }
                return { html: '', incomplete: false };
            }

            const startIndex = Math.min(...startCandidates);
            const endMatch = /<\/html\s*>/i.exec(html.slice(startIndex));
            if (endMatch) {
                const endIndex = startIndex + endMatch.index + endMatch[0].length;
                return {
                    html: html.slice(startIndex, endIndex).trim(),
                    incomplete: false
                };
            }
            return {
                html: completeStaticHtmlDocument(html.slice(startIndex).trim()),
                incomplete: true
            };
        }

        function scoreHtmlCandidate(html, incomplete = false) {
            const source = String(html || '');
            const lower = source.toLowerCase();
            let score = Math.min(source.length, 20000);
            if (!incomplete) score += 5000;
            if (lower.includes('<style')) score += 2500;
            if (lower.includes('<body')) score += 1500;
            if (/<(body|main|section|article|aside|header|footer|nav|div|h[1-6]|p|button|ul|ol|li|span|img|figure|table)\b/i.test(source)) {
                score += 1500;
            }
            const structuralMatches = source.match(/<(?:div|section|main|header|nav|footer|button|h[1-6]|p|li)\b/gi) || [];
            score += Math.min(structuralMatches.length * 120, 3000);
            const placeholderCount = (source.match(/\.{3}|…/g) || []).length;
            score -= placeholderCount * 3000;
            const placeholderElementCount = (source.match(/>\s*\.{3}\s*</g) || []).length;
            score -= placeholderElementCount * 5000;
            return score;
        }

        function looksIncompleteHtml(value) {
            const html = String(value || '');
            return (
                (/<html\b/i.test(html) && !/<\/html\s*>/i.test(html)) ||
                (/<body\b/i.test(html) && !/<\/body\s*>/i.test(html)) ||
                (/<head\b/i.test(html) && !/<\/head\s*>/i.test(html)) ||
                (/<style\b/i.test(html) && !/<\/style\s*>/i.test(html))
            );
        }

        function completeStaticHtmlDocument(value) {
            let html = String(value || '').trim();
            if (!html) return '';

            if (/<style\b[^>]*>/i.test(html) && !/<\/style\s*>/i.test(html)) {
                html += '\n</style>';
            }
            if (/<head\b[^>]*>/i.test(html) && !/<\/head\s*>/i.test(html)) {
                html += '\n</head>';
            }
            if (!/<body\b/i.test(html)) {
                html += '\n<body><main style="min-height:100vh;display:grid;place-items:center;font-family:sans-serif;color:#333;background:#f7f7f7;">HTML may be truncated; only styles are available to preview.</main>';
            }
            if (/<body\b[^>]*>/i.test(html) && !/<\/body\s*>/i.test(html)) {
                html += '\n</body>';
            }
            if (/<html\b[^>]*>/i.test(html) && !/<\/html\s*>/i.test(html)) {
                html += '\n</html>';
            }
            if (!/<html\b/i.test(html)) {
                html = `<!doctype html>\n<html><head><meta charset="UTF-8"></head><body>${html}</body></html>`;
            }
            return html;
        }

        function sanitizeStaticHtml(html) {
            if (!html) return '';
            const rawHtml = String(html);
            const allowedTags = [
                'html', 'head', 'body', 'title', 'style',
                'main', 'header', 'footer', 'nav', 'section', 'article', 'aside',
                'div', 'span', 'p', 'br', 'strong', 'em', 'b', 'i', 'u', 'small',
                'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
                'ul', 'ol', 'li', 'dl', 'dt', 'dd',
                'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption',
                'pre', 'code', 'blockquote', 'hr',
                'a', 'img', 'figure', 'figcaption', 'button'
            ];
            const allowedAttrs = [
                'class', 'id', 'style', 'title', 'role', 'aria-label',
                'href', 'src', 'alt', 'width', 'height', 'colspan', 'rowspan'
            ];

            if (typeof DOMPurify !== 'undefined') {
                const cleaned = DOMPurify.sanitize(rawHtml, {
                    WHOLE_DOCUMENT: true,
                    ALLOWED_TAGS: allowedTags,
                    ALLOWED_ATTR: allowedAttrs,
                    ALLOW_DATA_ATTR: false,
                    ALLOW_ARIA_ATTR: true,
                    ALLOWED_URI_REGEXP: /^(?:#|data:image\/(?:png|jpe?g|gif|webp);base64,)/i,
                    FORBID_TAGS: ['script', 'form', 'input', 'textarea', 'select', 'option', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'svg', 'math']
                });
                return normalizeStaticHtmlDocument(cleaned, allowedTags, allowedAttrs);
            }

            return sanitizeStaticHtmlFallback(rawHtml, allowedTags, allowedAttrs);
        }

        function normalizeStaticHtmlDocument(html, allowedTags, allowedAttrs) {
            if (typeof DOMParser === 'undefined') {
                return escapeHtml(html);
            }
            const parser = new DOMParser();
            const source = parser.parseFromString(String(html || ''), 'text/html');
            const cleanDoc = document.implementation.createHTMLDocument('');
            const cleanNode = makeStaticHtmlNodeCleaner(cleanDoc, allowedTags, allowedAttrs);

            Array.from(source.head.childNodes).forEach((child) => {
                const cleaned = cleanNode(child);
                if (cleaned) cleanDoc.head.appendChild(cleaned);
            });
            Array.from(source.body.childNodes).forEach((child) => {
                const cleaned = cleanNode(child);
                if (cleaned) cleanDoc.body.appendChild(cleaned);
            });

            return '<!doctype html>\n' + cleanDoc.documentElement.outerHTML;
        }

        function sanitizeStaticHtmlFallback(html, allowedTags, allowedAttrs) {
            if (typeof DOMParser === 'undefined') {
                return escapeHtml(html);
            }
            return normalizeStaticHtmlDocument(html, allowedTags, allowedAttrs);
        }

        function makeStaticHtmlNodeCleaner(cleanDoc, allowedTags, allowedAttrs) {
            const tagSet = new Set(allowedTags);
            const attrSet = new Set(allowedAttrs);
            const dropTags = new Set(['script', 'form', 'input', 'textarea', 'select', 'option', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'svg', 'math']);

            const cleanNode = (node) => {
                if (node.nodeType === Node.TEXT_NODE) {
                    return cleanDoc.createTextNode(node.textContent || '');
                }
                if (node.nodeType !== Node.ELEMENT_NODE) {
                    return null;
                }

                const tagName = node.tagName.toLowerCase();
                if (dropTags.has(tagName)) {
                    return null;
                }
                if (!tagSet.has(tagName)) {
                    const fragment = cleanDoc.createDocumentFragment();
                    Array.from(node.childNodes).forEach((child) => {
                        const cleanedChild = cleanNode(child);
                        if (cleanedChild) fragment.appendChild(cleanedChild);
                    });
                    return fragment;
                }

                const element = cleanDoc.createElement(tagName);
                Array.from(node.attributes || []).forEach((attr) => {
                    const attrName = attr.name.toLowerCase();
                    if (!attrSet.has(attrName) || attrName.startsWith('on')) {
                        return;
                    }
                    if (tagName === 'a' && attrName === 'href') {
                        return;
                    }
                    if (attrName === 'src' && !isSafeStaticUrl(attr.value)) {
                        return;
                    }
                    if (attrName === 'style') {
                        element.setAttribute(attrName, sanitizeStaticCss(attr.value));
                        return;
                    }
                    element.setAttribute(attrName, attr.value);
                });

                Array.from(node.childNodes).forEach((child) => {
                    const cleanedChild = cleanNode(child);
                    if (cleanedChild) element.appendChild(cleanedChild);
                });

                if (tagName === 'style') {
                    element.textContent = sanitizeStaticCss(node.textContent || '');
                }
                if (tagName === 'a') {
                    element.setAttribute('data-static-link', 'true');
                    element.setAttribute('tabindex', '-1');
                }
                if (tagName === 'button') {
                    element.setAttribute('type', 'button');
                }
                return element;
            };

            return cleanNode;
        }

        function isSafeStaticUrl(url) {
            const value = String(url || '').trim();
            return !value || value.startsWith('#') || /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(value);
        }

        function sanitizeStaticCss(css) {
            return String(css || '')
                .replace(/@import\b[^;]+;?/gi, '')
                .replace(/javascript:/gi, '')
                .replace(/expression\s*\(/gi, '')
                .replace(/url\s*\(\s*(['"]?)(?!data:image\/(?:png|jpe?g|gif|webp);base64,)[^)]+\)/gi, 'none');
        }

        function drawBackgroundBarChart(canvas, chart) {
            const dpr = window.devicePixelRatio || 1;
            const rect = canvas.getBoundingClientRect();
            const width = Math.max(320, Math.floor(rect.width || canvas.clientWidth || 640));
            const height = Math.max(220, Math.floor(rect.height || canvas.clientHeight || 280));
            canvas.width = width * dpr;
            canvas.height = height * dpr;
            const ctx = canvas.getContext('2d');
            ctx.scale(dpr, dpr);
            ctx.clearRect(0, 0, width, height);

            const styles = getComputedStyle(document.documentElement);
            const textColor = styles.getPropertyValue('--text-primary').trim() || '#f5f5f5';
            const mutedColor = styles.getPropertyValue('--text-secondary').trim() || '#aaa';
            const accentColor = styles.getPropertyValue('--warning-color').trim() || '#FFA726';
            const gridColor = styles.getPropertyValue('--border-color').trim() || '#333';
            const padding = { top: chart.title ? 36 : 20, right: 18, bottom: 58, left: 48 };
            const plotW = width - padding.left - padding.right;
            const plotH = height - padding.top - padding.bottom;
            const maxValue = Math.max(...chart.values, 0);
            const scaleMax = maxValue <= 0 ? 1 : maxValue * 1.12;

            ctx.font = '600 14px system-ui, sans-serif';
            ctx.fillStyle = textColor;
            if (chart.title) {
                ctx.fillText(chart.title, padding.left, 22);
            }

            ctx.strokeStyle = gridColor;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(padding.left, padding.top);
            ctx.lineTo(padding.left, padding.top + plotH);
            ctx.lineTo(padding.left + plotW, padding.top + plotH);
            ctx.stroke();

            const barGap = Math.max(6, Math.min(18, plotW / chart.labels.length * 0.18));
            const barW = Math.max(10, (plotW - barGap * (chart.labels.length - 1)) / chart.labels.length);
            ctx.textAlign = 'center';
            ctx.font = '12px system-ui, sans-serif';
            chart.values.forEach((value, index) => {
                const x = padding.left + index * (barW + barGap);
                const barH = Math.max(1, (value / scaleMax) * plotH);
                const y = padding.top + plotH - barH;
                ctx.fillStyle = accentColor;
                ctx.fillRect(x, y, barW, barH);
                ctx.fillStyle = textColor;
                ctx.fillText(String(value), x + barW / 2, Math.max(padding.top + 12, y - 6));
                ctx.fillStyle = mutedColor;
                const label = chart.labels[index];
                const shortLabel = label.length > 14 ? label.slice(0, 13) + '…' : label;
                ctx.fillText(shortLabel, x + barW / 2, padding.top + plotH + 22);
            });
            ctx.textAlign = 'left';
        }

        let activeBackgroundModal = null;

        function createBackgroundActionButton(icon, label, onClick) {
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'background-rich-action';
            button.innerHTML = `<i data-lucide="${icon}"></i><span>${label}</span>`;
            button.addEventListener('click', onClick);
            return button;
        }

        function openHtmlArtifact(url) {
            const value = String(url || '').trim();
            if (!value) return;
            window.open(value, '_blank', 'noopener,noreferrer');
        }

        function renderBackgroundRawView(view, text, options = {}) {
            view.className = 'background-raw-shell';
            const toolbar = document.createElement('div');
            toolbar.className = 'background-raw-toolbar';

            const copyButton = createBackgroundActionButton('copy', 'Copy', async () => {
                try {
                    await navigator.clipboard.writeText(String(text || ''));
                    copyButton.innerHTML = '<i data-lucide="check"></i><span>Copied</span>';
                    lucide.createIcons();
                    setTimeout(() => {
                        copyButton.innerHTML = '<i data-lucide="copy"></i><span>Copy</span>';
                        lucide.createIcons();
                    }, 900);
                } catch (err) {
                    console.error('Failed to copy background raw result:', err);
                }
            });
            toolbar.appendChild(copyButton);

            if (!options.modal) {
                toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {
                    openBackgroundModal('Raw', (body) => renderBackgroundRawView(body, text, { modal: true }));
                }));
            }

            const pre = document.createElement('pre');
            pre.className = 'background-raw-block';
            pre.textContent = String(text || '');
            view.appendChild(toolbar);
            view.appendChild(pre);
        }

        function renderBackgroundChartView(view, chart, options = {}) {
            view.className = 'background-view-shell';
            if (!options.modal) {
                const toolbar = document.createElement('div');
                toolbar.className = 'background-view-toolbar';
                toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {
                    openBackgroundModal('Chart', (body) => renderBackgroundChartView(body, chart, { modal: true }));
                }));
                view.appendChild(toolbar);
            }

            const canvas = document.createElement('canvas');
            canvas.className = 'background-chart';
            view.appendChild(canvas);
            requestAnimationFrame(() => drawBackgroundBarChart(canvas, chart));
        }

        function renderBackgroundHtmlView(view, html, options = {}) {
            view.className = 'background-view-shell';
            if (!options.modal) {
                const toolbar = document.createElement('div');
                toolbar.className = 'background-view-toolbar';
                if (options.htmlUrl) {
                    toolbar.appendChild(createBackgroundActionButton('external-link', 'Open', () => {
                        openHtmlArtifact(options.htmlUrl);
                    }));
                }
                toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {
                    openBackgroundModal('Preview', (body) => renderBackgroundHtmlView(body, html, {
                        modal: true,
                        incomplete: options.incomplete,
                        htmlUrl: options.htmlUrl
                    }));
                }));
                view.appendChild(toolbar);
            } else if (options.htmlUrl) {
                const toolbar = document.createElement('div');
                toolbar.className = 'background-view-toolbar';
                toolbar.appendChild(createBackgroundActionButton('external-link', 'Open', () => {
                    openHtmlArtifact(options.htmlUrl);
                }));
                view.appendChild(toolbar);
            }

            if (options.incomplete) {
                const warning = document.createElement('div');
                warning.className = 'background-preview-warning';
                warning.textContent = 'Background HTML may be truncated. Check the Raw view for the original content.';
                view.appendChild(warning);
            }

            const iframe = document.createElement('iframe');
            iframe.className = 'background-html-frame';
            iframe.setAttribute('sandbox', '');
            iframe.srcdoc = sanitizeStaticHtml(html);
            view.appendChild(iframe);
        }

        function openBackgroundModal(title, renderContent) {
            closeBackgroundModal();

            const backdrop = document.createElement('div');
            backdrop.className = 'background-modal-backdrop';
            backdrop.setAttribute('role', 'dialog');
            backdrop.setAttribute('aria-modal', 'true');

            const dialog = document.createElement('div');
            dialog.className = 'background-modal-dialog';
            dialog.addEventListener('click', (event) => event.stopPropagation());

            const header = document.createElement('div');
            header.className = 'background-modal-header';
            const titleElement = document.createElement('h3');
            titleElement.className = 'background-modal-title';
            titleElement.textContent = title;
            const closeButton = document.createElement('button');
            closeButton.type = 'button';
            closeButton.className = 'background-modal-close';
            closeButton.setAttribute('aria-label', 'Close');
            closeButton.innerHTML = '<i data-lucide="x"></i>';
            closeButton.addEventListener('click', closeBackgroundModal);
            header.appendChild(titleElement);
            header.appendChild(closeButton);

            const body = document.createElement('div');
            body.className = 'background-modal-body';
            renderContent(body);

            dialog.appendChild(header);
            dialog.appendChild(body);
            backdrop.appendChild(dialog);
            backdrop.addEventListener('click', closeBackgroundModal);

            document.body.appendChild(backdrop);
            document.body.classList.add('background-modal-open');
            activeBackgroundModal = backdrop;
            lucide.createIcons();
            closeButton.focus();
        }

        function closeBackgroundModal() {
            if (!activeBackgroundModal) return;
            activeBackgroundModal.remove();
            activeBackgroundModal = null;
            document.body.classList.remove('background-modal-open');
        }

        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape' && activeBackgroundModal) {
                closeBackgroundModal();
            }
        });

        function renderBackgroundRichContent(element, text, rich = null) {
            const structuredChart = rich && rich.chart && Array.isArray(rich.chart.labels) && Array.isArray(rich.chart.values)
                ? {
                    title: String(rich.chart.title || ''),
                    labels: rich.chart.labels.map(label => String(label)),
                    values: rich.chart.values.map(value => Number(value))
                }
                : null;
            const chart = structuredChart || parseBackgroundChart(text);
            let htmlDetails;
            if (rich && typeof rich.html === 'string' && rich.html.trim()) {
                htmlDetails = normalizeExtractedHtmlDetails(rich.html, {
                    sourceIncomplete: Boolean(rich.html_incomplete)
                });
                htmlDetails.incomplete = Boolean(rich.html_incomplete || htmlDetails.incomplete);
            } else {
                htmlDetails = extractBackgroundHtmlDetails(text);
            }
            const html = htmlDetails.html;
            const hasRich = Boolean(chart || html);
            const explanation = extractBackgroundExplanation(text);
            if (!hasRich) {
                renderTextIntoElement(element, text);
                element.classList.toggle('markdown-rendered', markdownEnabled);
                return;
            }

            element.innerHTML = '';
            element.classList.add('background-rich-content');

            const tabs = document.createElement('div');
            tabs.className = 'background-rich-tabs';
            const body = document.createElement('div');
            const views = [];
            let preferredViewLabel = chart ? 'Chart' : html ? 'Preview' : explanation ? 'Explanation' : 'Raw';

            const addView = (label, render) => {
                const tab = document.createElement('button');
                tab.type = 'button';
                tab.className = 'background-rich-tab';
                tab.textContent = label;
                const view = document.createElement('div');
                view.style.display = 'none';
                render(view);
                tab.addEventListener('click', () => {
                    views.forEach(item => {
                        item.tab.classList.toggle('active', item.view === view);
                        item.view.style.display = item.view === view ? 'block' : 'none';
                    });
                });
                tabs.appendChild(tab);
                body.appendChild(view);
                views.push({ label, tab, view });
            };

            if (explanation) {
                addView('Explanation', (view) => {
                    view.className = 'background-view-shell markdown-rendered';
                    renderTextIntoElement(view, explanation);
                });
            }

            addView('Raw', (view) => {
                renderBackgroundRawView(view, text);
            });

            if (chart) {
                addView('Chart', (view) => {
                    renderBackgroundChartView(view, chart);
                });
            }

            if (html) {
                addView('Preview', (view) => {
                    renderBackgroundHtmlView(view, html, {
                        incomplete: htmlDetails.incomplete,
                        htmlUrl: rich && typeof rich.html_url === 'string' ? rich.html_url : ''
                    });
                });
            }

            element.appendChild(tabs);
            element.appendChild(body);
            if (views.length) {
                const defaultView = views.find(item => item.label === preferredViewLabel) || views[0];
                defaultView.tab.click();
                lucide.createIcons();
            }
        }

        function isVlmHistoryNearBottom(element) {
            if (!element) return false;
            if (element.scrollHeight <= element.clientHeight) return true;
            return element.scrollHeight - element.scrollTop - element.clientHeight <= 48;
        }

        function scrollVlmHistoryToBottom(element) {
            if (!element) return;

            requestAnimationFrame(() => {
                element.scrollTop = element.scrollHeight;
                requestAnimationFrame(() => {
                    element.scrollTop = element.scrollHeight;
                });
            });
        }

        function updateTtsSpeakingDisplay(text = '') {
            const speakingText = String(text || '').trim();
            if (ttsSpeakingLine) {
                ttsSpeakingLine.classList.toggle('show', Boolean(speakingText));
            }
            if (ttsSpeakingText) {
                ttsSpeakingText.textContent = speakingText;
            }
        }

        function stopTtsPlayback({ clearQueue = true, requeueCurrent = false } = {}) {
            if (clearQueue) pendingTtsQueue = [];
            else if (requeueCurrent && currentTtsItem) pendingTtsQueue.unshift(currentTtsItem);
            currentTtsItem = null;
            ttsRequestToken += 1;

            if (ttsWs && ttsWs.readyState === WebSocket.OPEN) {
                ttsWs._acceptingAudio = false;
                ttsWs._requestId = '';
                ttsWs._pendingRequestId = '';
                ttsWs.send(JSON.stringify({
                    type: 'stop',
                    request_id: String(ttsRequestToken)
                }));
            }

            ttsSources.forEach(source => {
                try {
                    source.stop();
                } catch (e) {
                    // Source may have already ended.
                }
            });
            ttsSources = [];
            ttsNextPlayTime = 0;
            ttsPcmRemainder = null;
            ttsSpeaking = false;
            updateTtsSpeakingDisplay('');
            if (ttsFinishTimer) {
                clearTimeout(ttsFinishTimer);
                ttsFinishTimer = null;
            }
        }

        function closeTtsWebSocket() {
            stopTtsPlayback();
            if (ttsWs && [WebSocket.CONNECTING, WebSocket.OPEN].includes(ttsWs.readyState)) {
                ttsWs.close();
            }
            ttsWs = null;
            ttsWsReadyPromise = null;
        }

        function maybeSpeakPendingTts() {
            scheduleVoiceListening();
            if (!pendingTtsQueue.length) return;
            const inputBlocksPlayback = isSpeechActive()
                && (!isDuplexListening() || duplexUserSpeaking || asrSendPromptWhenFinal);
            if (ttsSpeaking || !pendingTtsQueue.length || inputBlocksPlayback || !settings.ttsEnabled || !voiceCapabilities.tts) {
                return;
            }
            currentTtsItem = pendingTtsQueue.shift();
            ttsRequestToken += 1;
            startTtsSpeech(currentTtsItem.text, currentTtsItem.lang);
        }

        function splitSpeechText(text) {
            // The speech server accepts 500 characters; keep long replies intact
            // by sending ordered pieces, preferably split at a word boundary.
            const parts = [];
            let rest = text;
            while (rest.length > 450) {
                let end = rest.lastIndexOf(' ', 450);
                if (end < 225) end = 450;
                parts.push(rest.slice(0, end));
                rest = rest.slice(end).trimStart();
            }
            if (rest) parts.push(rest);
            return parts;
        }

        function getTtsWebSocket() {
            if (ttsWs && ttsWs.readyState === WebSocket.OPEN) {
                return Promise.resolve(ttsWs);
            }

            if (ttsWsReadyPromise && ttsWs && ttsWs.readyState === WebSocket.CONNECTING) {
                return ttsWsReadyPromise;
            }

            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/api/tts?session_id=${encodeURIComponent(sessionId)}`;
            const ws = new WebSocket(wsUrl);
            ttsWs = ws;
            ws.binaryType = 'arraybuffer';

            ttsWsReadyPromise = new Promise((resolve, reject) => {
                ws.onopen = () => {
                    if (ttsWs === ws) {
                        resolve(ws);
                    } else {
                        reject(new Error('TTS websocket was replaced'));
                    }
                };
                ws.onerror = (error) => {
                    if (ttsWs === ws) {
                        lastTtsEventKey = '';
                    }
                    reject(error instanceof Error ? error : new Error('TTS websocket failed'));
                };
            });

            ws.onmessage = (event) => {
                if (ttsWs !== ws || !settings.ttsEnabled) {
                    return;
                }

                if (typeof event.data === 'string') {
                    let message;
                    try {
                        message = JSON.parse(event.data);
                    } catch (error) {
                        console.warn('TTS sent invalid control message:', event.data);
                        return;
                    }

                    if (message.type === 'start') {
                        const startedRequestId = String(message.request_id || message.reqid || '');
                        if (startedRequestId === ws._pendingRequestId) {
                            ws._sampleRate = Number(message.sample_rate) || ws._sampleRate || 24000;
                            ws._requestId = startedRequestId;
                            ws._acceptingAudio = true;
                            ws._serverDone = false;
                        }
                    } else if (message.type === 'done' || message.type === 'stopped') {
                        if (message.request_id && String(message.request_id) === ws._requestId) {
                            ws._acceptingAudio = false;
                            ws._serverDone = true;
                            scheduleTtsFinishCheck(String(message.request_id));
                            maybeFinishTtsSpeech(String(message.request_id));
                        }
                    } else if (message.type === 'error') {
                        const failedId = String(message.request_id || '');
                        if (!failedId || failedId === String(ttsRequestToken)) {
                            stopTtsPlayback({ clearQueue: false });
                            lastTtsEventKey = '';
                            updateStatus('Speech playback failed. Continuing with the next reply.', 'disconnected');
                            maybeSpeakPendingTts();
                        }
                    }
                    return;
                }

                const activeRequestId = String(ttsRequestToken);
                if (!ws._acceptingAudio || ws._requestId !== activeRequestId) {
                    return;
                }
                queueTtsPcmChunk(event.data, ws._sampleRate || 24000, ttsRequestToken);
            };

            ws.onclose = () => {
                if (ttsWs === ws) {
                    ttsWs = null;
                    ttsWsReadyPromise = null;
                    if (ttsSpeaking) {
                        stopTtsPlayback({ clearQueue: false });
                        updateStatus('Speech connection interrupted. Please retry.', 'disconnected');
                        maybeSpeakPendingTts();
                    }
                }
            };

            return ttsWsReadyPromise;
        }

        function ensureTtsAudioContext() {
            const AudioContextClass = window.AudioContext || window.webkitAudioContext;
            if (!AudioContextClass) {
                throw new Error('Web Audio API is not supported');
            }
            if (!ttsAudioContext || ttsAudioContext.state === 'closed') {
                ttsAudioContext = new AudioContextClass();
            }
            if (ttsAudioContext.state === 'suspended') {
                ttsAudioContext.resume();
            }
            return ttsAudioContext;
        }

        function pcm16ToAudioBuffer(arrayBuffer, sampleRate) {
            const context = ensureTtsAudioContext();
            const pcm = new Int16Array(arrayBuffer);
            const audioBuffer = context.createBuffer(1, pcm.length, sampleRate);
            const channel = audioBuffer.getChannelData(0);

            for (let i = 0; i < pcm.length; i += 1) {
                channel[i] = Math.max(-1, Math.min(1, pcm[i] / 32768));
            }

            return audioBuffer;
        }

        function normalizePcmChunk(arrayBuffer) {
            let bytes = new Uint8Array(arrayBuffer);

            if (ttsPcmRemainder?.length) {
                const combined = new Uint8Array(ttsPcmRemainder.length + bytes.length);
                combined.set(ttsPcmRemainder, 0);
                combined.set(bytes, ttsPcmRemainder.length);
                bytes = combined;
                ttsPcmRemainder = null;
            }

            if (bytes.length % 2 !== 0) {
                ttsPcmRemainder = bytes.slice(bytes.length - 1);
                bytes = bytes.slice(0, bytes.length - 1);
            }

            return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
        }

        function queueTtsPcmChunk(arrayBuffer, sampleRate, requestToken) {
            if (requestToken !== ttsRequestToken || !settings.ttsEnabled || arrayBuffer.byteLength === 0) {
                return;
            }

            const pcmBuffer = normalizePcmChunk(arrayBuffer);
            if (pcmBuffer.byteLength === 0) {
                return;
            }

            const context = ensureTtsAudioContext();
            const source = context.createBufferSource();
            source.buffer = pcm16ToAudioBuffer(pcmBuffer, sampleRate);
            source.connect(context.destination);

            const startAt = Math.max(context.currentTime + 0.02, ttsNextPlayTime || 0);
            ttsNextPlayTime = startAt + source.buffer.duration;
            ttsSources.push(source);
            scheduleTtsFinishCheck(String(requestToken));
            source.onended = () => {
                ttsSources = ttsSources.filter(item => item !== source);
                maybeFinishTtsSpeech(String(requestToken));
            };
            source.start(startAt);
        }

        function scheduleTtsFinishCheck(requestId) {
            if (ttsFinishTimer) {
                clearTimeout(ttsFinishTimer);
            }

            let delayMs = 100;
            if (ttsAudioContext && ttsNextPlayTime > ttsAudioContext.currentTime) {
                delayMs = Math.max(100, (ttsNextPlayTime - ttsAudioContext.currentTime) * 1000 + 80);
            }

            ttsFinishTimer = setTimeout(() => {
                ttsFinishTimer = null;
                maybeFinishTtsSpeech(requestId);
            }, delayMs);
        }

        function maybeFinishTtsSpeech(requestId, { failed = false } = {}) {
            const ws = ttsWs;
            const activeRequestId = ws?._requestId || '';
            const hasQueuedAudio = ttsSources.length > 0;
            const serverStillStreaming = ws?._acceptingAudio && activeRequestId === requestId;
            const serverDone = ws?._serverDone && activeRequestId === requestId;

            if (serverStillStreaming || hasQueuedAudio) {
                return;
            }

            if ((String(ttsRequestToken) === requestId && serverDone) || failed) {
                if (ws && activeRequestId === requestId) {
                    ws._requestId = '';
                    ws._serverDone = false;
                }
                if (ttsFinishTimer) {
                    clearTimeout(ttsFinishTimer);
                    ttsFinishTimer = null;
                }
                ttsSpeaking = false;
                currentTtsItem = null;
                ttsPcmRemainder = null;
                updateTtsSpeakingDisplay('');
                maybeSpeakPendingTts();
            }
        }

        function startTtsSpeech(speechText, language) {
            const requestToken = ttsRequestToken;
            ttsSpeaking = true;
            scheduleVoiceListening();
            updateTtsSpeakingDisplay(speechText);
            ttsPcmRemainder = null;
            ttsNextPlayTime = 0;

            getTtsWebSocket().then(ws => {
                if (requestToken !== ttsRequestToken || !settings.ttsEnabled) return;
                ws._sampleRate = 24000;
                ws._requestId = '';
                ws._pendingRequestId = String(requestToken);
                ws._acceptingAudio = false;
                ws._serverDone = false;
                ws.send(JSON.stringify({
                    type: 'speak',
                    text: speechText,
                    lang: language,
                    voice: window.aliveUi?.voice || 'serena',
                    session_id: sessionId,
                    request_id: String(requestToken)
                }));
            }).catch(error => {
                if (requestToken === ttsRequestToken) {
                    lastTtsEventKey = '';
                    ttsSpeaking = false;
                    currentTtsItem = null;
                    updateTtsSpeakingDisplay('');
                    console.warn('TTS playback failed:', error);
                    updateStatus('Speech connection failed. Please retry.', 'disconnected');
                    maybeSpeakPendingTts();
                }
            });
        }

        function speakVlmText(text, eventKey = '', metrics = null) {
            const speechText = String(text || '').trim();
            const speechEventKey = String(eventKey || '').trim();
            if (!settings.ttsEnabled || !speechText) {
                scheduleVoiceListening();
                return;
            }
            if (speechEventKey && speechEventKey === lastTtsEventKey) return;
            lastTtsEventKey = speechEventKey || `event:${++ttsEventSequence}`;
            if (isDuplexListening()) {
                // Do not resume an interrupted answer or speak over an utterance.
                const prompt = metrics?.user_prompt || '';
                if (duplexUserSpeaking || asrSendPromptWhenFinal
                    || (duplexReplyGate.waiting && (!duplexReplyGate.prompt || prompt !== duplexReplyGate.prompt))
                    || (duplexReplyGate.prompt && prompt && prompt !== duplexReplyGate.prompt)) return;
            }
            // A newer reply replaces all audio and remaining chunks of the old reply.
            stopTtsPlayback();
            const lang = resolveSpeechLanguage(speechText);
            for (const part of splitSpeechText(speechText)) pendingTtsQueue.push({text: part, lang});
            if (voiceModeEnabled && !isDuplexListening() && asrRecording && !asrHeardVoice) {
                // Idle listening yields to playback; never cut off an utterance.
                finishSpeech({ sendPrompt: false });
            }
            maybeSpeakPendingTts();
        }

        function clearVlmConversation() {
            closeTtsWebSocket();
            vlmHistory = [];
            backgroundTaskEntries.clear();
            backgroundSummaryEntries.clear();
            lastReadyBackgroundTaskId = '';
            lastText = '';
            lastTtsEventKey = '';
            lastHistoryKey = null;
            currentPromptText = '';
            pendingPromptEntry = null;

            resultText.classList.remove('fade');
            renderVlmHistory();

            videoOverlay.textContent = '';
            videoOverlay.classList.remove('show', 'top', 'bottom');

            currentPrompt.style.display = 'none';
            currentPrompt.textContent = '';
            metricsInline.style.display = 'flex';
            latencyValue.textContent = '0';
            avgLatencyValue.textContent = '0';
            countValue.textContent = '0';

            const requestPayloadDebug = document.getElementById('requestPayloadDebug');
            const requestPayloadContent = document.getElementById('requestPayloadContent');
            const responsePayloadDebug = document.getElementById('responsePayloadDebug');
            const responsePayloadContent = document.getElementById('responsePayloadContent');
            if (requestPayloadDebug) requestPayloadDebug.style.display = 'none';
            if (requestPayloadContent) requestPayloadContent.textContent = '';
            if (responsePayloadDebug) responsePayloadDebug.style.display = 'none';
            if (responsePayloadContent) responsePayloadContent.textContent = '';
            const memoryStateDebug = document.getElementById('memoryStateDebug');
            if (memoryStateDebug) memoryStateDebug.style.display = 'none';
            const midTermMemoryContent = document.getElementById('midTermMemoryContent');
            if (midTermMemoryContent) midTermMemoryContent.textContent = '';
            const longTermMemoryContent = document.getElementById('longTermMemoryContent');
            if (longTermMemoryContent) longTermMemoryContent.textContent = '';

            syncVlmToFullscreen();
        }

        function hasVisiblePrompt(entry) {
            return Boolean(entry?.prompt && entry.prompt.trim() && entry.prompt.trim() !== '--');
        }

        function createHistoryNodes(entry, animateResponse = false) {
            let promptDiv = null;
            if (hasVisiblePrompt(entry)) {
                promptDiv = document.createElement('div');
                promptDiv.className = 'result-prompt';
                promptDiv.textContent = cleanBackgroundQuestionText(entry.prompt.trim());
            }

            let responseDiv = null;
            if (entry.kind === 'background') {
                responseDiv = createBackgroundHistoryNode(entry, animateResponse);
            } else if (entry.response) {
                responseDiv = document.createElement('div');
                responseDiv.className = 'result-text';
                if (animateResponse && settings.popIn) {
                    responseDiv.classList.add('new-message');
                    if (settings.glow) {
                        responseDiv.classList.add('with-glow');
                    }
                }
                renderStandardResponseIntoElement(responseDiv, entry);
            }

            entry.promptElement = promptDiv;
            entry.responseElement = responseDiv;

            return { promptDiv, responseDiv };
        }

        function renderStandardResponseIntoElement(responseDiv, entry) {
            renderStandardRichContent(responseDiv, entry);
            appendBackgroundJumpButton(responseDiv, entry);
            requestAnimationFrame(() => lucide.createIcons());
        }

        function isBackgroundSummaryEntry(entry) {
            return entry?.kind === 'background_summary' ||
                Boolean(entry?.backgroundSummary) ||
                Boolean(resolveBackgroundJumpTaskId(entry));
        }

        function isForegroundHistoryEntry(entry) {
            return Boolean(entry) && entry.kind !== 'background' && !isBackgroundSummaryEntry(entry);
        }

        function formatInlineJsonAsMarkdown(text) {
            let source = String(text || '');
            const inlineBlocks = extractInlineJsonObjectCandidates(source)
                .sort((a, b) => b.start - a.start);

            inlineBlocks.forEach((candidate) => {
                let start = candidate.start;
                const prefix = source.slice(Math.max(0, start - 12), start);
                const jsonLabel = prefix.match(/(?:^|\s)json\s*$/i);
                if (jsonLabel) {
                    start -= jsonLabel[0].length;
                }

                let prettyJson = candidate.text;
                try {
                    prettyJson = JSON.stringify(JSON.parse(candidate.text), null, 2);
                } catch (err) {
                    // Keep the original JSON string if prettifying fails.
                }

                const block = `\n\n\`\`\`json\n${prettyJson}\n\`\`\`\n`;
                source = `${source.slice(0, start).trimEnd()}${block}${source.slice(candidate.end).trimStart()}`;
            });

            return source.trim();
        }

        function renderBackgroundSummaryMarkdown(responseDiv, text) {
            responseDiv.innerHTML = '';
            responseDiv.classList.remove('standard-rich-response');
            responseDiv.classList.add('background-summary-message');

            const label = document.createElement('div');
            label.className = 'background-summary-label';
            label.innerHTML = '<svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg><span>Summary</span>';

            const body = document.createElement('div');
            body.className = 'background-summary-body markdown-rendered';
            renderTextIntoElement(body, String(text || '').trim());

            responseDiv.appendChild(label);
            responseDiv.appendChild(body);
        }

        function renderStandardRichContent(responseDiv, entry) {
            const text = entry?.response || '';
            if (isBackgroundSummaryEntry(entry)) {
                renderBackgroundSummaryMarkdown(responseDiv, text);
                return;
            }

            const chart = parseBackgroundChart(text);
            const htmlDetails = extractBackgroundHtmlDetails(text);
            const html = htmlDetails.html;

            if (!chart && !html) {
                responseDiv.classList.remove('standard-rich-response');
                if (!isBackgroundSummaryEntry(entry)) {
                    responseDiv.classList.remove('background-summary-message');
                }
                renderTextIntoElement(responseDiv, text);
                return;
            }

            responseDiv.innerHTML = '';
            responseDiv.classList.add('standard-rich-response');
            responseDiv.classList.remove('background-summary-message');
            const explanation = extractBackgroundExplanation(text);
            if (explanation) {
                const explanationElement = document.createElement('div');
                explanationElement.className = 'standard-rich-explanation markdown-rendered';
                renderTextIntoElement(explanationElement, explanation);
                responseDiv.appendChild(explanationElement);
            }

            if (chart) {
                const chartElement = document.createElement('div');
                chartElement.className = 'standard-rich-chart';
                renderBackgroundChartView(chartElement, chart);
                responseDiv.appendChild(chartElement);
            }

            if (html) {
                const htmlElement = document.createElement('div');
                htmlElement.className = 'standard-rich-html';
                renderBackgroundHtmlView(htmlElement, html, {
                    incomplete: htmlDetails.incomplete
                });
                responseDiv.appendChild(htmlElement);
            }
        }

        function getLatestReadyBackgroundEntry() {
            if (lastReadyBackgroundTaskId && backgroundTaskEntries.has(lastReadyBackgroundTaskId)) {
                const entry = backgroundTaskEntries.get(lastReadyBackgroundTaskId);
                if (entry?.ready && entry.status === 'ready') {
                    return entry;
                }
            }

            for (let index = vlmHistory.length - 1; index >= 0; index -= 1) {
                const entry = vlmHistory[index];
                if (entry?.kind === 'background' && entry.ready && entry.status === 'ready') {
                    return entry;
                }
            }
            return null;
        }

        function cleanBackgroundQuestionText(question) {
            return String(question || '')
                .replace(/^\s*请(?:回答|解答)这道(?:简答题|数学题|题目|问题)[,,、\s]*(?:并(?:提供|给出)必要的推理过程和最终答案)?[::]\s*/u, '')
                .replace(/\[User Query[^\]]*\]\s*/gi, '')
                .replace(/^Prompt:\s*/i, '')
                .replace(/[ \t]{2,}/g, ' ')
                .trim();
        }

        function isBackgroundWaitingNotice(text) {
            const value = String(text || '').trim();
            return /(?:需要|正在)调用后台模型|后台模型(?:正在)?处理|请稍等/.test(value)
                && /继续(?:向我)?提问|期间/.test(value);
        }

        function resolveBackgroundJumpTaskId(entry) {
            const directTaskId = entry?.backgroundHandoff?.task_id;
            if (directTaskId && backgroundTaskEntries.has(String(directTaskId))) {
                return String(directTaskId);
            }

            return '';
        }

        function appendBackgroundJumpButton(responseDiv, entry) {
            if (!isBackgroundSummaryEntry(entry)) {
                return;
            }
            const taskId = resolveBackgroundJumpTaskId(entry);
            if (!taskId) {
                return;
            }

            const backgroundEntry = backgroundTaskEntries.get(String(taskId));
            const questionText = cleanBackgroundQuestionText(
                entry?.backgroundHandoff?.question ||
                backgroundEntry?.question ||
                ''
            );

            const row = document.createElement('div');
            row.className = 'background-jump-row';
            row.dataset.backgroundTaskId = taskId;
            if (questionText) {
                const question = document.createElement('div');
                question.className = 'background-jump-question';
                const label = document.createElement('span');
                label.className = 'background-jump-question-label';
                label.textContent = 'Related question';
                const value = document.createElement('span');
                value.className = 'background-jump-question-text';
                value.textContent = questionText;
                question.appendChild(label);
                question.appendChild(value);
                row.appendChild(question);
            }
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'background-jump-button';
            button.dataset.backgroundTaskId = taskId;
            button.innerHTML = '<i data-lucide="corner-down-left"></i><span>Jump</span>';
            button.title = 'Jump to the background result';
            button.addEventListener('click', (event) => {
                event.preventDefault();
                event.stopPropagation();
                jumpToBackgroundResult(button.dataset.backgroundTaskId || taskId);
            });
            row.appendChild(button);
            responseDiv.appendChild(row);
        }

        function findBackgroundResultElement(taskId) {
            const expectedTaskId = String(taskId || '');
            if (!expectedTaskId) return null;

            const domTarget = Array.from(document.querySelectorAll('[data-background-result-task-id]'))
                .find(element => element.dataset.backgroundResultTaskId === expectedTaskId);
            if (domTarget) {
                return domTarget;
            }

            const entry = backgroundTaskEntries.get(expectedTaskId);
            return entry?.responseElement || null;
        }

        function getScrollableAncestors(element) {
            const ancestors = [];
            let node = element?.parentElement || null;
            while (node && node !== document.body) {
                const style = window.getComputedStyle(node);
                const canScroll = /(auto|scroll|overlay)/.test(style.overflowY)
                    && node.scrollHeight > node.clientHeight + 1;
                if (canScroll) {
                    ancestors.push(node);
                }
                node = node.parentElement;
            }

            const root = document.scrollingElement || document.documentElement;
            if (root) {
                ancestors.push(root);
            }
            return ancestors;
        }

        function scrollElementIntoContainer(target, container, behavior = 'smooth') {
            if (!target || !container) return;
            const containerRect = container.getBoundingClientRect();
            const targetRect = target.getBoundingClientRect();
            const targetTop = container.scrollTop
                + targetRect.top
                - containerRect.top
                - 16;
            container.scrollTo({
                top: Math.max(0, targetTop),
                behavior
            });
        }

        function flashBackgroundJumpTarget(target) {
            if (!target) return;
            target.classList.add('jump-highlight');
            setTimeout(() => target.classList.remove('jump-highlight'), 1800);
        }

        function findBackgroundOriginEntry(entry) {
            const question = cleanBackgroundQuestionText(entry?.question || '');
            if (!question) return null;
            for (let index = vlmHistory.length - 1; index >= 0; index -= 1) {
                const candidate = vlmHistory[index];
                if (!isForegroundHistoryEntry(candidate)) continue;
                if (cleanBackgroundQuestionText(candidate.prompt || '') === question) {
                    return candidate;
                }
            }
            return null;
        }

        function jumpToBackgroundOrigin(entry) {
            const originEntry = findBackgroundOriginEntry(entry);
            const target = originEntry?.promptElement || null;
            if (!target) return;

            const historyContainer = document.getElementById('resultTextContent');
            if (historyContainer && historyContainer.contains(target)) {
                scrollElementIntoContainer(target, historyContainer, 'smooth');
            }
            getScrollableAncestors(target).forEach(container => {
                scrollElementIntoContainer(target, container, 'smooth');
            });
            target.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
            flashBackgroundJumpTarget(target);
        }

        function jumpToBackgroundResult(taskId) {
            const normalizedTaskId = String(taskId || '');
            const entry = backgroundTaskEntries.get(normalizedTaskId);
            if (!entry) return;
            entry.expanded = true;
            renderVlmHistory();

            const performJump = (attempt = 0) => {
                const target = findBackgroundResultElement(normalizedTaskId);
                if (!target) {
                    if (attempt < 3) {
                        setTimeout(() => performJump(attempt + 1), 80);
                    }
                    return;
                }

                const behavior = attempt === 0 ? 'smooth' : 'auto';
                const historyContainer = document.getElementById('resultTextContent');
                if (historyContainer && historyContainer.contains(target)) {
                    scrollElementIntoContainer(target, historyContainer, behavior);
                }
                getScrollableAncestors(target).forEach(container => {
                    scrollElementIntoContainer(target, container, behavior);
                });
                target.scrollIntoView({ behavior, block: 'start', inline: 'nearest' });
                flashBackgroundJumpTarget(target);

                if (attempt < 2) {
                    setTimeout(() => performJump(attempt + 1), attempt === 0 ? 180 : 360);
                }
            };

            requestAnimationFrame(() => {
                requestAnimationFrame(() => performJump(0));
            });
        }

        function createBackgroundHistoryNode(entry, animateResponse = false) {
            const responseDiv = document.createElement('div');
            responseDiv.className = 'result-text background-result';
            if (entry.taskId) {
                responseDiv.dataset.backgroundResultTaskId = String(entry.taskId);
            }
            if (animateResponse && settings.popIn) {
                responseDiv.classList.add('new-message');
            }

            const shell = document.createElement('div');
            shell.className = 'background-result-shell';

            const header = document.createElement('div');
            header.className = 'background-result-header';

            const icon = document.createElement('div');
            icon.className = 'background-result-icon';
            icon.innerHTML = '<svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg>';

            const title = document.createElement('div');
            title.className = 'background-result-title';
            title.textContent = entry.status === 'error'
                ? 'Background model failed'
                : entry.ready
                    ? 'Background result is ready. View it now?'
                    : 'Background model is working...';

            if (entry.question) {
                const question = document.createElement('div');
                question.className = 'background-result-question';
                question.textContent = entry.question;
                title.appendChild(question);
            }

            const action = document.createElement('button');
            action.type = 'button';
            action.className = 'background-result-action';
            action.textContent = entry.expanded ? 'Collapse' : entry.ready ? 'View' : 'Waiting';
            action.disabled = !entry.ready && entry.status !== 'error';
            action.addEventListener('click', () => {
                entry.expanded = !entry.expanded;
                renderVlmHistory();
            });

            const originEntry = findBackgroundOriginEntry(entry);
            let originAction = null;
            if (originEntry) {
                originAction = document.createElement('button');
                originAction.type = 'button';
                originAction.className = 'background-result-action background-origin-action';
                originAction.innerHTML = '<i data-lucide="corner-up-left"></i>';
                originAction.title = 'Jump to the original question';
                originAction.addEventListener('click', (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    jumpToBackgroundOrigin(entry);
                });
            }

            header.appendChild(icon);
            header.appendChild(title);
            if (originAction) {
                header.appendChild(originAction);
            }
            header.appendChild(action);
            shell.appendChild(header);

            if (entry.expanded) {
                const content = document.createElement('div');
                content.className = 'result-text-content markdown-rendered';
                if (entry.status === 'error') {
                    content.textContent = entry.error || 'Background model failed.';
                } else {
                    renderBackgroundRichContent(content, entry.response || '', entry.rich || null);
                }
                shell.appendChild(content);
            }

            responseDiv.appendChild(shell);
            entry.responseElement = responseDiv;
            requestAnimationFrame(() => lucide.createIcons());
            return responseDiv;
        }

        function appendVlmHistoryEntry(entry, { animateLast = false } = {}) {
            const contentDiv = document.getElementById('resultTextContent');
            if (!contentDiv) return;

            const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);
            const { promptDiv, responseDiv } = createHistoryNodes(entry, animateLast);

            if (promptDiv) {
                contentDiv.appendChild(promptDiv);
            }
            if (responseDiv) {
                contentDiv.appendChild(responseDiv);
            }
            resultText.style.display = settings.overlayPosition === 'none' ? 'flex' : 'none';

            if (shouldAutoScroll) {
                scrollVlmHistoryToBottom(contentDiv);
            }

            const videoCard = document.getElementById('videoCard');
            if (videoCard && videoCard.classList.contains('fullscreen')) {
                syncVlmToFullscreen();
            }
        }

        function renderVlmHistory({ animateLast = false } = {}) {
            const contentDiv = document.getElementById('resultTextContent');
            if (!contentDiv) return;

            const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);

            contentDiv.innerHTML = '';
            const fragment = document.createDocumentFragment();
            vlmHistory.forEach((entry, index) => {
                const { promptDiv, responseDiv } = createHistoryNodes(
                    entry,
                    animateLast && index === vlmHistory.length - 1
                );
                if (promptDiv) {
                    fragment.appendChild(promptDiv);
                }
                if (responseDiv) {
                    fragment.appendChild(responseDiv);
                }
            });
            contentDiv.appendChild(fragment);

            resultText.style.display = vlmHistory.length > 0 && settings.overlayPosition === 'none' ? 'flex' : 'none';
            if (shouldAutoScroll) {
                scrollVlmHistoryToBottom(contentDiv);
            }

            // Auto-sync to fullscreen overlay if in fullscreen mode
            const videoCard = document.getElementById('videoCard');
            if (videoCard && videoCard.classList.contains('fullscreen')) {
                syncVlmToFullscreen();
            }
        }

        function appendPromptHistoryEntry(prompt) {
            const latest = vlmHistory[vlmHistory.length - 1];
            const cleanPrompt = cleanBackgroundQuestionText(prompt);

            if (latest && latest.pending && latest.prompt === cleanPrompt) {
                pendingPromptEntry = latest;
                return;
            }

            const entry = {
                key: `prompt:${Date.now()}:${Math.random().toString(36).slice(2)}`,
                prompt: cleanPrompt,
                response: '',
                rawText: '',
                pending: true
            };
            vlmHistory.push(entry);
            pendingPromptEntry = entry;
            appendVlmHistoryEntry(entry);
        }

        function resolveBackgroundSummaryText(data) {
            return String(data?.summary_text || 'The background result is ready.').trim();
        }

        function resolveBackgroundSummaryDetailText(data) {
            const direct = String(data?.background_summary || '').trim();
            if (direct) return direct;
            const text = String(data?.text || '').trim();
            if (text) return text;
            const handoff = data?.interaction_handoff;
            if (handoff && typeof handoff === 'object') {
                return String(handoff.summary || '').trim();
            }
            return '';
        }

        function updateBackgroundSummaryEntry(data, summaryText = null, rawText = null) {
            const taskId = String(data?.task_id || '').trim();
            const summary = String(summaryText ?? resolveBackgroundSummaryText(data)).trim();
            const detailText = String(rawText ?? resolveBackgroundSummaryDetailText(data)).trim();
            if (!taskId || !summary) {
                return null;
            }

            let entry = backgroundSummaryEntries.get(taskId);
            if (!entry) {
                entry = {
                    key: `background-summary:${taskId}`,
                    kind: 'background_summary',
                    contextExcluded: true,
                    prompt: '',
                    response: summary,
                    rawText: detailText || summary,
                    backgroundSummary: true,
                    backgroundHandoff: {
                        task_id: taskId,
                        question: cleanBackgroundQuestionText(data.question || '')
                    }
                };
                backgroundSummaryEntries.set(taskId, entry);
            } else {
                entry.kind = 'background_summary';
                entry.contextExcluded = true;
                entry.backgroundSummary = true;
                entry.response = summary;
                entry.rawText = detailText || summary;
                entry.backgroundHandoff = {
                    task_id: taskId,
                    question: cleanBackgroundQuestionText(data.question || entry.backgroundHandoff?.question || '')
                };
            }
            return entry;
        }

        function appendOrUpdateBackgroundSummaryEntry(data) {
            updateBackgroundSummaryEntry(data);
        }

        function appendOrUpdateBackgroundSummaryHistoryEntry(data, summaryText = null, rawText = null) {
            const entry = updateBackgroundSummaryEntry(data, summaryText, rawText);
            if (!entry) {
                return null;
            }

            const alreadyInHistory = vlmHistory.includes(entry);
            if (!alreadyInHistory) {
                vlmHistory.push(entry);
                appendVlmHistoryEntry(entry, { animateLast: true });
            } else if (entry.responseElement) {
                renderStandardResponseIntoElement(entry.responseElement, entry);
            } else {
                renderVlmHistory({ animateLast: true });
            }
            return entry;
        }

        function appendOrUpdateBackgroundEntry(data) {
            const taskId = String(data.task_id || `background:${Date.now()}`);
            let entry = backgroundTaskEntries.get(taskId);
            const isReady = data.type === 'background_result_ready';
            const isError = data.type === 'background_result_error';

            if (!entry) {
                entry = {
                    key: `background:${taskId}`,
                    kind: 'background',
                    contextExcluded: true,
                    taskId,
                    question: data.question || '',
                    response: '',
                    rawText: '',
                    error: '',
                    ready: false,
                    expanded: false,
                    status: 'running'
                };
                backgroundTaskEntries.set(taskId, entry);
                vlmHistory.push(entry);
            }

            entry.question = data.question || entry.question || '';
            entry.foregroundText = data.foreground_text || entry.foregroundText || '';
            entry.metrics = data.metrics || entry.metrics || null;
            entry.model = data.model || entry.model || '';
            entry.contextExcluded = true;

            if (isReady) {
                entry.response = data.text || '';
                entry.rawText = data.text || '';
                entry.rich = data.rich || null;
                entry.ready = true;
                entry.status = 'ready';
                lastReadyBackgroundTaskId = taskId;
                appendOrUpdateBackgroundSummaryHistoryEntry(data);
            } else if (isError) {
                entry.error = data.error || 'Background model failed.';
                entry.ready = true;
                entry.status = 'error';
            }

            renderVlmHistory({ animateLast: true });
        }

        function applyBackgroundConfig(config) {
            if (!config) return;
            backgroundConfig = config;
            if (backgroundEnabledToggle && typeof config.enabled === 'boolean') {
                backgroundEnabledToggle.checked = config.enabled;
            }
            if (backgroundFrameMultiplier && config.frame_multiplier != null) {
                backgroundFrameMultiplier.value = String(config.frame_multiplier);
            }
            if (backgroundMaxFrames) {
                backgroundMaxFrames.value = String(config.max_frames || 100);
            }
        }

        function sendBackgroundConfig() {
            if (!websocket || websocket.readyState !== WebSocket.OPEN) return;
            websocket.send(JSON.stringify({
                type: 'update_background_config',
                enabled: !!backgroundEnabledToggle?.checked,
                frame_multiplier: parseInt(backgroundFrameMultiplier?.value, 10) || 2,
                max_frames: parseInt(backgroundMaxFrames?.value, 10) || 100
            }));
        }

        // Function to update result text (handles both markdown and plain text)
        function updateResultText(text, metrics = null, backgroundHandoff = null) {
            const displayText = getVlmDisplayText(text);
            if (displayText.trim() && isDuplexListening() && !duplexUserSpeaking && !asrSendPromptWhenFinal
                && duplexReplyGate.prompt && metrics?.user_prompt === duplexReplyGate.prompt) {
                duplexReplyGate.waiting = false;
            }
            if (voiceAwaitingPrompt !== null && metrics?.user_prompt === voiceAwaitingPrompt) {
                voiceAwaitingPrompt = null;
                clearTimeout(voiceReplyTimer);
                voiceReplyTimer = null;
            }
            if (displayText.trim() === '') {
                resultText.style.display = vlmHistory.length > 0 && settings.overlayPosition === 'none' ? 'flex' : 'none';
                scheduleVoiceListening();
                return;
            }

            const resolvedBackgroundHandoff = isBackgroundWaitingNotice(displayText)
                ? null
                : (backgroundHandoff || null);
            const prompt = currentPromptText || '';
            const hasInferenceKey = metrics?.total_inferences != null;
            const historyKey = hasInferenceKey
                ? `count:${metrics.total_inferences}`
                : `text:${text}`;
            const ttsEventKey = hasInferenceKey
                ? historyKey
                : `event:${++ttsEventSequence}`;
            speakVlmText(displayText, ttsEventKey, metrics);
            const pendingEntry = pendingPromptEntry && vlmHistory.includes(pendingPromptEntry)
                && isForegroundHistoryEntry(pendingPromptEntry)
                ? pendingPromptEntry
                : null;

            if (resolvedBackgroundHandoff?.task_id) {
                appendOrUpdateBackgroundSummaryHistoryEntry(
                    {
                        task_id: resolvedBackgroundHandoff.task_id,
                        question: resolvedBackgroundHandoff.question || ''
                    },
                    displayText,
                    text
                );
                syncVlmToFullscreen();
                return;
            }

            const latest = [...vlmHistory].reverse().find(isForegroundHistoryEntry);

            if (latest && latest.key === historyKey) {
                const handoffChanged = JSON.stringify(latest.backgroundHandoff || null)
                    !== JSON.stringify(resolvedBackgroundHandoff || latest.backgroundHandoff || null);
                if (latest.rawText === text && latest.response === displayText && !handoffChanged) {
                    return;
                }
                const contentDiv = document.getElementById('resultTextContent');
                const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);
                latest.rawText = text;
                latest.response = displayText;
                latest.backgroundHandoff = resolvedBackgroundHandoff || latest.backgroundHandoff || null;
                if (latest.responseElement) {
                    renderStandardResponseIntoElement(latest.responseElement, latest);
                } else {
                    renderVlmHistory();
                }
                if (shouldAutoScroll) {
                    scrollVlmHistoryToBottom(contentDiv);
                }
            } else if (pendingEntry) {
                const contentDiv = document.getElementById('resultTextContent');
                const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);
                pendingEntry.key = historyKey;
                pendingEntry.response = displayText;
                pendingEntry.rawText = text;
                pendingEntry.backgroundHandoff = resolvedBackgroundHandoff || pendingEntry.backgroundHandoff || null;
                pendingEntry.pending = false;
                lastHistoryKey = historyKey;
                currentPromptText = '';
                pendingPromptEntry = null;

                if (pendingEntry.responseElement) {
                    renderStandardResponseIntoElement(pendingEntry.responseElement, pendingEntry);
                } else if (pendingEntry.promptElement) {
                    const responseDiv = document.createElement('div');
                    responseDiv.className = 'result-text';
                    if (settings.popIn) {
                        responseDiv.classList.add('new-message');
                        if (settings.glow) {
                            responseDiv.classList.add('with-glow');
                        }
                    }
                    renderStandardResponseIntoElement(responseDiv, pendingEntry);
                    pendingEntry.responseElement = responseDiv;
                    pendingEntry.promptElement.insertAdjacentElement('afterend', responseDiv);
                } else {
                    renderVlmHistory({ animateLast: true });
                }

                if (shouldAutoScroll) {
                    scrollVlmHistoryToBottom(contentDiv);
                }
            } else if (historyKey !== lastHistoryKey && (hasInferenceKey || text !== lastText)) {
                const entry = {
                    key: historyKey,
                    prompt,
                    response: displayText,
                    rawText: text,
                    backgroundHandoff: resolvedBackgroundHandoff || null
                };
                vlmHistory.push(entry);
                lastHistoryKey = historyKey;
                currentPromptText = '';
                appendVlmHistoryEntry(entry, { animateLast: true });
            }

            syncVlmToFullscreen();
        }

        function logLatencyBreakdown(metrics) {
            if (!metrics || !metrics.latency_breakdown_ms) return;
            const inferenceCount = Number(metrics.total_inferences) || 0;
            if (inferenceCount <= lastLoggedInferenceCount) return;
            lastLoggedInferenceCount = inferenceCount;

            const toMs = (value) => Number.isFinite(Number(value)) ? Number(value).toFixed(2) : '--';
            const frameTiming = metrics.frame_timing_ms || {};
            const vlmTiming = metrics.latency_breakdown_ms || {};
            console.groupCollapsed(
                `[VLM latency] #${inferenceCount} total ${toMs(metrics.last_latency_ms)} ms`
            );
            console.table([
                { phase: 'Frame to ndarray', scope: 'Before Latency', ms: toMs(frameTiming.frame_to_ndarray_ms) },
                { phase: 'Frame copy', scope: 'Before Latency', ms: toMs(frameTiming.frame_copy_ms) },
                { phase: 'BGR to RGB + PIL', scope: 'Before Latency', ms: toMs(frameTiming.bgr_to_rgb_pil_ms) },
                { phase: 'Pre-VLM subtotal', scope: 'Before Latency', ms: toMs(frameTiming.pre_vlm_total_ms) },
                { phase: 'JPEG encode', scope: 'Latency', ms: toMs(vlmTiming.jpeg_encode_ms) },
                { phase: 'Base64 encode', scope: 'Latency', ms: toMs(vlmTiming.base64_encode_ms) },
                { phase: 'Request build/debug payload', scope: 'Latency', ms: toMs(vlmTiming.request_build_ms) },
                { phase: 'API call + VLM inference', scope: 'Latency', ms: toMs(vlmTiming.api_call_ms) },
                { phase: 'Response payload record', scope: 'Latency', ms: toMs(vlmTiming.response_payload_ms) },
                { phase: 'Response extract', scope: 'Latency', ms: toMs(vlmTiming.response_extract_ms) },
                { phase: 'Latency total', scope: 'Latency', ms: toMs(vlmTiming.total_ms) },
            ]);
            console.groupEnd();
        }

        // Enumerate cameras on page load
        enumerateCameras();

        // Start the redesigned page in light mode once, then remember explicit choices.
        function applyTheme(theme) {
            // theme can be 'light', 'dark', or 'auto'
            if (theme === 'light') {
                document.body.classList.add('light-theme');
                themeIcon.innerHTML = '<i data-lucide="sun"></i>';
                themeText.textContent = 'Light';
            } else if (theme === 'dark') {
                document.body.classList.remove('light-theme');
                themeIcon.innerHTML = '<i data-lucide="moon"></i>';
                themeText.textContent = 'Dark';
            } else { // 'auto' - follow OS preference
                const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
                if (prefersLight) {
                    document.body.classList.add('light-theme');
                } else {
                    document.body.classList.remove('light-theme');
                }
                // Always show monitor icon for AUTO mode
                themeIcon.innerHTML = '<i data-lucide="monitor"></i>';
                themeText.textContent = 'Auto';
            }
            lucide.createIcons();

        }

        // Theme Toggle: cycles through Auto -> Light -> Dark -> Auto
        jdLogo.addEventListener('click', () => {
            window.location.reload();
        });

        jdLogo.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                window.location.reload();
            }
        });

        themeToggle.addEventListener('click', () => {
            const currentTheme = demoStorage.getItem('theme') || 'light';
            let nextTheme;

            if (currentTheme === 'auto' || !currentTheme) {
                nextTheme = 'light';
            } else if (currentTheme === 'light') {
                nextTheme = 'dark';
            } else { // dark
                nextTheme = 'auto';
            }

            demoStorage.setItem('theme', nextTheme);
            applyTheme(nextTheme);
        });

        const themeVersion = 'alive-white-1';
        if (demoStorage.getItem('themeVersion') !== themeVersion) {
            demoStorage.setItem('theme', 'light');
            demoStorage.setItem('themeVersion', themeVersion);
        }
        const savedTheme = demoStorage.getItem('theme');
        applyTheme(['light', 'dark', 'auto'].includes(savedTheme) ? savedTheme : 'light');

        // Listen for OS preference changes when in 'auto' mode
        const colorSchemeQuery = window.matchMedia('(prefers-color-scheme: light)');
        colorSchemeQuery.addEventListener('change', (e) => {
            const currentTheme = demoStorage.getItem('theme');
            // Only update if user hasn't manually set a preference
            if (currentTheme === 'auto') {
                applyTheme('auto');
            }
        });

        // Load saved colorful UI accents setting (default: disabled for clean two-tone system)
        const colorfulFocusToggle = document.getElementById('colorfulFocusToggle');
        const colorfulFocusSaved = demoStorage.getItem('colorfulFocus');
        if (colorfulFocusSaved === 'true') {
            document.body.classList.add('colorful-focus');
            colorfulFocusToggle.checked = true;
        } else {
            // Default: neutral white/gray icons and focus glows with red flash
            document.body.classList.remove('colorful-focus');
            colorfulFocusToggle.checked = false;
        }

        // Settings Modal
        const settingsBtn = document.getElementById('settingsBtn');
        const settingsModal = document.getElementById('settingsModal');
        const settingsClose = document.getElementById('settingsClose');
        const popInToggle = document.getElementById('popInToggle');
        const glowToggle = document.getElementById('glowToggle');
        const fadeToggle = document.getElementById('fadeToggle');
        const overlayPosition = document.getElementById('overlayPosition');
        const layoutOrder = document.getElementById('layoutOrder');
        const videoOverlay = document.getElementById('videoOverlay');

        // Migrate older independent EN/ZH settings to the shared Auto default once.
        if (demoStorage.getItem('voiceDefaultsVersion') !== 'unified-auto-v3') {
            demoStorage.setItem('voiceLanguage', 'auto');
            demoStorage.setItem('voiceDefaultsVersion', 'unified-auto-v3');
        }
        const savedVoiceLanguage = ['auto', 'zh', 'en'].includes(demoStorage.getItem('voiceLanguage'))
            ? demoStorage.getItem('voiceLanguage') : 'auto';
        // Settings state
        const settings = {
            popIn: demoStorage.getItem('popIn') !== 'false',
            glow: demoStorage.getItem('glow') !== 'false',
            fade: demoStorage.getItem('fade') !== 'false',
            overlayPosition: demoStorage.getItem('overlayPosition') || 'none',
            layoutOrder: demoStorage.getItem('layoutOrder') || 'vlm-first',
            ttsEnabled: false,
            fullDuplex: false,
            asrLanguage: savedVoiceLanguage,
            ttsLanguage: savedVoiceLanguage
        };

        // Load saved settings
        popInToggle.checked = settings.popIn;
        glowToggle.checked = settings.glow;
        fadeToggle.checked = settings.fade;
        overlayPosition.value = settings.overlayPosition;
        layoutOrder.value = settings.layoutOrder;
        if (ttsEnabledToggle) {
            ttsEnabledToggle.checked = settings.ttsEnabled;
            ttsEnabledToggle.disabled = true;
        }
        fullDuplexToggle.checked = settings.fullDuplex;
        fullDuplexToggle.addEventListener('change', () => setFullDuplex(fullDuplexToggle.checked));

        function isDuplexListening() {
            return settings.fullDuplex && voiceModeEnabled;
        }

        function resetDuplexDetection() {
            duplexUserSpeaking = false;
            duplexOnsetSamples = duplexPrerollSamples = 0;
            duplexPreroll = [];
        }

        function setFullDuplex(enabled) {
            settings.fullDuplex = Boolean(enabled);
            fullDuplexToggle.checked = settings.fullDuplex;
            duplexReplyGate = { prompt: null, waiting: false };
            resetDuplexDetection();
            if (isDuplexListening()) {
                // Keep any utterance already in progress when enabling the option.
                duplexUserSpeaking = asrHeardVoice && isSpeechActive();
                if (duplexUserSpeaking) stopTtsPlayback();
            } else if (voiceModeEnabled && !asrHeardVoice && (ttsSpeaking || voiceAwaitingPrompt !== null)) {
                finishSpeech({ sendPrompt: false });
            }
            maybeSpeakPendingTts();
            scheduleVoiceListening();
        }

        function resolveSpeechLanguage(text) {
            return settings.ttsLanguage === 'auto'
                ? (/[\u3400-\u9fff]/u.test(text) ? 'zh' : 'en') : settings.ttsLanguage;
        }

        function syncVoiceLanguageTabs() {
            voiceLanguageTabs.forEach(tab => {
                const selected = tab.dataset.language === settings.asrLanguage;
                tab.setAttribute('aria-checked', String(selected));
                tab.tabIndex = selected ? 0 : -1;
            });
        }

        function setVoiceLanguage(language) {
            if (!['auto', 'zh', 'en'].includes(language) || language === settings.asrLanguage) return;
            // Retain only the current reply; replay its current chunk in the new voice.
            const remaining = [currentTtsItem, ...pendingTtsQueue].filter(Boolean);
            closeTtsWebSocket();
            settings.asrLanguage = settings.ttsLanguage = language;
            demoStorage.setItem('voiceLanguage', language);
            finishSpeech({ sendPrompt: false });
            pendingTtsQueue = remaining.map(item => ({text: item.text, lang: resolveSpeechLanguage(item.text)}));
            syncVoiceLanguageTabs();
            syncSpeechButtons();
            maybeSpeakPendingTts();
            scheduleVoiceListening();
        }
        voiceLanguageTabs.forEach((tab, index) => {
            tab.addEventListener('click', () => setVoiceLanguage(tab.dataset.language));
            tab.addEventListener('keydown', event => {
                if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return;
                event.preventDefault();
                const offset = ['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 1;
                const next = event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + offset + 3) % 3;
                voiceLanguageTabs[next].focus();
                setVoiceLanguage(voiceLanguageTabs[next].dataset.language);
            });
        });
        syncVoiceLanguageTabs();

        async function refreshVoiceCapabilities() {
            const controller = new AbortController();
            const timer = setTimeout(() => controller.abort(), 10000);
            try {
                const response = await fetch('/api/voice/status', { signal: controller.signal });
                if (!response.ok) throw new Error('Voice service unavailable');
                const state = await response.json();
                voiceCapabilities = { asr: state.asr?.available === true, tts: state.tts?.available === true };
            } catch (error) {
                voiceCapabilities = { asr: false, tts: false };
            } finally {
                clearTimeout(timer);
            }
            ttsEnabledToggle.disabled = !voiceCapabilities.tts;
            if (!voiceCapabilities.tts && settings.ttsEnabled) setTtsEnabled(false);
            if (voiceModeEnabled && !voiceCapabilities.asr) {
                stopVoiceMode('Voice service unavailable. Click to retry.');
            }
            document.getElementById('voiceStatus').textContent = voiceCapabilities.asr && voiceCapabilities.tts
                ? 'English and Chinese voice ready'
                : voiceCapabilities.tts ? 'Microphone unavailable; sound and text input are ready'
                : voiceCapabilities.asr ? 'Microphone ready; sound is unavailable'
                : 'Voice unavailable; use text input';
            updatePromptAvailability();
            maybeSpeakPendingTts();
        }
        refreshVoiceCapabilities();
        setInterval(refreshVoiceCapabilities, 30000);

        // Apply overlay position
        function applyOverlayPosition(position) {
            videoOverlay.classList.remove('show', 'top', 'bottom');
            const resultText = document.getElementById('resultText');
            const hasDisplayText = (vlmHistory[vlmHistory.length - 1]?.response || getVlmDisplayText(lastText)).trim() !== '';

            if (position !== 'none') {
                // Overlay enabled - show on video, hide response balloon (keep prompt visible)
                if (hasDisplayText) {
                    videoOverlay.classList.add('show', position);
                }
                resultText.style.display = 'none';
            } else {
                // Overlay disabled - hide from video, show response balloon
                resultText.style.display = hasDisplayText ? 'flex' : 'none';
            }
        }
        applyOverlayPosition(settings.overlayPosition);

        // Apply layout order
        function isMobileLayout() {
            return window.matchMedia('(max-width: 768px)').matches;
        }

        function isPressToTalkLayout() {
            return isMobileLayout() && mobileVoiceMode;
        }

        function applyLayoutOrder(order) {
            const mainContent = document.querySelector('.main-content');
            const videoCard = document.querySelector('.video-card');
            const resultCard = document.getElementById('vlmOutputCard');

            if (!mainContent || !videoCard || !resultCard) {
                return;
            }

            if (isMobileLayout()) {
                mainContent.insertBefore(videoCard, resultCard);
            } else if (order === 'vlm-first') {
                // Conversation at top, Camera below (default)
                mainContent.insertBefore(resultCard, videoCard);
            } else {
                // Camera at top, Conversation below
                mainContent.insertBefore(videoCard, resultCard);
            }
        }
        applyLayoutOrder(settings.layoutOrder);

        window.matchMedia('(max-width: 768px)').addEventListener('change', () => {
            applyLayoutOrder(settings.layoutOrder);
            updatePromptAvailability();
            syncSpeechButtons();
        });

        // Open settings modal
        settingsBtn.addEventListener('click', () => {
            settingsModal.classList.add('show');
        });

        // Close settings modal
        settingsClose.addEventListener('click', () => {
            settingsModal.classList.remove('show');
        });

        // Close modal when clicking outside
        settingsModal.addEventListener('click', (e) => {
            if (e.target === settingsModal) {
                settingsModal.classList.remove('show');
            }
        });

        // Handle settings changes
        popInToggle.addEventListener('change', (e) => {
            settings.popIn = e.target.checked;
            demoStorage.setItem('popIn', settings.popIn);
        });

        glowToggle.addEventListener('change', (e) => {
            settings.glow = e.target.checked;
            demoStorage.setItem('glow', settings.glow);
        });

        fadeToggle.addEventListener('change', (e) => {
            settings.fade = e.target.checked;
            demoStorage.setItem('fade', settings.fade);
        });

        function syncTtsToggle() {
            ttsEnabledToggle.checked = settings.ttsEnabled;
            ttsToggleBtn.disabled = !voiceCapabilities.tts;
            ttsToggleBtn.setAttribute('aria-pressed', String(settings.ttsEnabled));
            const label = settings.ttsEnabled ? 'Turn spoken replies off' : 'Turn spoken replies on';
            ttsToggleBtn.setAttribute('aria-label', label);
            ttsToggleBtn.title = voiceCapabilities.tts ? label : 'Speech output is unavailable';
            ttsToggleLabel.textContent = settings.ttsEnabled ? 'Sound on' : 'Sound off';
            document.getElementById('ttsToggleIcon').innerHTML = settings.ttsEnabled ? voiceIcons.sound : voiceIcons.soundOff;
        }

        function setTtsEnabled(enabled) {
            settings.ttsEnabled = Boolean(enabled && voiceCapabilities.tts);
            if (!settings.ttsEnabled) closeTtsWebSocket();
            else {
                try { ensureTtsAudioContext(); }
                catch (error) {
                    settings.ttsEnabled = false;
                    closeTtsWebSocket();
                    voiceModeStatus.textContent = 'Sound could not start. Please retry.';
                }
            }
            syncTtsToggle();
            if (!voiceModeEnabled) {
                voiceModeStatus.textContent = settings.ttsEnabled
                    ? 'Microphone off · Spoken replies on'
                    : 'Microphone and sound are off';
            }
            scheduleVoiceListening();
        }
        ttsEnabledToggle.addEventListener('change', e => setTtsEnabled(e.target.checked));
        ttsToggleBtn.addEventListener('click', () => setTtsEnabled(!settings.ttsEnabled));

        colorfulFocusToggle.addEventListener('change', (e) => {
            const enabled = e.target.checked;
            demoStorage.setItem('colorfulFocus', enabled);
            if (enabled) {
                document.body.classList.add('colorful-focus');
            } else {
                document.body.classList.remove('colorful-focus');
            }
            // Force icon re-render to apply new colors
            lucide.createIcons();
        });

        overlayPosition.addEventListener('change', (e) => {
            settings.overlayPosition = e.target.value;
            demoStorage.setItem('overlayPosition', settings.overlayPosition);
            applyOverlayPosition(settings.overlayPosition);
        });

        layoutOrder.addEventListener('change', (e) => {
            settings.layoutOrder = e.target.value;
            demoStorage.setItem('layoutOrder', settings.layoutOrder);
            applyLayoutOrder(settings.layoutOrder);
        });

        // Panel Toggle
        function togglePanel(panelId) {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById(panelId);
            const toggle = document.getElementById(panelId + 'Toggle');
            const sidebarPanelIds = ['vlmConfig', 'cameraConfig'];
            const isSidebarPanel = sidebarPanelIds.includes(panelId);

            if (isSidebarPanel && sidebar?.classList.contains('docked')) {
                sidebar.classList.remove('docked');
                sidebarPanelIds.forEach(id => {
                    const panelContent = document.getElementById(id);
                    const panelToggle = document.getElementById(id + 'Toggle');
                    const isActive = id === panelId;
                    panelContent?.classList.toggle('collapsed', !isActive);
                    panelToggle?.classList.toggle('collapsed', !isActive);
                });
                return;
            }

            content?.classList.toggle('collapsed');
            toggle?.classList.toggle('collapsed');

            const allSidebarPanelsCollapsed = sidebarPanelIds
                .every(id => document.getElementById(id)?.classList.contains('collapsed'));
            if (isSidebarPanel && allSidebarPanelsCollapsed) {
                sidebar?.classList.add('docked');
            }
        }


        // Fullscreen Toggle
        function toggleFullscreen() {
            const videoCard = document.getElementById('videoCard');
            const fullscreenIcon = document.getElementById('fullscreenIcon');

            videoCard.classList.toggle('fullscreen');

            // Update icon: maximize when normal, minimize when fullscreen
            if (videoCard.classList.contains('fullscreen')) {
                fullscreenIcon.setAttribute('data-lucide', 'minimize');
                if (fullscreenPromptOverlay && promptEditor) {
                    fullscreenPromptOverlay.appendChild(document.getElementById('voiceModeBar'));
                    fullscreenPromptOverlay.appendChild(promptEditor);
                }
                // Sync current VLM output to fullscreen overlay
                syncVlmToFullscreen();
            } else {
                fullscreenIcon.setAttribute('data-lucide', 'maximize');
                restorePromptEditorHome();
            }
            lucide.createIcons();
        }

        function restorePromptEditorHome() {
            if (promptEditorHome && promptEditor && promptEditor.parentElement !== promptEditorHome) {
                promptEditorHome.appendChild(document.getElementById('voiceModeBar'));
                promptEditorHome.appendChild(promptEditor);
            }
        }

        // Sync VLM output to fullscreen overlay
        function syncVlmToFullscreen() {
            const fullscreenVlmContent = document.getElementById('fullscreenVlmContent');
            const fullscreenVlmMetrics = document.getElementById('fullscreenVlmMetrics');

            if (fullscreenVlmContent) {
                fullscreenVlmContent.textContent = getFullscreenVlmText();
            }

            // Add metrics if available
            const latency = document.getElementById('latencyValue')?.textContent;
            const count = document.getElementById('countValue')?.textContent;
            if (latency && count) {
                fullscreenVlmMetrics.innerHTML = `<span>Latency: ${latency}ms</span><span>Count: ${count}</span>`;
            }
        }

        function normalizeFullscreenLine(text) {
            return String(text || '').replace(/\s+/g, ' ').trim();
        }

        function getFullscreenVlmText() {
            const lines = [];

            vlmHistory.forEach(entry => {
                if (entry.kind === 'background' || entry.contextExcluded) {
                    return;
                }
                const prompt = normalizeFullscreenLine(entry.prompt);
                const response = normalizeFullscreenLine(entry.response);

                if (hasVisiblePrompt(entry) && prompt) {
                    lines.push(`Input: ${prompt}`);
                }
                if (response) {
                    lines.push(`Output: ${response}`);
                }
            });

            const liveResponse = normalizeFullscreenLine(getVlmDisplayText(lastText));
            if (!lines.length && liveResponse) {
                lines.push(`Output: ${liveResponse}`);
            }

            return lines.slice(-4).join('\n') || 'Ready';
        }

        // ESC key to exit fullscreen
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                const videoCard = document.getElementById('videoCard');
                if (videoCard.classList.contains('fullscreen')) {
                    toggleFullscreen();
                }
            }
        });

        // API Key Field Toggle
        function toggleApiKeyField() {
            const field = document.getElementById('apiKeyField');
            const toggle = document.getElementById('apiKeyToggle');
            field.classList.toggle('collapsed');
            toggle.classList.toggle('collapsed');
        }

        // Check if API Base URL requires API key
        function checkApiKeyRequirement(url) {
            const apiKeyField = document.getElementById('apiKeyField');
            const apiKeyToggle = document.getElementById('apiKeyToggle');

            // Check if URL is a remote service (not localhost or 127.0.0.1)
            const isLocal = url.includes('localhost') || url.includes('127.0.0.1') || url.includes('0.0.0.0');
            const isRemote = !isLocal;

            if (isRemote) {
                // Show API key field for remote services
                apiKeyField.classList.remove('collapsed');
                apiKeyToggle.classList.remove('collapsed');
                console.log('Remote API detected - API Key field expanded');
            } else {
                // Hide API key field for local services
                apiKeyField.classList.add('collapsed');
                apiKeyToggle.classList.add('collapsed');
                console.log('Local API detected - API Key field collapsed');
            }
        }

        // Status Update
        function updateStatus(message, state) {
            connectionStatus.textContent = message;
            connectionStatus.className = `status-badge ${state}`;
        }

        function updatePromptAvailability() {
            const canSendPrompt = Boolean(isAnalysisRunning);
            promptSendBtn.disabled = !canSendPrompt;
            speechButtons.forEach(button => {
                button.disabled = voiceModeEnabled || asrSendPromptWhenFinal || (isSpeechActive() ? false : (!canSendPrompt || !voiceCapabilities.asr));
            });
            promptText.placeholder = canSendPrompt ? 'Ask about what you see…' : 'Open your camera to start a conversation';
            promptSendBtn.title = canSendPrompt ? 'Send prompt' : 'Start the video to send';
            syncSpeechButtons();
            syncVoiceMode();

            processEvery.disabled = isAnalysisRunning;
            processEvery.title = isAnalysisRunning ? 'Stop the video before changing this setting' : '';
            framesPerBatch.disabled = isAnalysisRunning;
            framesPerBatch.title = isAnalysisRunning ? 'Stop the video before changing this setting' : '';
        }

        function setVideoWaitingForStream(waiting) {
            const videoCard = document.getElementById('videoCard');
            videoCard?.classList.toggle('waiting-for-stream', waiting);
        }

        function resetVideoButtons() {
            const bigBtn = document.getElementById('bigStartBtn');
            const smallStopBtn = document.getElementById('smallStopBtn');
            bigBtn.classList.remove('animating', 'streaming');
            smallStopBtn.classList.remove('show');
        }

        function cancelRevealVideoFallback() {
            if (revealVideoFallbackTimeout) {
                clearTimeout(revealVideoFallbackTimeout);
                revealVideoFallbackTimeout = null;
            }
        }

        function revealVideoWhenReady(token) {
            if (token !== streamStartToken) {
                return;
            }
            cancelRevealVideoFallback();
            revealVideoAfterMetricsToken = null;
            setVideoWaitingForStream(false);
            updateStatus('Streaming', 'connected');
        }

        function showProcessedVideoStream(stream, token) {
            if (token !== streamStartToken) {
                return;
            }
            videoElement.srcObject = stream;

            const markStreaming = () => {
                if (token !== streamStartToken || videoElement.srcObject !== stream) {
                    return;
                }
                isAnalysisRunning = true;
                updatePromptAvailability();
                if (revealVideoAfterMetricsToken === token) {
                    updateStatus('Preparing first metrics...', 'processing');
                    cancelRevealVideoFallback();
                    revealVideoFallbackTimeout = setTimeout(() => {
                        revealVideoWhenReady(token);
                    }, 5000);
                } else {
                    revealVideoWhenReady(token);
                }
            };

            const playPromise = videoElement.play();
            if (playPromise && typeof playPromise.then === 'function') {
                playPromise.then(markStreaming).catch(err => {
                    console.error('Error playing video:', err);
                    markStreaming();
                });
            } else {
                markStreaming();
            }
        }

        // Detect Local VLM Services
        async function detectServices() {
            try {
                const response = await fetch('/detect-services');
                const data = await response.json();

                if (data.default) {
                    const service = data.default;
                    console.log('Detected service:', service.name);

                    // Update API Base URL
                    apiBaseUrl.value = service.url;

                    // Check if API key is required
                    checkApiKeyRequirement(service.url);

                    // Update hint text
                    const hintDiv = apiBaseUrl.nextElementSibling;
                    if (data.detected.length > 1) {
                        const serviceNames = data.detected.map(s => s.name).join(', ');
                        hintDiv.textContent = `Detected: ${serviceNames}`;
                    } else if (service.name === 'NVIDIA API Catalog') {
                        hintDiv.textContent = 'No local VLM services found. Using NVIDIA API Catalog (requires API key from build.nvidia.com)';
                    }
                }
            } catch (error) {
                console.error('Error detecting services:', error);
                // Default to showing API key field on error
                checkApiKeyRequirement('https://');
            }
        }

        function displayModelName(model) {
            if (model === 'streaming-infer-adapter') return 'ALIVE';
            if (/qwen/i.test(String(model || ''))) return 'ALIVE';
            return model;
        }

        function formatDebugPayload(payload) {
            // Alias model labels in the UI; keep transport IDs unchanged.
            return JSON.stringify(payload, (key, value) =>
                ['model', 'model_id', 'model_name'].includes(key) && typeof value === 'string'
                    ? displayModelName(value) : value, 2);
        }

        // Fetch Models
        async function fetchModels() {
            try {
                modelSelect.innerHTML = '<option value="">Loading models...</option>';

                // Get current API settings from UI
                const currentApiBase = apiBaseUrl.value.trim();
                const currentApiKey = apiKey.value.trim();

                // Build query params
                const params = new URLSearchParams();
                if (currentApiBase) {
                    params.append('api_base', currentApiBase);
                }
                if (currentApiKey) {
                    params.append('api_key', currentApiKey);
                }

                const url = `/models${params.toString() ? '?' + params.toString() : ''}`;
                const response = await fetch(url);
                const data = await response.json();

                if (data.models && data.models.length > 0) {
                    modelSelect.innerHTML = '';
                    let currentModel = null;
                    let autoSelectedModel = null;

                    data.models.forEach((model, index) => {
                        const option = document.createElement('option');
                        option.value = model.id;
                        option.textContent = displayModelName(model.id);
                        if (model.current) {
                            option.selected = true;
                            currentModel = model.id;
                        }
                        modelSelect.appendChild(option);
                    });

                    // If no current model, auto-select first model and apply
                    if (!currentModel && data.models.length > 0) {
                        autoSelectedModel = data.models[0].id;
                        modelSelect.value = autoSelectedModel;
                        currentModel = autoSelectedModel;

                        // Auto-apply the new model
                        console.log(`Auto-selected model: ${autoSelectedModel}`);
                        applyApiSettings({ showFeedback: false });
                    }

                    // Update model name in VLM output header
                    if (currentModel) {
                        document.getElementById('modelName').textContent = displayModelName(currentModel);
                    }
                } else {
                    modelSelect.innerHTML = '<option value="">No models available</option>';
                }
            } catch (error) {
                console.error('Error fetching models:', error);
                modelSelect.innerHTML = '<option value="">Error loading models</option>';
            }
        }

        // Handle model change
        modelSelect.addEventListener('change', (e) => {
            const newModel = e.target.value;
            if (!newModel) return;

            // Update model name in VLM output header
            document.getElementById('modelName').textContent = displayModelName(newModel);

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                // Send model, API base, and API key together
                websocket.send(JSON.stringify({
                    type: 'update_model',
                    model: newModel,
                    api_base: apiBaseUrl.value.trim(),
                    api_key: apiKey.value.trim()
                }));
                updateStatus('Model configured', 'connected');
            }

            // Trigger flash animation
            modelSelect.classList.add('applied');
            setTimeout(() => {
                modelSelect.classList.remove('applied');
            }, 600);
        });

        // Also trigger flash on blur (when dropdown closes)
        modelSelect.addEventListener('blur', () => {
            const currentModel = modelSelect.value;
            if (currentModel) {
                // Trigger flash animation
                modelSelect.classList.add('applied');
                setTimeout(() => {
                    modelSelect.classList.remove('applied');
                }, 600);
            }
        });

        // Helper function to apply prompt settings
        function applyPromptSettings() {
            if (!isAnalysisRunning || !websocket || websocket.readyState !== WebSocket.OPEN) {
                updateStatus('Start the video and wait for the connection before sending.', 'disconnected');
                return false;
            }
            const newPrompt = cleanBackgroundQuestionText(promptText.value.trim());
            if (!newPrompt) return false;
            try {
                websocket.send(JSON.stringify({
                    type: 'update_prompt', prompt: newPrompt, client_sent_at_ms: Date.now()
                }));
            } catch (error) {
                updateStatus('Message not sent. Please retry.', 'disconnected');
                return false;
            }
            if (isDuplexListening()) {
                stopTtsPlayback();
                duplexReplyGate = { prompt: newPrompt, waiting: true };
            }
            if (voiceModeEnabled) {
                voiceAwaitingPrompt = newPrompt;
                clearTimeout(voiceListenTimer);
                clearTimeout(voiceReplyTimer);
                voiceReplyTimer = setTimeout(() => {
                    if (voiceModeEnabled && voiceAwaitingPrompt !== null) {
                        if (isDuplexListening()) {
                            voiceAwaitingPrompt = null;
                            voiceReplyTimer = null;
                            updateStatus('Reply delayed. You can keep speaking.', 'connected');
                            scheduleVoiceListening();
                        } else {
                            stopVoiceMode('No reply yet. You can retry with voice or text.');
                        }
                    }
                }, 60000);
                syncVoiceMode();
            }
            // Manual Send during recording ends that utterance too. Late ASR
            // events cannot put previously submitted words back into the input.
            if (asrWs || isSpeechActive()) finishSpeech({ sendPrompt: false });
            currentPromptText = newPrompt;
            appendPromptHistoryEntry(newPrompt);
            promptText.value = '';
            asrFinalText = asrPartialText = asrLastFinalText = '';
            resizePromptInput();
            scheduleVoiceListening();
            return true;
        }

        function resizePromptInput() {
            promptText.style.height = 'auto';
            promptText.style.height = Math.min(promptText.scrollHeight, 120) + 'px';
        }

        function syncVoiceMode() {
            voiceModeBtn.disabled = !voiceModeEnabled && !voiceCapabilities.asr;
            voiceModeBtn.setAttribute('aria-pressed', String(voiceModeEnabled));
            const label = voiceModeEnabled ? 'Turn microphone off' : 'Turn microphone on';
            voiceModeBtn.setAttribute('aria-label', label);
            voiceModeBtn.title = voiceCapabilities.asr ? label : 'Speech input is unavailable';
            voiceModeLabel.textContent = voiceModeEnabled ? 'Mic on' : 'Mic off';
            document.getElementById('voiceModeIcon').innerHTML = voiceModeEnabled ? voiceIcons.mic : voiceIcons.micOff;
            syncTtsToggle();
            if (voiceModeEnabled) {
                voiceModeStatus.textContent = voiceModeStarting ? 'Starting camera…'
                    : ttsSpeaking ? (isDuplexListening()
                        ? (asrRecording ? 'Speaking + listening — speak to interrupt' : 'Speaking — connecting microphone…')
                        : 'Speaking — microphone paused')
                    : isDuplexListening() && asrRecording ? (duplexUserSpeaking
                        ? 'Listening — pause to send'
                        : voiceAwaitingPrompt !== null ? 'Listening — waiting for reply…' : 'Listening — full duplex')
                    : voiceAwaitingPrompt !== null ? 'Waiting for a reply…'
                    : asrSendPromptWhenFinal ? 'Sending…'
                    : asrRecording ? 'Listening — pause to send'
                    : 'Connecting microphone…';
            }
        }

        function canResumeVoiceListening() {
            return voiceModeEnabled && !voiceModeStarting && isAnalysisRunning && !document.hidden && !isSpeechActive()
                && (isDuplexListening() || (voiceAwaitingPrompt === null && !ttsSpeaking && !pendingTtsQueue.length));
        }

        function scheduleVoiceListening() {
            syncVoiceMode();
            if (!canResumeVoiceListening()) return;
            clearTimeout(voiceListenTimer);
            const generation = voiceModeGeneration;
            voiceListenTimer = setTimeout(() => {
                voiceListenTimer = null;
                if (generation === voiceModeGeneration && canResumeVoiceListening()) startSpeech({ mode: 'auto' });
            }, isDuplexListening() ? 120 : 400);
        }

        function stopVoiceMode(message = 'Microphone off') {
            if (!voiceModeEnabled) return;
            voiceModeEnabled = voiceModeStarting = false;
            voiceModeGeneration += 1;
            duplexReplyGate = { prompt: null, waiting: false };
            voiceAwaitingPrompt = null;
            clearTimeout(voiceListenTimer);
            clearTimeout(voiceReplyTimer);
            voiceListenTimer = voiceReplyTimer = null;
            finishSpeech({ sendPrompt: false });
            voiceModeStatus.textContent = message;
            updatePromptAvailability();
        }

        async function toggleVoiceMode() {
            if (voiceModeEnabled) { stopVoiceMode(); return; }
            if (!voiceCapabilities.asr) return;
            if (isSpeechActive()) finishSpeech({ sendPrompt: false });
            voiceModeEnabled = true;
            const generation = ++voiceModeGeneration;
            mobileVoiceMode = false;
            try {
                voiceModeStarting = !isAnalysisRunning;
                syncVoiceMode();
                if (!isAnalysisRunning) {
                    await start();
                    const deadline = Date.now() + 15000;
                    while (voiceModeEnabled && generation === voiceModeGeneration
                        && !isAnalysisRunning && Date.now() < deadline) {
                        await new Promise(resolve => setTimeout(resolve, 100));
                    }
                }
                if (!voiceModeEnabled || generation !== voiceModeGeneration) return;
                voiceModeStarting = false;
                if (!isAnalysisRunning) {
                    stopVoiceMode('Camera did not start. Check permissions and retry.');
                    return;
                }
                updatePromptAvailability();
                scheduleVoiceListening();
            } catch (error) {
                stopVoiceMode('Microphone could not start. Check permissions and retry.');
            }
        }
        voiceModeBtn.addEventListener('click', toggleVoiceMode);
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) stopVoiceMode('Microphone paused. Click to resume.');
        });

        function closePromptPopovers(except = null) {
            if (except !== 'presets') {
                promptPresetMenu.classList.add('hidden');
                promptPresetBtn.classList.remove('active');
            }
        }

        function flashPromptControl(element) {
            element.classList.add('applied');
            setTimeout(() => {
                element.classList.remove('applied');
            }, 600);
        }


        function syncSpeechButtons() {
            const canSendPrompt = Boolean(isAnalysisRunning);
            const pressMode = isPressToTalkLayout();
            const speechActive = isSpeechActive();
            const speechVisualActive = isSpeechVisualActive();
            const idleTitle = !voiceCapabilities.asr ? 'Voice unavailable' : canSendPrompt
                ? (isMobileLayout() ? (pressMode ? 'Hold to speak' : 'Switch to voice input') : 'Click to speak')
                : 'Start the video to speak';

            promptEditor?.classList.toggle('mobile-voice-mode', pressMode);
            promptEditor?.classList.toggle('voice-ripple-active', pressMode && speechVisualActive);
            fullscreenPromptOverlay?.classList.toggle('voice-panel-open', pressMode);

            speechButtons.forEach(button => {
                button.classList.toggle('recording', speechVisualActive);
                button.title = speechVisualActive
                    ? (pressMode ? 'Release to send' : 'Stop speaking')
                    : idleTitle;

                const label = button.querySelector('.speech-label');
                if (label) {
                    if (speechVisualActive) {
                        label.textContent = pressMode ? 'Release to send' : 'Stop speaking';
                    } else {
                        label.textContent = pressMode ? 'Hold to speak' : (settings.asrLanguage === 'auto' ? 'Speak' : settings.asrLanguage === 'en' ? 'Speak EN' : 'Speak ZH');
                    }
                }
            });
            lucide.createIcons();
        }

        function isSpeechActive() {
            return Boolean(asrStarting || asrRecording || asrSendPromptWhenFinal);
        }

        function isSpeechVisualActive() {
            if (isPressToTalkLayout()) {
                return asrPointerId !== null || asrStarting || asrRecording || Boolean(asrStream || asrAudioContext || asrWs);
            }
            return isSpeechActive();
        }

        function setSpeechRecording(recording) {
            asrStarting = false;
            asrRecording = recording;
            syncSpeechButtons();
            updatePromptAvailability();
        }

        function suppressNextSpeechClick() {
            ignoreNextSpeechClick = true;
            if (ignoreSpeechClickTimeout) {
                clearTimeout(ignoreSpeechClickTimeout);
            }
            ignoreSpeechClickTimeout = setTimeout(() => {
                ignoreNextSpeechClick = false;
                ignoreSpeechClickTimeout = null;
            }, 450);
        }

        function floatToInt16(input) {
            const output = new Int16Array(input.length);
            for (let i = 0; i < input.length; i += 1) {
                const sample = Math.max(-1, Math.min(1, input[i]));
                output[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
            }
            return output;
        }

        function downsampleToInt16(input, inputSampleRate) {
            if (inputSampleRate === ASR_TARGET_SAMPLE_RATE) {
                return floatToInt16(input).buffer;
            }

            const ratio = inputSampleRate / ASR_TARGET_SAMPLE_RATE;
            const length = Math.floor(input.length / ratio);
            const output = new Float32Array(length);
            let inputOffset = 0;

            for (let i = 0; i < length; i += 1) {
                const nextOffset = Math.floor((i + 1) * ratio);
                let sum = 0;
                let count = 0;
                for (let j = inputOffset; j < nextOffset && j < input.length; j += 1) {
                    sum += input[j];
                    count += 1;
                }
                output[i] = count ? sum / count : 0;
                inputOffset = nextOffset;
            }

            return floatToInt16(output).buffer;
        }

        function getAudioRms(input) {
            let sum = 0;
            for (let i = 0; i < input.length; i += 1) {
                sum += input[i] * input[i];
            }
            return Math.sqrt(sum / Math.max(1, input.length));
        }

        function getMicErrorMessage(error) {
            if (!window.isSecureContext) {
                return 'Microphone access requires HTTPS or localhost.';
            }
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                return 'Microphone access is unavailable in this browser.';
            }
            if (error && error.name === 'NotAllowedError') {
                return 'Allow microphone access in your browser and try again.';
            }
            if (error && error.name === 'NotFoundError') {
                return 'No microphone found.';
            }
            return `Microphone unavailable: ${error ? error.message : 'Unknown error'}`;
        }

        function updatePromptFromSpeech() {
            const text = [asrFinalText, asrPartialText].filter(Boolean).join(settings.asrLanguage === 'zh' ? '' : ' ');
            promptText.value = text;
            resizePromptInput();
        }

        function handleAsrResult(data) {
            if (!asrWs || !['IS_PARTIAL', 'IS_FINAL', 'IS_END'].includes(data.event)) return;
            if (data.text) {
                asrHeardVoice = true;
                if (isDuplexListening()) beginDuplexUtterance();
            }
            if (data.final) {
                const text = String(data.text || '').trim();
                if (text && text !== asrLastFinalText) {
                    asrFinalText += (settings.asrLanguage !== 'zh' && asrFinalText ? ' ' : '') + text;
                    asrLastFinalText = text;
                }
                asrPartialText = '';
                updatePromptFromSpeech();
                if (asrSendPromptWhenFinal || asrStopMode === 'auto') {
                    finishSpeech({ sendPrompt: true });
                }
            } else {
                asrPartialText = data.text || '';
                updatePromptFromSpeech();
            }
        }

        function beginDuplexUtterance() {
            if (duplexUserSpeaking) return;
            duplexUserSpeaking = true;
            asrHeardVoice = true;
            duplexReplyGate = { prompt: '', waiting: true };
            voiceAwaitingPrompt = null;
            clearTimeout(voiceReplyTimer);
            voiceReplyTimer = null;
            stopTtsPlayback();
            syncVoiceMode();
        }

        function sendDuplexAudio(audio) {
            const pcm = new Int16Array(audio);
            const output = [];
            for (let pos = 0; pos < pcm.length; pos += 320) {
                const frame = pcm.subarray(pos, pos + 320);
                let sum = 0;
                for (const sample of frame) sum += (sample / 32768) ** 2;
                const rms = Math.sqrt(sum / frame.length);
                if (duplexUserSpeaking) {
                    if (rms >= ASR_SILENCE_RMS_THRESHOLD) asrLastVoiceTime = performance.now();
                    output.push(frame);
                    continue;
                }
                duplexPreroll.push(frame.slice());
                duplexPrerollSamples += frame.length;
                while (duplexPrerollSamples > DUPLEX_PREROLL_SAMPLES && duplexPreroll.length > 1) {
                    duplexPrerollSamples -= duplexPreroll.shift().length;
                }
                duplexOnsetSamples = rms >= DUPLEX_ONSET_RMS ? duplexOnsetSamples + frame.length : 0;
                if (duplexOnsetSamples >= DUPLEX_ONSET_SAMPLES) {
                    beginDuplexUtterance();
                    asrLastVoiceTime = performance.now();
                    output.push(...duplexPreroll);
                    duplexPreroll = [];
                    duplexPrerollSamples = 0;
                } else {
                    output.push(new Int16Array(frame.length));
                }
            }
            const merged = new Int16Array(output.reduce((count, part) => count + part.length, 0));
            let offset = 0;
            for (const part of output) { merged.set(part, offset); offset += part.length; }
            if (merged.length) asrWs.send(merged.buffer);
            if (duplexUserSpeaking && asrStopMode === 'auto'
                && performance.now() - asrLastVoiceTime >= ASR_SILENCE_AUTO_STOP_MS) stopSpeech();
        }

        async function prepareSpeechMic(token) {
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    channelCount: 1,
                    echoCancellation: true,
                    noiseSuppression: true,
                    autoGainControl: true
                }
            });
            if (token !== asrStartToken || asrStopRequested || !isAnalysisRunning) {
                stream.getTracks().forEach(track => track.stop());
                return false;
            }
            asrStream = stream;

            asrAudioContext = new AudioContext();
            asrSource = asrAudioContext.createMediaStreamSource(asrStream);
            asrProcessor = asrAudioContext.createScriptProcessor(ASR_AUDIO_BUFFER_SIZE, 1, 1);
            asrSilence = asrAudioContext.createGain();
            asrSilence.gain.value = 0;
            asrLastVoiceTime = performance.now();

            asrProcessor.onaudioprocess = (event) => {
                if (token !== asrStartToken || !asrRecording || !asrWs || asrWs.readyState !== WebSocket.OPEN) {
                    return;
                }

                const input = event.inputBuffer.getChannelData(0);
                if (isDuplexListening() && !asrUsesServerVad) {
                    sendDuplexAudio(downsampleToInt16(input, asrAudioContext.sampleRate));
                    return;
                }
                const rms = getAudioRms(input);
                const now = performance.now();
                if (!asrUsesServerVad && rms >= ASR_SILENCE_RMS_THRESHOLD) {
                    asrLastVoiceTime = now;
                    asrHeardVoice = true;
                } else if (!asrUsesServerVad && asrStopMode === 'auto' && (!voiceModeEnabled || asrHeardVoice)
                    && now - asrLastVoiceTime >= ASR_SILENCE_AUTO_STOP_MS) {
                    stopSpeech();
                    return;
                }

                const audio = downsampleToInt16(input, asrAudioContext.sampleRate);
                if (audio.byteLength > 0) {
                    asrWs.send(audio);
                }
            };

            asrSource.connect(asrProcessor);
            asrProcessor.connect(asrSilence);
            asrSilence.connect(asrAudioContext.destination);
            return true;
        }

        function connectAsrWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            // Press-to-talk may span pauses; click-to-talk ends after one utterance.
            const continuous = asrStopMode === 'press' ? '&continuous=1' : '';
            const ws = new WebSocket(`${protocol}//${window.location.host}${ASR_WS_PATH}?session_id=${encodeURIComponent(sessionId)}&lang=${settings.asrLanguage}${continuous}`);
            asrWs = ws;
            ws.binaryType = 'arraybuffer';
            ws.onmessage = (event) => {
                if (asrWs !== ws) return;
                const data = JSON.parse(event.data);
                if (data.type === 'status' && data.message === 'connected') {
                    if (!isAnalysisRunning || asrStopRequested) {
                        finishSpeech({ sendPrompt: false });
                        return;
                    }
                    asrUsesServerVad = data.speech_detection === 'silero-vad';
                    asrLastVoiceTime = performance.now();
                    setSpeechRecording(true);
                    if (voiceModeEnabled || Number(data.max_recording_sec) > 0) {
                        // Respect each provider's stream limit, including silent
                        // hands-free listening. Renew before the backend closes.
                        const maxSeconds = Number(data.max_recording_sec) || 120;
                        const renewMs = Math.max(1000, (maxSeconds - 2) * 1000);
                        asrRenewTimer = setTimeout(() => {
                            if (asrWs === ws) {
                                if (asrHeardVoice) stopSpeech();
                                else finishSpeech({ sendPrompt: false });
                            }
                        }, renewMs);
                    }
                } else if (data.type === 'speech_activity' && data.active) {
                    asrHeardVoice = true;
                    asrLastVoiceTime = performance.now();
                    if (isDuplexListening()) beginDuplexUtterance();
                } else if (data.type === 'error') {
                    updateStatus(data.message, 'disconnected');
                    stopVoiceMode('Speech recognition unavailable. Click to retry.');
                    finishSpeech({ sendPrompt: false });
                } else if (data.type === 'result') {
                    handleAsrResult(data);
                }
            };
            ws.onclose = () => {
                if (asrWs !== ws) return;
                if (voiceModeEnabled && !asrSendPromptWhenFinal) {
                    stopVoiceMode('Microphone connection closed. Click to retry.');
                    return;
                }
                // Only an explicit stop/final result authorizes submission.
                finishSpeech({ sendPrompt: asrSendPromptWhenFinal });
            };
            ws.onerror = () => {
                if (asrWs !== ws) return;
                updateStatus('Speech recognition connection failed. Please retry.', 'disconnected');
                stopVoiceMode('Microphone connection failed. Click to retry.');
                finishSpeech({ sendPrompt: false });
            };
        }

        async function startSpeech({ mode = 'auto' } = {}) {
            if (!voiceCapabilities.asr) {
                updateStatus('Voice unavailable. Please use text input.', 'disconnected');
                return;
            }
            if (!isAnalysisRunning) {
                updateStatus('Start the video first', 'disconnected');
                updatePromptAvailability();
                return;
            }

            if (isSpeechActive() || asrStream || asrAudioContext || asrWs) {
                return;
            }

            if (!isDuplexListening()) stopTtsPlayback({ clearQueue: false, requeueCurrent: true });
            resetDuplexDetection();
            const token = ++asrStartToken;
            asrStarting = true;
            syncSpeechButtons();
            updatePromptAvailability();
            asrStopMode = mode;
            asrHeardVoice = false;
            asrUsesServerVad = false;
            asrStopRequested = false;
            if (mode !== 'press') {
                speechButtons.forEach(button => {
                    button.disabled = true;
                });
            }
            asrFinalText = '';
            asrPartialText = '';
            asrLastFinalText = '';
            asrSendPromptWhenFinal = false;
            if (asrFinalFallbackTimer) {
                clearTimeout(asrFinalFallbackTimer);
                asrFinalFallbackTimer = null;
            }
            promptText.value = '';
            resizePromptInput();

            try {
                if (!await prepareSpeechMic(token)) return;
                if (token !== asrStartToken || asrStopRequested || !isAnalysisRunning) {
                    await stopSpeech({ sendEnd: false, sendPrompt: false });
                    return;
                }
                connectAsrWebSocket();
            } catch (error) {
                updateStatus(getMicErrorMessage(error), 'disconnected');
                stopVoiceMode(getMicErrorMessage(error));
                updatePromptAvailability();
                await stopSpeech({ sendEnd: false, sendPrompt: false });
            }
        }

        function releaseSpeechMic() {
            // Detach synchronously before awaiting AudioContext.close. Final and
            // close events may arrive together, and cleanup must be idempotent.
            const context = asrAudioContext;
            clearTimeout(asrRenewTimer);
            asrRenewTimer = null;
            asrProcessor?.disconnect();
            asrSource?.disconnect();
            asrSilence?.disconnect();
            asrStream?.getTracks().forEach(track => track.stop());
            asrProcessor = asrSource = asrSilence = asrStream = asrAudioContext = null;
            if (context && context.state !== 'closed') context.close().catch(console.warn);
        }

        function finishSpeech({ sendPrompt = false } = {}) {
            asrStartToken += 1;
            asrStopRequested = true;
            const ws = asrWs;
            asrWs = null; // Ignore late results before clearing/submitting text.
            asrStarting = asrRecording = asrSendPromptWhenFinal = false;
            asrPointerId = null;
            if (asrFinalFallbackTimer) clearTimeout(asrFinalFallbackTimer);
            asrFinalFallbackTimer = null;
            releaseSpeechMic();
            if (ws && [WebSocket.CONNECTING, WebSocket.OPEN].includes(ws.readyState)) ws.close();
            if (sendPrompt && promptText.value.trim()) {
                if (applyPromptSettings()) flashPromptControl(promptText);
                else stopVoiceMode('Message not sent. Your text is kept for retry.');
            }
            asrFinalText = asrPartialText = asrLastFinalText = '';
            resetDuplexDetection();
            if (duplexReplyGate.prompt === '') duplexReplyGate = { prompt: null, waiting: false };
            if (isMobileLayout()) mobileVoiceMode = false;
            updatePromptAvailability();
            maybeSpeakPendingTts();
        }

        async function stopSpeech({ sendEnd = true, sendPrompt = true } = {}) {
            if (!sendEnd || !sendPrompt) {
                finishSpeech({ sendPrompt });
                return;
            }
            if (asrSendPromptWhenFinal) return;
            asrStartToken += 1;
            asrStopRequested = true;
            const wasRecording = asrRecording;
            asrStarting = asrRecording = false;
            asrPointerId = null;
            releaseSpeechMic();
            if (wasRecording && asrWs?.readyState === WebSocket.OPEN) {
                asrSendPromptWhenFinal = true;
                asrFinalFallbackTimer = setTimeout(() => finishSpeech({ sendPrompt: true }), ASR_FINAL_FALLBACK_MS);
                asrWs.send(JSON.stringify({ type: 'end' }));
                updatePromptAvailability();
            } else {
                finishSpeech({ sendPrompt });
            }
        }

        function finishPressToTalk({ sendEnd = true, sendPrompt = true } = {}) {
            if (!isPressToTalkLayout() && asrPointerId === null) {
                return;
            }
            asrPointerId = null;
            stopSpeech({ sendEnd, sendPrompt });
            mobileVoiceMode = false;
            updatePromptAvailability();
        }

        promptPresetBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const willOpen = promptPresetMenu.classList.contains('hidden');
            closePromptPopovers(willOpen ? 'presets' : null);
            promptPresetMenu.classList.toggle('hidden', !willOpen);
            promptPresetBtn.classList.toggle('active', willOpen);
        });

        promptPresetOptions.forEach(option => {
            option.addEventListener('click', () => {
                promptPresetOptions.forEach(item => item.classList.remove('selected'));
                option.classList.add('selected');
                promptText.value = option.dataset.prompt || '';
                resizePromptInput();
                closePromptPopovers();
                promptText.focus();
            });
        });

        document.addEventListener('click', (e) => {
            if (!e.target.closest('.chat-prompt-shell')) {
                closePromptPopovers();
            }
        });

        let promptImeComposing = false;
        let promptCompositionEndedAt = 0;

        promptText.addEventListener('compositionstart', () => {
            promptImeComposing = true;
        });

        promptText.addEventListener('compositionend', () => {
            promptImeComposing = false;
            promptCompositionEndedAt = Date.now();
        });

        function isPromptImeEnter(e) {
            return Boolean(
                promptImeComposing ||
                e.isComposing ||
                e.keyCode === 229 ||
                Date.now() - promptCompositionEndedAt < 30
            );
        }

        // Apply prompt on Enter key (Shift+Enter for newline)
        promptText.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                if (isPromptImeEnter(e)) {
                    return;
                }
                e.preventDefault();
                if (applyPromptSettings()) {
                    flashPromptControl(promptText);
                }
            }
        });

        promptText.addEventListener('input', resizePromptInput);

        function toggleSpeechByClick() {
            if (isSpeechActive()) {
                stopSpeech();
            } else {
                startSpeech({ mode: 'auto' });
            }
        }

        function enterMobileVoiceMode(event) {
            if (!isMobileLayout() || mobileVoiceMode) {
                return false;
            }
            event.preventDefault();
            mobileVoiceMode = true;
            closePromptPopovers();
            updatePromptAvailability();
            return true;
        }

        function preventSpeechLongPressMenu(event) {
            if (
                isMobileLayout() &&
                (event.target === speechBtn || event.target.closest?.('.speech-control, .mobile-voice-mode'))
            ) {
                event.preventDefault();
            }
        }

        function startPressToTalk(event) {
            if (!isMobileLayout()) {
                return;
            }
            event.preventDefault();
            if (enterMobileVoiceMode(event)) {
                asrPointerId = event.pointerId;
                suppressNextSpeechClick();
                event.currentTarget.setPointerCapture?.(event.pointerId);
                syncSpeechButtons();
                startSpeech({ mode: 'press' });
                return;
            }
            if (isSpeechActive() || asrStream || asrAudioContext || asrWs) {
                return;
            }
            asrPointerId = event.pointerId;
            suppressNextSpeechClick();
            event.currentTarget.setPointerCapture?.(event.pointerId);
            syncSpeechButtons();
            startSpeech({ mode: 'press' });
        }

        function stopPressToTalk(event) {
            if (!isPressToTalkLayout() || asrPointerId !== event.pointerId) {
                return;
            }
            event.preventDefault();
            event.currentTarget.releasePointerCapture?.(event.pointerId);
            finishPressToTalk({ sendEnd: true, sendPrompt: true });
        }

        speechBtn.addEventListener('pointerdown', startPressToTalk);
        speechBtn.addEventListener('contextmenu', preventSpeechLongPressMenu);
        speechBtn.addEventListener('selectstart', preventSpeechLongPressMenu);
        promptEditor?.addEventListener('contextmenu', preventSpeechLongPressMenu);
        promptEditor?.addEventListener('selectstart', preventSpeechLongPressMenu);
        speechBtn.addEventListener('pointerup', stopPressToTalk);
        speechBtn.addEventListener('pointercancel', stopPressToTalk);
        speechBtn.addEventListener('pointerleave', stopPressToTalk);
        document.addEventListener('pointerup', (event) => {
            if (asrPointerId !== null && event.pointerId === asrPointerId) {
                finishPressToTalk({ sendEnd: true, sendPrompt: true });
            }
        }, true);
        document.addEventListener('pointercancel', (event) => {
            if (asrPointerId !== null && event.pointerId === asrPointerId) {
                finishPressToTalk({ sendEnd: false, sendPrompt: false });
            }
        }, true);
        window.addEventListener('blur', () => {
            if (asrPointerId !== null || isPressToTalkLayout()) {
                finishPressToTalk({ sendEnd: false, sendPrompt: false });
            }
        });
        document.addEventListener('visibilitychange', () => {
            if (document.hidden && (asrPointerId !== null || isPressToTalkLayout())) {
                finishPressToTalk({ sendEnd: false, sendPrompt: false });
            }
        });
        speechBtn.addEventListener('click', (event) => {
            if (ignoreNextSpeechClick) {
                event.preventDefault();
                ignoreNextSpeechClick = false;
                if (ignoreSpeechClickTimeout) {
                    clearTimeout(ignoreSpeechClickTimeout);
                    ignoreSpeechClickTimeout = null;
                }
                return;
            }
            if (isPressToTalkLayout()) {
                event.preventDefault();
                return;
            }
            if (enterMobileVoiceMode(event)) {
                return;
            }
            toggleSpeechByClick();
        });

        promptSendBtn.addEventListener('click', () => {
            if (applyPromptSettings()) {
                flashPromptControl(promptText);
            }
        });

        updatePromptAvailability();
        resizePromptInput();

        refreshModelsBtn.addEventListener('click', fetchModels);

        // Helper function to apply API settings to server
        function applyApiSettings(options = {}) {
            const currentApiBase = apiBaseUrl.value.trim();
            const currentApiKey = apiKey.value.trim();
            const currentModel = modelSelect.value;

            if (!currentApiBase) {
                return; // Silently skip if no API base
            }

            if (!currentModel) {
                return; // Silently skip if no model selected yet
            }

            // Send update to server
            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_model',
                    model: currentModel,
                    api_base: currentApiBase,
                    api_key: currentApiKey
                }));

                if (options.showFeedback) {
                    updateStatus('API settings updated', 'connected');
                }

                // Refresh models from new endpoint if requested
                if (options.refreshModels) {
                    fetchModels();
                }
            }
        }

        // Auto-apply API settings when API Base URL changes
        apiBaseUrl.addEventListener('blur', (e) => {
            checkApiKeyRequirement(e.target.value);
            applyApiSettings({ refreshModels: true, showFeedback: true });

            // Trigger flash animation
            apiBaseUrl.classList.add('applied');
            setTimeout(() => {
                apiBaseUrl.classList.remove('applied');
            }, 600);
        });

        apiBaseUrl.addEventListener('change', (e) => {
            checkApiKeyRequirement(e.target.value);
            applyApiSettings({ refreshModels: true, showFeedback: true });

            // Trigger flash animation
            apiBaseUrl.classList.add('applied');
            setTimeout(() => {
                apiBaseUrl.classList.remove('applied');
            }, 600);
        });

        // Auto-apply API settings when API Key changes (with debounce)
        let apiKeyDebounceTimer;
        apiKey.addEventListener('input', () => {
            clearTimeout(apiKeyDebounceTimer);
            apiKeyDebounceTimer = setTimeout(() => {
                applyApiSettings({ showFeedback: false });
            }, 1000); // Wait 1 second after user stops typing
        });

        // Flash animation when API Key loses focus
        apiKey.addEventListener('blur', () => {
            clearTimeout(apiKeyDebounceTimer);
            applyApiSettings({ showFeedback: false });

            // Trigger flash animation
            apiKey.classList.add('applied');
            setTimeout(() => {
                apiKey.classList.remove('applied');
            }, 600);
        });

        // API Presets Menu
        const apiPresetsBtn = document.getElementById('apiPresetsBtn');
        const apiPresetsMenu = document.getElementById('apiPresetsMenu');

        if (apiPresetsBtn && apiPresetsMenu) {
            apiPresetsBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                apiPresetsMenu.style.display = apiPresetsMenu.style.display === 'none' ? 'block' : 'none';
            });

            // Close menu when clicking outside
            document.addEventListener('click', (e) => {
                if (!apiPresetsMenu.contains(e.target) && e.target !== apiPresetsBtn) {
                    apiPresetsMenu.style.display = 'none';
                }
            });

            // Handle preset selection
            document.querySelectorAll('.api-preset-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    const url = e.currentTarget.getAttribute('data-url');
                    apiBaseUrl.value = url;
                    apiPresetsMenu.style.display = 'none';

                    // Trigger checks
                    checkApiKeyRequirement(url);

                    // Auto-apply new API settings
                    applyApiSettings({ refreshModels: true, showFeedback: true });

                    // Update hint
                    const hint = document.getElementById('apiBaseHint');
                    const serviceName = e.currentTarget.querySelector('strong').textContent;
                    hint.textContent = `Using ${serviceName}`;
                });
            });
        }

        // Mirror video toggle
        mirrorBtn.addEventListener('click', () => {
            videoElement.classList.toggle('mirrored');
            mirrorBtn.classList.toggle('active');
        });

        // Auto-apply processing interval on change
        processEvery.addEventListener('change', () => {
            const interval = parseFloat(processEvery.value) || 1.0;

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_processing',
                    process_interval: interval
                }));
            }

            // Trigger flash animation
            processEvery.classList.add('applied');
            setTimeout(() => {
                processEvery.classList.remove('applied');
            }, 600);
        });

        // Also trigger flash on blur
        processEvery.addEventListener('blur', () => {
            const interval = parseFloat(processEvery.value) || 1.0;

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_processing',
                    process_interval: interval
                }));
            }

            // Trigger flash animation
            processEvery.classList.add('applied');
            setTimeout(() => {
                processEvery.classList.remove('applied');
            }, 600);
        });

        // Auto-apply frames per batch on change
        framesPerBatch.addEventListener('change', () => {
            const value = parseInt(framesPerBatch.value) || 1;

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_frames_per_batch',
                    frames_per_batch: value
                }));
            }

            framesPerBatch.classList.add('applied');
            setTimeout(() => {
                framesPerBatch.classList.remove('applied');
            }, 600);
        });

        framesPerBatch.addEventListener('blur', () => {
            const value = parseInt(framesPerBatch.value) || 1;

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_frames_per_batch',
                    frames_per_batch: value
                }));
            }

            framesPerBatch.classList.add('applied');
            setTimeout(() => {
                framesPerBatch.classList.remove('applied');
            }, 600);
        });

        // Auto-apply max latency on change
        maxLatency.addEventListener('change', () => {
            const latency = parseFloat(maxLatency.value) || 1.0;

            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(JSON.stringify({
                    type: 'update_max_latency',
                    max_latency: latency
                }));
            }
        });

        // Debug payload toggles (Settings modal): send set_debug so server includes request/response payload in vlm_response
        function sendDebugFlags() {
            if (!websocket || websocket.readyState !== WebSocket.OPEN) return;
            const req = document.getElementById('debugShowRequestPayload');
            const res = document.getElementById('debugShowResponsePayload');
            const mem = document.getElementById('debugShowMemoryState');
            websocket.send(JSON.stringify({
                type: 'set_debug',
                show_request_payload: !!req?.checked,
                show_response_payload: !!res?.checked,
                show_memory_state: !!mem?.checked
            }));
        }
        const debugShowRequestPayload = document.getElementById('debugShowRequestPayload');
        const debugShowResponsePayload = document.getElementById('debugShowResponsePayload');
        const debugShowMemoryState = document.getElementById('debugShowMemoryState');
        const requestPayloadDebugEl = document.getElementById('requestPayloadDebug');
        const responsePayloadDebugEl = document.getElementById('responsePayloadDebug');
        const memoryStateDebugEl = document.getElementById('memoryStateDebug');
        if (debugShowRequestPayload) {
            debugShowRequestPayload.addEventListener('change', () => {
                sendDebugFlags();
                if (requestPayloadDebugEl) requestPayloadDebugEl.style.display = debugShowRequestPayload.checked ? 'block' : 'none';
            });
        }
        if (debugShowResponsePayload) {
            debugShowResponsePayload.addEventListener('change', () => {
                sendDebugFlags();
                if (responsePayloadDebugEl) responsePayloadDebugEl.style.display = debugShowResponsePayload.checked ? 'block' : 'none';
            });
        }
        if (debugShowMemoryState) {
            debugShowMemoryState.addEventListener('change', () => {
                sendDebugFlags();
                if (memoryStateDebugEl) memoryStateDebugEl.style.display = debugShowMemoryState.checked ? 'block' : 'none';
            });
        }

        [backgroundEnabledToggle, backgroundFrameMultiplier, backgroundMaxFrames].forEach(control => {
            if (!control) return;
            control.addEventListener('change', () => {
                sendBackgroundConfig();
                control.classList?.add('applied');
                setTimeout(() => control.classList?.remove('applied'), 600);
            });
        });

        // Memory state change detection for console logging
        let _lastMemoryStateHash = '';


        // WebSocket Connection
        function connectWebSocket() {
            if (gatewaySessionBlocked || (websocket && [WebSocket.OPEN, WebSocket.CONNECTING].includes(websocket.readyState))) {
                return;
            }

            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/ws?session_id=${encodeURIComponent(sessionId)}`;

            const ws = new WebSocket(wsUrl);
            websocket = ws;

            ws.onopen = () => {
                if (websocket !== ws) {
                    return;
                }
                console.log('WebSocket connected');
                updateStatus('Connected', 'connected');

                // Send current model/API settings to server after WebSocket connects
                // This ensures auto-selected models are properly initialized on the server side
                // Fix for race condition: page load might auto-select model before WS connects
                const currentModel = modelSelect.value;
                if (currentModel) {
                    console.log('Initializing server with current model:', currentModel);
                    applyApiSettings({ showFeedback: false });
                }
            };

            ws.onmessage = (event) => {
                if (websocket !== ws) {
                    return;
                }
                const data = JSON.parse(event.data);
                if (data.type === 'service_busy') {
                    gatewaySessionBlocked = true;
                    stopVoiceMode();
                    stopTtsPlayback();
                    updateStatus('ALIVE is busy. Please retry.', 'disconnected');
                    return;
                }

                if (data.type === 'vlm_response') {
                    if (!isAnalysisRunning) {
                        return;
                    }

                    if (data.text !== lastText) {
                        resultText.classList.remove('fade');

                        if (fadeTimeout) {
                            clearTimeout(fadeTimeout);
                        }

                        // Start fade after 2 seconds if enabled
                        if (settings.fade) {
                            fadeTimeout = setTimeout(() => {
                                resultText.classList.add('fade');
                            }, 2000);
                        }
                    }

                    updateResultText(data.text, data.metrics, data.metrics?.background_handoff || null);
                    lastText = data.text;

                    // Update video overlay (always, visibility is controlled by CSS)
                    const displayText = getVlmDisplayText(data.text);
                    videoOverlay.textContent = displayText;
                    videoOverlay.classList.remove('show', 'top', 'bottom');
                    if (displayText && settings.overlayPosition !== 'none') {
                        videoOverlay.classList.add('show', settings.overlayPosition);
                    }

                    if (data.metrics) {
                        metricsInline.style.display = 'flex';
                        latencyValue.textContent = Math.round(data.metrics.last_latency_ms);
                        avgLatencyValue.textContent = Math.round(data.metrics.avg_latency_ms);
                        countValue.textContent = data.metrics.total_inferences;
                        if (
                            revealVideoAfterMetricsToken === streamStartToken &&
                            Number(data.metrics.total_inferences) > 0
                        ) {
                            revealVideoWhenReady(streamStartToken);
                        }
                        logLatencyBreakdown(data.metrics);
                    }
                    if (data.summarizer_timing) {
                        const st = data.summarizer_timing;
                        const stKey = JSON.stringify(st);
                        if (stKey !== window._lastSummarizerKey) {
                            window._lastSummarizerKey = stKey;
                            let parts = [];
                            if (st.last_mid_term_ms != null) parts.push(`mid-term=${st.last_mid_term_ms}ms (chunk#${st.last_mid_term_chunk})`);
                            if (st.barrier_wait_ms != null) parts.push(`barrier_wait=${st.barrier_wait_ms}ms`);
                            if (st.last_long_term_ms != null) parts.push(`long-term=${st.last_long_term_ms}ms`);
                            if (parts.length) console.log(`[summary model] ${parts.join(', ')}`);
                        }
                    }
                    if (data.request_payload) {
                        const block = document.getElementById('requestPayloadDebug');
                        const pre = document.getElementById('requestPayloadContent');
                        if (block && pre && document.getElementById('debugShowRequestPayload')?.checked) {
                            block.style.display = 'block';
                            pre.textContent = formatDebugPayload(data.request_payload);
                        }
                    }
                    if (data.response_payload) {
                        const block = document.getElementById('responsePayloadDebug');
                        const pre = document.getElementById('responsePayloadContent');
                        if (block && pre && document.getElementById('debugShowResponsePayload')?.checked) {
                            block.style.display = 'block';
                            pre.textContent = formatDebugPayload(data.response_payload);
                        }
                    }
                    if (data.memory_state) {
                        const summaries = data.memory_state.mid_term_summaries || [];
                        const longTerm = data.memory_state.long_term_memory || '';
                        const memHash = JSON.stringify(data.memory_state);
                        if (memHash !== _lastMemoryStateHash) {
                            _lastMemoryStateHash = memHash;
                            // UI display (controlled by toggle)
                            const memBlock = document.getElementById('memoryStateDebug');
                            if (memBlock && document.getElementById('debugShowMemoryState')?.checked) {
                                memBlock.style.display = 'block';
                                const midPre = document.getElementById('midTermMemoryContent');
                                if (midPre) {
                                    midPre.textContent = summaries.length
                                        ? summaries.map(s => `[Chunk ${s.chunk_index} | ${s.frame_range}]\n${s.summary_text}`).join('\n\n')
                                        : '(empty)';
                                }
                                const ltPre = document.getElementById('longTermMemoryContent');
                                if (ltPre) {
                                    ltPre.textContent = longTerm || '(empty)';
                                }
                            }
                            // Console output
                            console.group('%c[Memory State]', 'color: #4fc3f7; font-weight: bold;');
                            if (summaries.length) {
                                console.groupCollapsed(`Mid-term memory (${summaries.length} chunks)`);
                                summaries.forEach(s => {
                                    console.log(`%c[Chunk ${s.chunk_index} | ${s.frame_range}]`, 'color: #81c784;', '\n' + s.summary_text);
                                });
                                console.groupEnd();
                            } else {
                                console.log('Mid-term memory: (empty)');
                            }
                            if (longTerm) {
                                console.groupCollapsed('Long-term memory');
                                console.log(longTerm);
                                console.groupEnd();
                            } else {
                                console.log('Long-term memory: (empty)');
                            }
                            console.groupEnd();
                        }
                    }
                } else if (data.type === 'status') {
                    // Don't show status messages in result balloon (too flashy)
                    // Status is already shown in the header
                } else if (
                    data.type === 'background_task_started' ||
                    data.type === 'background_result_ready' ||
                    data.type === 'background_result_error'
                ) {
                    appendOrUpdateBackgroundEntry(data);
                } else if (data.type === 'server_config') {
                    // Server sent its current configuration (model, api_base, prompt)
                    if (data.model) {
                        document.getElementById('modelName').textContent = displayModelName(data.model);
                        // Also update the model select if it matches
                        if (modelSelect.querySelector(`option[value="${data.model}"]`)) {
                            modelSelect.value = data.model;
                        }
                    }
                    if (data.api_base) {
                        apiBaseUrl.value = data.api_base;
                        checkApiKeyRequirement(apiBaseUrl.value);
                        serverConfigApplied = true;
                        fetchModels();
                    }
                    if (data.process_interval != null && !isNaN(data.process_interval)) {
                        processEvery.value = String(data.process_interval);
                    }
                    if (data.frames_per_batch != null && !isNaN(data.frames_per_batch)) {
                        framesPerBatch.value = String(data.frames_per_batch);
                    }
                    if (data.background_model) {
                        applyBackgroundConfig(data.background_model);
                    }
                    const reqCb = document.getElementById('debugShowRequestPayload');
                    const resCb = document.getElementById('debugShowResponsePayload');
                    const memCb = document.getElementById('debugShowMemoryState');
                    if ((reqCb?.checked || resCb?.checked || memCb?.checked) && websocket && websocket.readyState === WebSocket.OPEN) {
                        websocket.send(JSON.stringify({
                            type: 'set_debug',
                            show_request_payload: !!reqCb?.checked,
                            show_response_payload: !!resCb?.checked,
                            show_memory_state: !!memCb?.checked
                        }));
                    }
                } else if (data.type === 'model_updated') {
                    // Model was updated on server
                    if (data.model) {
                        document.getElementById('modelName').textContent = displayModelName(data.model);
                        console.log('Model updated to:', data.model);
                    }
                } else if (data.type === 'prompt_updated') {
                    // Prompt was updated on server (already handled in applyPrompt)
                    console.log('Prompt updated:', data.prompt);
                } else if (data.type === 'processing_updated') {
                    if (data.process_interval != null) processEvery.value = String(data.process_interval);
                    console.log('Processing interval updated:', data.process_interval, 's');
                } else if (data.type === 'frames_per_batch_updated') {
                    if (data.frames_per_batch != null) framesPerBatch.value = String(data.frames_per_batch);
                    if (data.background_model) applyBackgroundConfig(data.background_model);
                    console.log('Frames per batch updated:', data.frames_per_batch);
                } else if (data.type === 'background_config_updated') {
                    applyBackgroundConfig(data.background_model);
                    console.log('Background model config updated:', data.background_model);
                }
            };

            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
            };

            ws.onclose = () => {
                if (websocket !== ws) {
                    return;
                }
                if (gatewaySessionBlocked) return;
                console.log('WebSocket disconnected, will reconnect...');
                websocket = null;
                stopVoiceMode('Connection interrupted. Click to resume when connected.');
                updateStatus('Reconnecting...', 'disconnected');
                setTimeout(connectWebSocket, 2000);
            };
        }

        window.addEventListener('pagehide', () => {
            stopVoiceMode();
            stopTtsPlayback();
            if (cameraWebsocket) cameraWebsocket.close();
            if (websocket) websocket.close();
            navigator.sendBeacon('/api/session/cleanup', new Blob([
                JSON.stringify({session_id: sessionId, reset_adapter: true})
            ], {type: 'application/json'}));
        });

        async function cleanupServerSession(sessionIdToCleanup) {
            if (!sessionIdToCleanup) {
                return;
            }

            try {
                const response = await fetch('/api/session/cleanup', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_id: sessionIdToCleanup,
                        reset_adapter: true
                    })
                });
                if (!response.ok) {
                    console.warn('Session cleanup failed:', response.status);
                } else {
                    const result = await response.json();
                }
            } catch (error) {
                console.warn('Session cleanup request failed:', error);
            }
        }

        async function resetSession({ clearConversation = false, cleanupServer = true } = {}) {
            const oldSessionId = sessionId;

            if (!cleanupServer && websocket && websocket.readyState === WebSocket.OPEN) {
                try {
                    websocket.send(JSON.stringify({ type: 'reset_session' }));
                } catch (e) {
                    console.warn('Failed to send reset_session:', e);
                }
            }

            sessionId = crypto.randomUUID ? crypto.randomUUID() : 'tab-' + Date.now() + '-' + Math.random().toString(36).slice(2);
            console.log('Session reset:', oldSessionId, '->', sessionId);

            // Release the previous page slot before replacing its control WS.
            // A gateway without admission support may return 404; local close
            // below retains compatibility with that deployment.
            const previousControl = websocket;
            websocket = null;
            try {
                await fetch('/_bridge/release', {method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({session_id: oldSessionId})});
            } catch (error) { console.warn('Session release unavailable', error); }
            // Reconnect WebSocket with new session_id
            if (previousControl) {
                const oldSocket = previousControl;
                // Allow the gateway to release the old experience slot before
                // opening its replacement, including when both slots are full.
                await new Promise(resolve => {
                    if (oldSocket.readyState === WebSocket.CLOSED) { resolve(); return; }
                    const timer = setTimeout(resolve, 2000);
                    oldSocket.addEventListener('close', () => { clearTimeout(timer); resolve(); }, {once: true});
                    oldSocket.close();
                });
            }
            connectWebSocket();

            // Clear prompt input
            promptText.value = '';
            currentPromptText = '';

            if (clearConversation) {
                clearVlmConversation();
            } else {
                // Reset current streaming state, keep the visible history in the page
                resultText.classList.remove('fade');
                videoOverlay.textContent = '';
                lastText = '';
                lastTtsEventKey = '';
                lastHistoryKey = null;
                lastLoggedInferenceCount = 0;
                renderVlmHistory();
            }

            if (cleanupServer) {
                await cleanupServerSession(oldSessionId);
            }
        }

        // Start - dispatch to webcam or RTSP based on active tab
        async function start() {
            streamStartToken += 1;
            const token = streamStartToken;
            isAnalysisRunning = false;
            revealVideoAfterMetricsToken = null;
            cancelRevealVideoFallback();
            updatePromptAvailability();
            metricsInline.style.display = 'flex';
            latencyValue.textContent = '--';
            avgLatencyValue.textContent = '--';
            countValue.textContent = '--';
            setVideoWaitingForStream(true);
            videoElement.srcObject = null;
            if (settings.ttsEnabled) {
                try {
                    ensureTtsAudioContext();
                } catch (error) {
                    console.warn('Unable to initialize TTS audio context:', error);
                }
            }

            // Animate big button
            const bigBtn = document.getElementById('bigStartBtn');
            bigBtn.classList.add('animating');
            setTimeout(() => {
                bigBtn.classList.remove('animating');
                bigBtn.classList.add('streaming');
            }, 500);

            // Show small stop button
            document.getElementById('smallStopBtn').classList.add('show');

            const activeTab = document.querySelector('.input-source-tab.active');
            const inputSource = activeTab ? activeTab.getAttribute('data-source') : 'webcam';

            if (inputSource === 'webcam') {
                revealVideoAfterMetricsToken = token;
                await startWebcam(token);
            } else if (inputSource === 'rtsp') {
                await startRTSP(token);
            }

        }

        // Start WebRTC (Webcam mode)
        async function startWebcam(token) {
            if (window.__ALIVE_CAMERA_TRANSPORT__ === 'websocket') {
                return startWebcamUpload(token);
            }
            try {
                if (!websocket || websocket.readyState !== WebSocket.OPEN) {
                    connectWebSocket();
                }

                updateStatus('Requesting camera...', 'processing');

                // Use selected camera or default
                const videoConstraints = {
                    width: { ideal: 1280 },
                    height: { ideal: 720 }
                };

                if (selectedCameraId) {
                    videoConstraints.deviceId = { exact: selectedCameraId };
                }

                localStream = await navigator.mediaDevices.getUserMedia({
                    video: videoConstraints,
                    audio: false
                });

                updateStatus('Connecting...', 'processing');
                showProcessedVideoStream(localStream, token);

                peerConnection = new RTCPeerConnection({
                    iceServers: window.__ALIVE_ICE_SERVERS__ || [{ urls: 'stun:stun.l.google.com:19302' }]
                });

                localStream.getTracks().forEach(track => {
                    peerConnection.addTrack(track, localStream);
                });

                peerConnection.ontrack = (event) => {
                    console.log('Received remote track');
                };

                peerConnection.oniceconnectionstatechange = () => {
                    console.log('ICE connection state:', peerConnection.iceConnectionState);
                    switch (peerConnection.iceConnectionState) {
                        case 'connected':
                            if (isAnalysisRunning) {
                                updateStatus('Streaming', 'connected');
                            }
                            break;
                        case 'disconnected':
                        case 'failed':
                        case 'closed':
                            updateStatus('Disconnected', 'disconnected');
                            stop();
                            break;
                    }
                };

                const offer = await peerConnection.createOffer();
                await peerConnection.setLocalDescription(offer);

                const response = await fetch('/offer', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        sdp: peerConnection.localDescription.sdp,
                        type: peerConnection.localDescription.type,
                        session_id: sessionId,
                    }),
                });

                const answer = await response.json();
                await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));

            } catch (error) {
                console.error('Error starting webcam:', error);
                updateStatus(`Error: ${error.message}`, 'disconnected');
                setVideoWaitingForStream(false);
                stop();
            }
        }

        // Browser-camera transport for deployments where WebRTC UDP cannot reach
        // the compute node (for example, an HTTPS reverse tunnel). Frames travel
        // as bounded JPEGs over the authenticated WebSocket; the local stream is
        // still shown immediately as the preview.
        async function startWebcamUpload(token) {
            try {
                if (!websocket || websocket.readyState !== WebSocket.OPEN) {
                    connectWebSocket();
                    await new Promise((resolve, reject) => {
                        const deadline = Date.now() + 10000;
                        const poll = () => {
                            if (websocket && websocket.readyState === WebSocket.OPEN) return resolve();
                            if (Date.now() > deadline) return reject(new Error('Control connection timed out'));
                            setTimeout(poll, 100);
                        };
                        poll();
                    });
                }
                updateStatus('Requesting camera...', 'processing');
                const videoConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } };
                if (selectedCameraId) videoConstraints.deviceId = { exact: selectedCameraId };
                localStream = await navigator.mediaDevices.getUserMedia({ video: videoConstraints, audio: false });
                showProcessedVideoStream(localStream, token);

                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const url = `${protocol}//${window.location.host}/ws/camera?session_id=${encodeURIComponent(sessionId)}`;
                cameraWebsocket = new WebSocket(url);
                cameraWebsocket.binaryType = 'arraybuffer';
                const ws = cameraWebsocket;
                ws.onopen = () => {
                    if (cameraWebsocket !== ws) return;
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d', { alpha: false });
                    const sendFrame = () => {
                        if (cameraWebsocket !== ws || ws.readyState !== WebSocket.OPEN || !videoElement.videoWidth) return;
                        const maxShortEdge = 480;
                        const scale = Math.min(1, maxShortEdge / Math.min(videoElement.videoWidth, videoElement.videoHeight));
                        canvas.width = Math.max(1, Math.round(videoElement.videoWidth * scale));
                        canvas.height = Math.max(1, Math.round(videoElement.videoHeight * scale));
                        context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
                        canvas.toBlob(blob => {
                            if (blob && ws.readyState === WebSocket.OPEN) ws.send(blob);
                        }, 'image/jpeg', 0.72);
                    };
                    const intervalMs = Math.max(500, Number(processEvery?.value || 1) * 1000);
                    cameraCaptureTimer = setInterval(sendFrame, intervalMs);
                    sendFrame();
                    updateStatus('Streaming', 'connected');
                };
                ws.onmessage = event => {
                    try {
                        const data = JSON.parse(event.data);
                        if (data.type === 'frame_error') console.warn('Camera frame:', data.message);
                    } catch (_) {}
                };
                ws.onerror = () => updateStatus('Camera connection error', 'disconnected');
                ws.onclose = () => {
                    if (cameraWebsocket === ws && isAnalysisRunning) {
                        stopVoiceMode('Camera connection closed. Restart the video to continue.');
                        updateStatus('Disconnected', 'disconnected');
                    }
                };
            } catch (error) {
                console.error('Error starting webcam upload:', error);
                updateStatus(`Error: ${error.message}`, 'disconnected');
                setVideoWaitingForStream(false);
                stop();
            }
        }

        // Start RTSP mode
        async function startRTSP(token) {
            try {
                if (!websocket || websocket.readyState !== WebSocket.OPEN) {
                    connectWebSocket();
                }

                const rtspUrl = document.getElementById('rtspUrl').value.trim();

                if (!rtspUrl) {
                    alert('Please enter an RTSP URL');
                    setVideoWaitingForStream(false);
                    resetVideoButtons();
                    return;
                }

                updateStatus('Connecting to RTSP stream...', 'processing');

                // Create WebRTC peer connection (no local stream needed for RTSP)
                peerConnection = new RTCPeerConnection({
                    iceServers: window.__ALIVE_ICE_SERVERS__ || [{ urls: 'stun:stun.l.google.com:19302' }]
                });

                // Receive processed video from server
                peerConnection.ontrack = (event) => {
                    console.log('Received RTSP stream from server');
                    if (event.track.kind === 'video') {
                        showProcessedVideoStream(event.streams[0], token);
                    }
                };

                peerConnection.oniceconnectionstatechange = () => {
                    console.log('ICE connection state:', peerConnection.iceConnectionState);
                    switch (peerConnection.iceConnectionState) {
                        case 'connected':
                            if (isAnalysisRunning) {
                                updateStatus('Streaming', 'connected');
                            }
                            break;
                        case 'disconnected':
                        case 'failed':
                        case 'closed':
                            updateStatus('Disconnected', 'disconnected');
                            stop();
                            break;
                    }
                };

                // Create offer (recvonly - we're only receiving video from server)
                peerConnection.addTransceiver('video', { direction: 'recvonly' });
                const offer = await peerConnection.createOffer();
                await peerConnection.setLocalDescription(offer);

                // Wait for ICE gathering to complete before sending offer (with timeout)
                // This ensures all ICE candidates are embedded in the SDP
                console.log('Waiting for ICE gathering to complete...');
                await new Promise((resolve) => {
                    if (peerConnection.iceGatheringState === 'complete') {
                        resolve();
                    } else {
                        const checkState = () => {
                            if (peerConnection.iceGatheringState === 'complete') {
                                peerConnection.removeEventListener('icegatheringstatechange', checkState);
                                resolve();
                            }
                        };
                        peerConnection.addEventListener('icegatheringstatechange', checkState);

                        // Timeout after 5 seconds - proceed anyway to avoid hanging
                        setTimeout(() => {
                            peerConnection.removeEventListener('icegatheringstatechange', checkState);
                            console.warn('ICE gathering timeout - proceeding anyway');
                            resolve();
                        }, 5000);
                    }
                });
                console.log('ICE gathering state:', peerConnection.iceGatheringState, '- sending offer');

                // Send offer with RTSP URL and session to server
                const response = await fetch('/offer', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        sdp: peerConnection.localDescription.sdp,
                        type: peerConnection.localDescription.type,
                        rtsp_url: rtspUrl,
                        session_id: sessionId,
                    })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || 'Failed to connect to RTSP stream');
                }

                const answer = await response.json();
                await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));

                // Disable RTSP URL field and Test button while streaming
                rtspUrlInput.disabled = true;
                document.getElementById('testRtspBtn').disabled = true;

            } catch (error) {
                console.error('Error starting RTSP:', error);
                updateStatus(`Error: ${error.message}`, 'disconnected');
                alert('Failed to connect to RTSP stream: ' + error.message);
                setVideoWaitingForStream(false);
                resetVideoButtons();
                if (peerConnection) {
                    peerConnection.close();
                    peerConnection = null;
                }
            }
        }

        // Stop (handles both webcam and RTSP)
        async function stop({ clearConversation = false } = {}) {
            stopVoiceMode();
            streamStartToken += 1;
            isAnalysisRunning = false;
            revealVideoAfterMetricsToken = null;
            cancelRevealVideoFallback();
            mobileVoiceMode = false;
            closeTtsWebSocket();
            restorePromptEditorHome();
            updatePromptAvailability();
            if (asrRecording || asrStream || asrAudioContext) {
                await stopSpeech({ sendEnd: false, sendPrompt: false });
            }

            // Reset overlay buttons
            resetVideoButtons();

            if (fadeTimeout) {
                clearTimeout(fadeTimeout);
                fadeTimeout = null;
            }

            // Stop webcam (if in webcam mode)
            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
                localStream = null;
            }

            if (cameraCaptureTimer) {
                clearInterval(cameraCaptureTimer);
                cameraCaptureTimer = null;
            }
            if (cameraWebsocket) {
                cameraWebsocket.close();
                cameraWebsocket = null;
            }

            // Close WebRTC peer connection (used by both webcam and RTSP)
            if (peerConnection) {
                peerConnection.close();
                peerConnection = null;
            }

            videoElement.srcObject = null;
            setVideoWaitingForStream(false);

            // Reset session after local tracks are stopped so the backend can cancel
            // any in-flight VLM call and remove old session state.
            await resetSession({ clearConversation, cleanupServer: true });

            updateStatus('Connected', 'connected');

            // Re-enable RTSP URL field and Test button
            const rtspUrlInput = document.getElementById('rtspUrl');
            if (rtspUrlInput) {
                rtspUrlInput.disabled = false;
            }
            const testRtspBtn = document.getElementById('testRtspBtn');
            if (testRtspBtn) {
                testRtspBtn.disabled = false;
            }
        }

        // Sidebar start/stop buttons removed - using overlay buttons instead
        // startBtn.addEventListener('click', start);
        // stopBtn.addEventListener('click', stop);

        // Load on page load
        window.addEventListener('load', async () => {
            connectWebSocket();

            // Fallback for older servers that do not send server_config.
            setTimeout(() => {
                if (!serverConfigApplied) {
                    checkApiKeyRequirement(apiBaseUrl.value);
                    fetchModels();
                }
            }, 1000);

            // Initialize prompt display
            const initialPrompt = promptText.value.trim();
            if (initialPrompt) {
                currentPromptText = initialPrompt;
            }

            // Initialize Lucide icons
            lucide.createIcons();
        });
    </script>


    <script>
    (() => {
        const history = document.getElementById('resultTextContent');
        const refreshEmpty = () => {
            if (!history.textContent.trim() && !history.querySelector('.alive-empty')) {
                const note=document.createElement('div'); note.className='alive-empty';
                note.textContent='Open your camera, then ask a question — or tell ALIVE what to watch for.';
                history.appendChild(note);
            } else if (history.querySelector('.alive-empty') && history.children.length > 1) {
                history.querySelector('.alive-empty').remove();
            }
        };
        new MutationObserver(refreshEmpty).observe(history,{childList:true}); refreshEmpty();
    })();
    </script>
<script>
(() => {
    'use strict';
    const translations = {
        'Connected': '已连接', 'Disconnected': '未连接', 'Connecting...': '正在连接…',
        'Reconnecting...': '正在重连…', 'Streaming': '运行中', 'Ready': '就绪',
        'Light': '浅色', 'Dark': '深色', 'Auto': '自动', 'Settings': '设置',
        'Interface language': '界面语言', 'Voice': '语音', 'TTS voice': '音色',
        'Voice for spoken replies': '模型语音回复的音色',
        'Loading voices…': '正在加载音色…', 'Voices unavailable': '音色暂不可用',
        'Layout': '布局', 'Main Content Order': '主区域顺序',
        'Choose which element appears at the top': '选择上下排列时首先显示的内容',
        'Camera → Conversation': '摄像头 → 对话', 'Conversation → Camera': '对话 → 摄像头',
        'Responses on Camera View': '在画面上显示回复',
        'Show text overlay directly on video feed': '将回复文字叠加到摄像头画面上',
        'None': '不显示', 'At the top': '顶部', 'At the bottom': '底部',
        'Visual Effects': '视觉效果', 'Pop-in Animation': '弹出动画',
        'Scale animation when new VLM response arrives': '新回复出现时播放缩放动画',
        'Green Glow Effect': '高亮光晕', 'Border glow on new VLM response': '新回复出现时高亮边框',
        'Fade Effect': '淡出效果', 'Gradually fade response after 2 seconds': '回复出现 2 秒后逐渐淡出',
        'Visual Style': '视觉风格', 'Colorful UI Accents': '彩色界面点缀',
        'Color-coded icons and input focus glows': '使用彩色图标和输入框聚焦光晕',
        'Max Video Latency (seconds)': '最大视频延迟(秒)',
        'Drop old frames if delay exceeds this (0 = no intervention)': '超过该延迟时丢弃旧帧(0 表示不干预)',
        'Use Auto / 中 / 英 below the message box to switch both speech input and output. Auto detects your speech language and reads replies in their original language.': '使用输入框下方的“自动 / 中 / 英”切换语音输入和输出语言。自动模式会识别说话语言,并按回复原文语言朗读。',
        'Full duplex (experimental)': '全双工(实验功能)',
        'Keep listening while replies play; speak to interrupt. Off on every page load. Turn on Mic and Sound below. Headphones recommended; if speaker echo triggers interruptions, turn this off.': '播放回复时继续聆听,开口即可打断。每次打开页面默认关闭,请先开启下方的麦克风和声音。建议使用耳机;如果扬声器回声导致误打断,请关闭此功能。',
        'Checking voice service…': '正在检查语音服务…',
        'English and Chinese voice ready': '中英文语音服务已就绪',
        'Microphone unavailable; sound and text input are ready': '麦克风暂不可用;可播放声音和输入文字',
        'Microphone ready; sound is unavailable': '麦克风已就绪;声音暂不可用',
        'Voice unavailable; use text input': '语音暂不可用,请输入文字',
        'Speak replies': '朗读回复',
        'Off by default. Read replies in English or Chinese when enabled': '默认关闭,开启后朗读中文或英文回复',
        'Background Model': '后台模型', 'Enable delegation solver': '启用后台任务处理',
        'Use ALIVE for delegated questions, visual reasoning, and chart tasks in the background': '使用 ALIVE 在后台处理委托问题、视觉推理和图表任务',
        'Frame multiplier': '帧数倍率',
        'Background frames per second relative to foreground streaming FPS': '后台每秒帧数相对于前台流式帧率的倍数',
        'Max background frames': '后台最大帧数',
        'Recent background frame cache cap; default and maximum are 100': '后台最近帧的缓存上限;默认值和最大值均为 100',
        'Debug': '调试', 'Show request payload': '显示请求内容',
        'Include request JSON (image + prompt) under the prompt area; collapsed by default': '在输入区域下显示请求 JSON(图像和提示词),默认折叠',
        'Show response payload': '显示响应内容',
        'Include API response JSON under the VLM output; collapsed by default': '在模型输出下显示接口响应 JSON,默认折叠',
        'Show memory state': '显示记忆状态',
        'Display mid-term and long-term memory content below VLM output': '在模型输出下显示中期和长期记忆内容',
        'VLM API Configuration': '视觉模型接口配置', 'API Base URL': '接口基础地址',
        'Current VLM endpoint': '当前视觉模型接口', 'API Key (Optional)': 'API 密钥(可选)',
        'Leave empty for local deployment.': 'OpenAI、NVIDIA API Catalog 等服务需要密钥',
        'Model Selection': '模型选择', 'Video Source': '视频来源', 'Webcam': '摄像头',
        'RTSP Stream': 'RTSP 视频流', 'BETA': '测试版', 'Camera Selection': '选择摄像头',
        'No cameras found': '未找到摄像头', 'Error detecting cameras': '检测摄像头失败',
        'Select camera device to use for VLM analysis': '选择供视觉模型分析的摄像头设备',
        'RTSP Stream URL': 'RTSP 视频流地址', 'Format:': '格式:', 'Examples:': '示例:',
        'Beta:': '测试版:', 'Tested with Reolink RLC-811A. Other cameras may work.': '已测试 Reolink RLC-811A,其他摄像头也可能适用。',
        'Learn more': '了解更多', 'Processing Interval': '推理间隔',
        'Seconds between each VLM inference (default: 1s)': '每次视觉模型推理的间隔秒数(默认 1 秒)',
        'Frames per Batch': '每批帧数', 'Number of frames batched per inference (default: 1)': '每次推理输入的帧数(默认 1 帧)',
        'Speaking:': '正在朗读:', 'Model:': '模型:', 'ms': '毫秒', 'Avg:': '平均:', 'Count:': '次数:',
        'Request payload (debug)': '请求内容(调试)', 'Response payload (debug)': '响应内容(调试)',
        'Mid-term memory': '中期记忆', 'Long-term memory': '长期记忆',
        'Plain Text': '纯文本',
        'Open your camera, then ask a question — or tell ALIVE what to watch for.': '打开摄像头后即可提问,或告诉 ALIVE 需要留意什么。',
        'A conversation starts with a shared view. Open your camera, then ask ALIVE a question — or tell it what to watch for.': '从分享画面开始对话。打开摄像头后向 ALIVE 提问,或告诉它需要留意什么。',
        'Describe the current scene in one sentence': '用一句话描述当前画面',
        'Describe the scene': '描述画面', 'Identify the object I am holding': '识别我手中的物品',
        'Identify an object': '识别物品', 'Tell me the color of my clothing': '告诉我衣服的颜色',
        'Clothing color': '衣服颜色', 'Describe what I am doing': '描述我正在做什么',
        'Describe my action': '描述动作', 'Quick prompts': '快捷提示',
        'YOUR VIEW': '你的画面', 'A shared view, a new perspective.': '共享视野,发现新角度。',
        'Start your camera to begin.': '打开摄像头即可开始。', 'Open camera': '打开摄像头',
        'Start': '开始', 'Stop': '停止', 'Stop camera': '关闭摄像头', 'Stop video': '停止视频',
        'Starting...': '正在启动…', 'Starting…': '正在启动…', 'Stopping...': '正在停止…',
        'Front': '前置', 'Rear': '后置', 'Responses': '回复', 'Mirror': '镜像',
        'Refresh page': '刷新页面', 'Select preset API endpoint': '选择预设接口',
        'Refresh available models': '刷新模型列表',
        'RTSP IP Camera (Beta - Tested with Reolink RLC-811A)': 'RTSP 网络摄像头(测试版,已测试 Reolink RLC-811A)',
        'Test Connection': '测试连接',
        'Model processing time; excludes ASR, TTS, and public network delay': '模型处理耗时,不包括语音识别、语音合成和公网延迟',
        'Toggle Markdown Rendering': '切换 Markdown 渲染', 'Copy to clipboard': '复制到剪贴板',
        'Ask about what you see…': '问问你看到的内容…',
        'Open your camera to start a conversation': '打开摄像头开始对话',
        'Start the video to speak': '先打开视频再说话', 'Start the video to send': '先打开视频再发送',
        'Send prompt': '发送消息', 'Voice controls': '语音控制',
        'Mic off': '麦克风关', 'Mic on': '麦克风开', 'Sound off': '声音关', 'Sound on': '声音开',
        'Turn microphone on': '开启麦克风', 'Turn microphone off': '关闭麦克风',
        'Turn spoken replies on': '开启回复朗读', 'Turn spoken replies off': '关闭回复朗读',
        'Speech input and output language': '语音输入和输出语言',
        'Detect speech and reply language': '自动识别语音和回复语言',
        'Chinese speech input and output': '中文语音输入和输出',
        'English speech input and output': '英文语音输入和输出',
        'Toggle fullscreen': '切换全屏', 'Switch front/rear camera': '切换前后摄像头', 'Mirror video': '镜像画面',
        'Microphone and sound are off': '麦克风和声音均已关闭',
        'Microphone off · Spoken replies on': '麦克风已关闭 · 回复朗读已开启',
        'Microphone access requires HTTPS or localhost.': '麦克风需要通过 HTTPS 或 localhost 访问。',
        'Microphone access is unavailable in this browser.': '此浏览器无法访问麦克风。',
        'Allow microphone access in your browser and try again.': '请在浏览器中允许麦克风访问,然后重试。',
        'No microphone found.': '未找到麦克风。',
        'Microphone is off; replies will be spoken': '麦克风已关闭;回复将自动朗读',
        'Microphone off': '麦克风已关闭', 'Sound could not start. Please retry.': '声音启动失败,请重试。',
        'Speech output is unavailable': '语音输出暂不可用', 'Speech input is unavailable': '语音输入暂不可用',
        'Starting camera…': '正在打开摄像头…',
        'Speaking + listening — speak to interrupt': '正在朗读并聆听,开口可打断',
        'Speaking — connecting microphone…': '正在朗读,连接麦克风中…',
        'Speaking — microphone paused': '正在朗读,麦克风已暂停',
        'Listening — pause to send': '正在聆听,停顿后发送',
        'Listening — waiting for reply…': '正在聆听,等待回复中…',
        'Listening — full duplex': '正在聆听,全双工模式', 'Waiting for a reply…': '正在等待回复…',
        'Sending…': '正在发送…', 'Connecting microphone…': '正在连接麦克风…',
        'Release to send': '松开发送', 'Stop speaking': '结束说话', 'Hold to speak': '按住说话',
        'Speak': '说话', 'Speak EN': '说英文', 'Speak ZH': '说中文',
        'Stop the video before changing this setting': '请先停止视频再修改此设置',
        'Voice service unavailable. Click to retry.': '语音服务暂不可用,点击重试。',
        'Speech connection failed. Please retry.': '语音连接失败,请重试。',
        'Speech connection interrupted. Please retry.': '语音连接中断,请重试。',
        'Speech playback failed. Continuing with the next reply.': '语音播放失败,将继续下一条回复。',
        'Preparing first metrics...': '正在准备首次统计…', 'Model configured': '模型已配置',
        'Start the video and wait for the connection before sending.': '请启动视频并等待连接后再发送。',
        'Message not sent. Please retry.': '消息未发送,请重试。',
        'Reply delayed. You can keep speaking.': '回复有延迟,你可以继续说话。',
        'No reply yet. You can retry with voice or text.': '暂未收到回复,可使用语音或文字重试。',
        'Camera did not start. Check permissions and retry.': '摄像头未启动,请检查权限并重试。',
        'Microphone could not start. Check permissions and retry.': '麦克风未启动,请检查权限并重试。',
        'Microphone paused. Click to resume.': '麦克风已暂停,点击恢复。',
        'Speech recognition unavailable. Click to retry.': '语音识别暂不可用,点击重试。',
        'Microphone connection closed. Click to retry.': '麦克风连接已关闭,点击重试。',
        'Speech recognition connection failed. Please retry.': '语音识别连接失败,请重试。',
        'Microphone connection failed. Click to retry.': '麦克风连接失败,点击重试。',
        'Voice unavailable. Please use text input.': '语音暂不可用,请输入文字。',
        'Start the video first': '请先启动视频',
        'Message not sent. Your text is kept for retry.': '消息未发送,文字已保留,可重试。',
        'API settings updated': '接口设置已更新',
        'Connection interrupted. Click to resume when connected.': '连接中断,重新连接后点击恢复。',
        'Requesting camera...': '正在请求摄像头权限…', 'Camera connection error': '摄像头连接错误',
        'Camera connection closed. Restart the video to continue.': '摄像头连接已关闭,请重启视频。',
        'Connecting to RTSP stream...': '正在连接 RTSP 视频流…',
        'Summary': '摘要', 'Related question': '相关问题', 'Jump': '跳转',
        'Background model failed': '后台模型处理失败',
        'Background result is ready. View it now?': '后台结果已就绪,要现在查看吗?',
        'Background model is working...': '后台模型正在处理…',
        'Jump to the background result': '跳转到后台结果', 'Jump to the original question': '跳转到原始问题',
        'Collapse': '收起', 'View': '查看', 'Waiting': '等待中', 'Copy': '复制', 'Copied': '已复制',
        'Preview': '预览', 'Raw': '原文', 'Close': '关闭',
        'Background model failed.': '后台模型处理失败。',
        'Loading models...': '正在加载模型…', 'No models available': '暂无可用模型', 'Error loading models': '加载模型失败',
        '⚠️ Please enter an RTSP URL': '⚠️ 请输入 RTSP 地址', '🔄 Testing connection...': '🔄 正在测试连接…'
    };
    const languageKey = 'alive-demo:uiLanguage';
    const voiceKey = 'alive-demo:ttsVoice';
    const read = key => { try { return localStorage.getItem(key); } catch { return null; } };
    const save = (key, value) => { try { localStorage.setItem(key, value); } catch {} };
    let language = read(languageKey) === 'zh' ? 'zh' : 'en';
    let voice = read(voiceKey) || 'serena';
    const original = new WeakMap();
    const originalAttributes = new WeakMap();
    const protectedContent = 'script,style,svg,textarea,input,pre,code,iframe,[contenteditable],[data-no-ui-translate],.result-prompt,.markdown-rendered:not(#resultTextContent),.result-text-content:not(#resultTextContent),#ttsSpeakingText,#videoOverlay,#fullscreenVlmContent,#currentPrompt,#requestPayloadContent,#responsePayloadContent,#midTermMemoryContent,#longTermMemoryContent';
    const historyControls = '.alive-empty,#markdownToggle,#copyButton,.background-summary-label,.background-result-title,.background-result-action,.background-origin-action,.background-jump-button,.background-jump-question-label,.background-view-toolbar,.background-raw-toolbar';
    function excluded(node, attribute = false) {
        const e = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
        if (!e || e.closest(attribute ? protectedContent.replace('textarea,input,', '') : protectedContent)) return true;
        return Boolean(e.closest('#resultTextContent,.result-text') && !e.closest(historyControls));
    }
    function translate(source) {
        if (language !== 'zh') return source;
        const key = source.trim();
        const translated = translations[key];
        return translated ? source.replace(key, translated) : source;
    }
    function applyText(node) {
        if (excluded(node)) return;
        const current = node.nodeValue;
        let state = original.get(node);
        if (!state || state.rendered !== current) state = { source: current };
        state.rendered = translate(state.source);
        original.set(node, state);
        if (current !== state.rendered) node.nodeValue = state.rendered;
    }
    function applyAttribute(element, attribute) {
        if (excluded(element, true)) return;
        const current = element.getAttribute(attribute);
        if (current === null) return;
        const states = originalAttributes.get(element) || {};
        let state = states[attribute];
        if (!state || state.rendered !== current) state = { source: current };
        state.rendered = translate(state.source);
        states[attribute] = state;
        originalAttributes.set(element, states);
        if (current !== state.rendered) element.setAttribute(attribute, state.rendered);
    }
    const languageControl = document.createElement('div');
    languageControl.className = 'ui-language-control';
    languageControl.setAttribute('role', 'group');
    languageControl.setAttribute('aria-label', 'Interface language');
    languageControl.innerHTML = '<button type="button" data-ui-language="zh" data-no-ui-translate lang="zh-CN">中文</button><button type="button" data-ui-language="en" data-no-ui-translate lang="en">EN</button>';
    document.querySelector('.header-right').prepend(languageControl);
    const voiceControl = document.createElement('label');
    voiceControl.className = 'tts-voice-control';
    voiceControl.htmlFor = 'ttsVoiceSelect';
    voiceControl.innerHTML = '<span>TTS voice</span><select id="ttsVoiceSelect" title="Voice for spoken replies" disabled><option>Loading voices…</option></select>';
    document.getElementById('voiceModeStatus').before(voiceControl);
    const voiceSelect = document.getElementById('ttsVoiceSelect');
    voiceSelect.addEventListener('change', () => {
        voice = voiceSelect.value;
        save(voiceKey, voice);
    });
    const observer = new MutationObserver(records => {
        if (records.some(record => !excluded(record.target, record.type === 'attributes') ||
            [...record.addedNodes].some(node => node.nodeType === Node.ELEMENT_NODE &&
                (node.matches(historyControls) || node.querySelector(historyControls))))) schedule();
    });
    let scheduled = false;
    function schedule() {
        if (scheduled) return;
        scheduled = true;
        queueMicrotask(applyLanguage);
    }
    function applyLanguage() {
        scheduled = false;
        observer.disconnect();
        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
        while (walker.nextNode()) applyText(walker.currentNode);
        document.querySelectorAll('[title],[placeholder],[aria-label]').forEach(element => {
            for (const attribute of ['title', 'placeholder', 'aria-label']) applyAttribute(element, attribute);
        });
        document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en';
        languageControl.querySelectorAll('button').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.uiLanguage === language)));
        observer.observe(document.body, {subtree:true, childList:true, characterData:true, attributes:true, attributeFilter:['title','placeholder','aria-label']});
    }
    languageControl.addEventListener('click', event => {
        const button = event.target.closest('[data-ui-language]');
        if (!button) return;
        language = button.dataset.uiLanguage;
        save(languageKey, language);
        applyLanguage();
    });
    const names = {serena:'Serena', vivian:'Vivian', uncle_fu:'Uncle Fu', ryan:'Ryan', aiden:'Aiden', ono_anna:'Ono Anna', sohee:'Sohee', eric:'Eric', dylan:'Dylan'};
    async function loadVoices() {
        try {
            const response = await fetch('/api/tts/config', {signal:AbortSignal.timeout(10000)});
            if (!response.ok) throw new Error('Voice configuration unavailable');
            const config = await response.json();
            const choices = config.available_voices;
            if (!Array.isArray(choices) || !choices.length) throw new Error('No available voices');
            if (!choices.includes(voice)) voice = config.default_voice || choices[0];
            voiceSelect.replaceChildren(...choices.map(id => new Option(names[id] || id, id)));
            voiceSelect.value = voice;
            voiceSelect.disabled = false;
            save(voiceKey, voice);
        } catch (error) {
            voiceSelect.replaceChildren(new Option('Voices unavailable', ''));
            voiceSelect.disabled = true;
            setTimeout(loadVoices, 15000);
        }
        schedule();
    }
    window.aliveUi = { get voice() { return voice; }, get language() { return language; } };
    applyLanguage();
    loadVoices();
})();

</script>
<script>
(() => {
    let ownedSession = null;
    let acquiring = false;
    let lastState = null;
    let networkError = false;
    const status = document.createElement('span');
    status.className = 'admission-status';
    status.setAttribute('role', 'status');
    status.setAttribute('data-no-ui-translate', '');
    document.querySelector('.header-right').prepend(status);
    const zh = () => document.documentElement.lang.startsWith('zh');
    function render() {
        const mine = lastState?.mine && ownedSession === sessionId;
        const busy = lastState?.busy && !mine;
        const text = networkError ? (zh()?'连接检查中':'Checking connection')
            : mine ? (zh()?'你正在使用':'Your session')
            : busy ? (zh()?'有人使用中':'In use')
            : (zh()?'空闲 · 单人使用':'Available · one at a time');
        if (status.textContent !== text) status.textContent = text;
        status.dataset.busy = String(Boolean(busy));
        const title = busy ? (zh()?'其他人正在使用,请等待对方停止或断开连接。':'Someone else is using ALIVE. Please wait until they stop or disconnect.')
            : (zh()?'打开摄像头后占用,停止后释放。':'Opening your camera reserves ALIVE; stopping releases it.');
        if (status.title !== title) status.title = title;
        if (!isAnalysisRunning) document.getElementById('bigStartBtn').disabled = Boolean(busy || acquiring || networkError);
    }
    async function request(path, sid, method='POST') {
        const response = await fetch('/api/use/'+path+(method==='GET'?'?session_id='+encodeURIComponent(sid):''), {
            method, cache:'no-store', signal:AbortSignal.timeout(12000),
            ...(method==='POST'?{headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid})}:{})
        });
        const state = await response.json();
        return {response,state};
    }
    async function releaseOwned(sid=ownedSession) {
        if (!sid) return;
        if (ownedSession===sid) ownedSession=null;
        try { await request('release',sid); } catch { /* lease expiry recovers disconnects */ }
    }
    const originalStart = start;
    start = async function(...args) {
        if (acquiring || isAnalysisRunning) return;
        acquiring=true; render();
        const sid=sessionId;
        try {
            const {response,state}=await request('acquire',sid);
            lastState=state; networkError=false;
            if (!response.ok || !state.mine) {
                stopVoiceMode(zh()?'有人正在使用,请稍后重试。':'ALIVE is in use. Please try again later.');
                return;
            }
            ownedSession=sid;
            await originalStart(...args);
        } catch (error) {
            await releaseOwned(sid);
            networkError=true;
            stopVoiceMode(zh()?'连接失败,请稍后重试。':'Connection failed. Please try again.');
        } finally {
            acquiring=false; render();
        }
    };
    const originalStop = stop;
    stop = async function(...args) {
        const sid=ownedSession;
        try { return await originalStop(...args); }
        finally { await releaseOwned(sid); await refresh(); }
    };
    let checking=false;
    async function refresh() {
        if (checking) return;
        checking=true;
        try {
            const {response,state}=await request(ownedSession?'heartbeat':'status',ownedSession||sessionId,ownedSession?'POST':'GET');
            networkError=false; lastState=state;
            if (ownedSession && (!response.ok || !state.mine)) {
                ownedSession=null;
                await originalStop();
            }
        } catch { networkError=true; }
        finally { checking=false; render(); }
    }
    window.addEventListener('pagehide',()=>{
        if (ownedSession) navigator.sendBeacon('/api/use/release',new Blob([JSON.stringify({session_id:ownedSession})],{type:'application/json'}));
    });
    new MutationObserver(render).observe(document.documentElement,{attributes:true,attributeFilter:['lang']});
    setInterval(refresh,5000);
    refresh();
})();

</script>
</body>
</html>