From 9b5711d3124622b1f1b18500d442c76492da877a Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期一, 17 八月 2026 16:52:33 +0800
Subject: [PATCH] 优化llm插件及bug修复

---
 samples/plugins/sample.llm-command-palette/index.html | 1889 ++++++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 1,352 insertions(+), 537 deletions(-)

diff --git a/samples/plugins/sample.llm-command-palette/index.html b/samples/plugins/sample.llm-command-palette/index.html
index 0fe981e..87b804c 100644
--- a/samples/plugins/sample.llm-command-palette/index.html
+++ b/samples/plugins/sample.llm-command-palette/index.html
@@ -1,5 +1,6 @@
 <!doctype html>
 <html lang="en">
+
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -7,8 +8,21 @@
   <style>
     :root {
       color-scheme: dark;
-      font-family: "Segoe UI", system-ui, sans-serif;
-      background: transparent;
+      --bar-bg: rgba(29, 28, 27, 0.78);
+      --bar-bg-solid: rgb(35, 34, 33);
+      --panel-bg: rgba(25, 24, 23, 0.82);
+      --line: rgba(255, 255, 255, 0.12);
+      --line-strong: rgba(255, 255, 255, 0.18);
+      --text: rgba(255, 255, 255, 0.9);
+      --muted: rgba(255, 255, 255, 0.56);
+      --dim: rgba(255, 255, 255, 0.38);
+      --accent: #e76f45;
+      --error: #ff8b7f;
+      --ok: #8fe0bb;
+      --shadow: 0 16px 38px rgba(0, 0, 0, 0.22);
+      --panel-max-height: 420px;
+      --response-max-height: 376px;
+      font-family: "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
     }
 
     * {
@@ -18,670 +32,1471 @@
     html,
     body {
       width: 100%;
-      min-height: 100%;
+      height: 100%;
+      min-width: 0;
       margin: 0;
-      background: transparent;
       overflow: hidden;
+      background: transparent;
     }
 
     body {
+      color: var(--text);
+      user-select: none;
+    }
+
+    .palette-shell {
+      width: 100%;
+      height: 100%;
+      min-width: 360px;
+      min-height: 0;
       padding: 8px;
+      display: flex;
+      flex-direction: column;
     }
 
-    .shell {
+    .palette {
       width: 100%;
-      color: rgba(255, 255, 255, 0.92);
-    }
-
-    .bar,
-    .output,
-    .memory {
-      width: 100%;
-      border: 1px solid rgba(255, 255, 255, 0.14);
-      background: rgba(28, 26, 25, 0.72);
-      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
-      backdrop-filter: blur(18px);
-    }
-
-    .bar {
-      display: grid;
-      grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px);
-      align-items: center;
-      gap: 14px;
-      min-height: 56px;
-      padding: 0 20px;
+      flex: 1 1 auto;
+      min-height: 0;
+      display: flex;
+      flex-direction: column;
+      border: 1px solid var(--line);
       border-radius: 20px;
+      background: var(--bar-bg-solid);
+      background: var(--bar-bg);
+      box-shadow: var(--shadow), inset 0 1px 0 rgba(255, 255, 255, 0.06);
+      overflow: visible;
     }
 
-    .mark {
+    @supports ((backdrop-filter: blur(18px)) or (-webkit-backdrop-filter: blur(18px))) {
+      .palette {
+        -webkit-backdrop-filter: blur(18px) saturate(128%);
+        backdrop-filter: blur(18px) saturate(128%);
+      }
+    }
+
+    .input-row {
+      display: grid;
+      grid-template-columns: 24px minmax(96px, 154px) 1fr auto minmax(92px, 132px);
+      align-items: center;
+      gap: 8px;
+      flex: 0 0 auto;
+      min-height: 54px;
+      padding: 0 14px 0 18px;
+    }
+
+    .status-mark {
       width: 18px;
       height: 18px;
-      color: #ff8258;
       display: grid;
       place-items: center;
-      font-size: 20px;
-      line-height: 1;
-      transform-origin: center;
+      border-radius: 999px;
+      color: var(--accent);
+      flex: 0 0 auto;
     }
 
-    .mark.busy {
-      animation: spin 1.1s linear infinite;
+    .status-mark::before {
+      content: "";
+      width: 15px;
+      height: 15px;
+      display: block;
+      background:
+        conic-gradient(from 0deg, transparent 0 9deg, currentColor 10deg 18deg, transparent 19deg 39deg, currentColor 40deg 48deg, transparent 49deg 69deg, currentColor 70deg 78deg, transparent 79deg 99deg, currentColor 100deg 108deg, transparent 109deg 129deg, currentColor 130deg 138deg, transparent 139deg 159deg, currentColor 160deg 168deg, transparent 169deg 189deg, currentColor 190deg 198deg, transparent 199deg 219deg, currentColor 220deg 228deg, transparent 229deg 249deg, currentColor 250deg 258deg, transparent 259deg 279deg, currentColor 280deg 288deg, transparent 289deg 309deg, currentColor 310deg 318deg, transparent 319deg 339deg, currentColor 340deg 348deg, transparent 349deg);
+      -webkit-mask: radial-gradient(circle, transparent 0 3px, #000 3.2px 7.5px, transparent 7.8px);
+      mask: radial-gradient(circle, transparent 0 3px, #000 3.2px 7.5px, transparent 7.8px);
     }
 
-    @keyframes spin {
-      to { transform: rotate(360deg); }
+    .status-mark.loading::before {
+      width: 16px;
+      height: 16px;
+      border: 2px solid rgba(255, 255, 255, 0.18);
+      border-top-color: var(--accent);
+      border-radius: 999px;
+      background: none;
+      -webkit-mask: none;
+      mask: none;
+      animation: spin 0.9s linear infinite;
     }
 
-    textarea {
-      width: 100%;
-      min-height: 24px;
-      max-height: 78px;
-      resize: none;
-      border: 0;
-      outline: none;
-      color: rgba(255, 255, 255, 0.94);
-      background: transparent;
-      font: 600 16px/1.35 "Segoe UI", system-ui, sans-serif;
-      letter-spacing: 0;
-      overflow-y: auto;
+    .status-mark.error {
+      color: var(--error);
     }
 
-    textarea::placeholder {
-      color: rgba(255, 255, 255, 0.46);
+    .status-mark.error::before {
+      width: 10px;
+      height: 10px;
+      border-radius: 999px;
+      background: currentColor;
+      -webkit-mask: none;
+      mask: none;
+      box-shadow: 0 0 0 4px rgba(255, 139, 127, 0.14);
     }
 
-    input {
-      width: 100%;
-      height: 34px;
-      border: 1px solid rgba(255, 255, 255, 0.13);
-      outline: none;
-      color: rgba(255, 255, 255, 0.88);
-      background: rgba(255, 255, 255, 0.07);
-      border-radius: 8px;
-      padding: 0 30px 0 10px;
-      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
-      letter-spacing: 0;
-      transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;
-    }
-
-    .combo {
-      position: relative;
-      width: 100%;
+    .select-wrap {
       min-width: 0;
-    }
-
-    .combo-input {
-      display: none;
-    }
-
-    .combo-trigger {
-      width: 100%;
-      height: 34px;
-      border: 0;
-      border-radius: 8px;
-      color: rgba(255, 255, 255, 0.82);
-      background: transparent;
-      padding: 0 28px 0 10px;
-      text-align: left;
-      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
-      letter-spacing: 0;
-      cursor: pointer;
-      overflow: hidden;
-      text-overflow: ellipsis;
-      white-space: nowrap;
       position: relative;
-      transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;
     }
 
-    .combo-trigger::after {
+    .select-wrap::after {
       content: "";
       position: absolute;
-      right: 11px;
-      top: 13px;
+      right: 8px;
+      top: 50%;
       width: 7px;
       height: 7px;
-      border-right: 2px solid rgba(255, 255, 255, 0.72);
-      border-bottom: 2px solid rgba(255, 255, 255, 0.72);
-      transform: rotate(45deg);
+      border-right: 1.5px solid var(--dim);
+      border-bottom: 1.5px solid var(--dim);
+      transform: translateY(-65%) rotate(45deg);
+      pointer-events: none;
     }
 
-    input:hover,
-    input:focus,
-    .combo.open .combo-trigger,
-    .combo-trigger:hover,
-    .combo-trigger:focus {
-      background-color: rgba(255, 255, 255, 0.08);
-      box-shadow: none;
+    .select-control {
+      width: 100%;
+      height: 34px;
+      line-height: 32px !important;
+      padding: 0 22px 0 10px;
+      border: 1px solid transparent;
+      border-radius: 10px;
+      background: rgba(255, 255, 255, 0.04);
+      color: var(--muted);
+      font: 500 12px/1 "Segoe UI", system-ui, sans-serif;
+      outline: none;
+      appearance: none;
+      white-space: nowrap;
+      text-overflow: ellipsis;
+      overflow: hidden;
+      cursor: pointer;
     }
 
-    .combo-menu {
+    .select-control:hover,
+    .select-control:focus-visible,
+    .select-control.open {
+      color: var(--text);
+      border-color: var(--line-strong);
+      background: rgba(255, 255, 255, 0.07);
+    }
+
+    .select-menu {
       position: absolute;
       left: 0;
       right: 0;
       top: calc(100% + 6px);
-      z-index: 10;
+      z-index: 30;
       display: none;
-      max-height: 184px;
-      overflow-y: auto;
+      max-height: 190px;
+      overflow: auto;
       padding: 6px;
-      border: 1px solid rgba(255, 255, 255, 0.13);
+      border: 1px solid var(--line-strong);
       border-radius: 10px;
-      background: rgba(28, 26, 25, 0.92);
+      background: rgba(31, 30, 29, 0.96);
       box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26);
-      backdrop-filter: blur(16px);
     }
 
-    .combo.open .combo-menu {
+    .select-control.open + .select-menu {
       display: block;
     }
 
-    .combo-option {
-      min-height: 36px;
+    .select-option {
+      min-height: 30px;
       display: flex;
       align-items: center;
+      padding: 0 8px;
       border-radius: 7px;
-      padding: 0 10px;
-      color: rgba(255, 255, 255, 0.86);
-      font: 600 13px/1.2 "Segoe UI", system-ui, sans-serif;
-      cursor: pointer;
+      color: var(--muted);
+      font: 500 12px/1.2 "Segoe UI", system-ui, sans-serif;
       overflow: hidden;
       text-overflow: ellipsis;
       white-space: nowrap;
-    }
-
-    .combo-option:hover,
-    .combo-option.selected {
-      background: rgba(255, 130, 88, 0.16);
-      color: rgba(255, 255, 255, 0.96);
-    }
-
-    .output,
-    .memory {
-      display: none;
-      margin-top: 8px;
-      max-height: 50vh;
-      overflow: auto;
-      border-radius: 16px;
-      padding: 16px 18px 14px;
-      font-size: 14px;
-      line-height: 1.55;
-      white-space: pre-wrap;
-    }
-
-    .output.open,
-    .memory.open {
-      display: block;
-      animation: panelIn 160ms ease-out;
-    }
-
-    @keyframes panelIn {
-      from { opacity: 0; transform: translateY(-3px); }
-      to { opacity: 1; transform: translateY(0); }
-    }
-
-    .actions,
-    .memory-actions {
-      display: flex;
-      justify-content: flex-end;
-      gap: 8px;
-      margin-top: 12px;
-    }
-
-    .memory-row {
-      display: grid;
-      grid-template-columns: minmax(0, 1fr) 32px;
-      gap: 8px;
-      align-items: start;
-      padding: 8px 0;
-      border-top: 1px solid rgba(255, 255, 255, 0.08);
-      white-space: normal;
-    }
-
-    .memory-row:first-child {
-      border-top: 0;
-    }
-
-    .memory-content {
-      color: rgba(255, 255, 255, 0.86);
-      overflow-wrap: anywhere;
-    }
-
-    button {
-      width: 30px;
-      height: 30px;
-      border: 0;
-      border-radius: 8px;
-      color: rgba(255, 255, 255, 0.84);
-      background: rgba(255, 255, 255, 0.08);
       cursor: pointer;
-      font: 700 13px/1 "Segoe UI", system-ui, sans-serif;
     }
 
-    button:disabled,
-    input:disabled {
+    .select-option:hover,
+    .select-option.selected {
+      color: var(--text);
+      background: rgba(231, 111, 69, 0.14);
+    }
+
+    .prompt-editor {
+      width: 100%;
+      min-width: 0;
+      max-height: 66px;
+      min-height: 24px;
+      padding: 2px 0;
+      border: 0;
+      resize: none;
+      overflow: hidden;
+      outline: none;
+      background: transparent;
+      color: var(--text);
+      font: 500 16px/1.45 "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
+      letter-spacing: 0;
+    }
+
+    .prompt-editor:empty::before {
+      content: attr(data-placeholder);
+      color: var(--muted);
+      pointer-events: none;
+    }
+
+    .tool-button {
+      width: 32px;
+      height: 32px;
+      display: grid;
+      place-items: center;
+      border: 1px solid transparent;
+      border-radius: 10px;
+      background: rgba(255, 255, 255, 0.04);
+      color: var(--muted);
+      font: 700 12px/1 "Segoe UI", system-ui, sans-serif;
+      cursor: pointer;
+    }
+
+    .tool-button:hover,
+    .tool-button:focus-visible,
+    .tool-button.active {
+      color: var(--text);
+      border-color: var(--line-strong);
+      background: rgba(255, 255, 255, 0.08);
+      outline: none;
+    }
+
+    .tool-button.disabled,
+    .icon-action.disabled,
+    .memory-input.disabled {
       cursor: not-allowed;
       opacity: 0.52;
+      pointer-events: none;
     }
 
-    .error {
-      color: #ffad9b;
+    .output-panel,
+    .memory-panel {
+      max-height: 0;
+      opacity: 0;
+      overflow: hidden;
+      border-top: 0 solid transparent;
+      transition: opacity 140ms ease, border-color 140ms ease;
+    }
+
+    .memory-panel {
+      transition: max-height 160ms ease, opacity 140ms ease, border-color 140ms ease;
+    }
+
+    .output-panel.open,
+    .memory-panel.open {
+      max-height: var(--panel-max-height);
+      opacity: 1;
+      border-top: 1px solid rgba(255, 255, 255, 0.08);
+    }
+
+    .output-panel.open {
+      flex: 1 0 auto;
+      min-height: 0;
+      display: flex;
+      flex-direction: column;
+      overflow: hidden;
+      max-height: none;
+    }
+
+    .output-scroll {
+      position: relative;
+      flex: 1 1 auto;
+      min-height: 0;
+    }
+
+    .output-inner {
+      height: auto;
+      max-height: var(--response-max-height);
+      overflow-x: hidden;
+      overflow-y: auto;
+      overscroll-behavior: contain;
+      padding: 8px 22px 14px 18px;
+      color: rgba(255, 255, 255, 0.86);
+      font: 14px/1.58 "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
+      white-space: pre-wrap;
+      user-select: text;
+      background: rgba(0, 0, 0, 0.16);
+    }
+
+    .output-inner::-webkit-scrollbar {
+      width: 0;
+      height: 0;
+    }
+
+    .output-scrollbar {
+      position: absolute;
+      top: 8px;
+      right: 6px;
+      bottom: 8px;
+      width: 10px;
+      border-radius: 999px;
+      background: rgb(58, 56, 54);
+      opacity: 0.5;
+      z-index: 4;
+    }
+
+    .output-scrollbar[hidden] {
+      display: none;
+    }
+
+    .output-thumb {
+      position: absolute;
+      left: 1px;
+      right: 1px;
+      min-height: 28px;
+      border-radius: 999px;
+      background: rgb(196, 194, 191);
+      cursor: grab;
+      touch-action: none;
+    }
+
+    .output-thumb:hover,
+    .output-thumb.dragging {
+      background: rgb(230, 228, 225);
+      cursor: grabbing;
+    }
+
+    .output-inner.error {
+      color: var(--error);
+    }
+
+    .output-inner:empty::before {
+      content: attr(data-placeholder);
+      color: var(--dim);
+    }
+
+    .stream-caret {
+      display: inline-block;
+      width: 6px;
+      height: 1em;
+      margin-left: 2px;
+      vertical-align: -2px;
+      border-radius: 999px;
+      background: var(--accent);
+      animation: pulse 1s ease-in-out infinite;
+    }
+
+    .actions {
+      flex: 0 0 auto;
+      display: flex;
+      justify-content: flex-end;
+      gap: 6px;
+      padding: 8px 12px 0;
+    }
+
+    .icon-action {
+      width: 30px;
+      height: 28px;
+      display: grid;
+      place-items: center;
+      border: 1px solid transparent;
+      border-radius: 8px;
+      background: transparent;
+      color: var(--muted);
+      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
+      cursor: pointer;
+    }
+
+    .icon-action svg {
+      width: 14px;
+      height: 14px;
+      display: block;
+      fill: none;
+      stroke: currentColor;
+      stroke-width: 1.7;
+      stroke-linecap: round;
+      stroke-linejoin: round;
+    }
+
+    .icon-action:hover,
+    .icon-action:focus-visible {
+      color: var(--text);
+      border-color: var(--line);
+      background: rgba(255, 255, 255, 0.06);
+      outline: none;
+    }
+
+    .memory-panel.open {
+      background: rgba(0, 0, 0, 0.1);
+    }
+
+    .memory-inner {
+      display: grid;
+      grid-template-columns: 1fr auto;
+      gap: 8px;
+      padding: 12px 14px;
+    }
+
+    .memory-list {
+      min-height: 34px;
+      max-height: 134px;
+      overflow: auto;
+      color: var(--muted);
+      font-size: 12px;
+      user-select: text;
+    }
+
+    .memory-item {
+      display: flex;
+      align-items: flex-start;
+      gap: 8px;
+      padding: 7px 0;
+      border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+    }
+
+    .memory-item:last-child {
+      border-bottom: 0;
+    }
+
+    .memory-text {
+      min-width: 0;
+      flex: 1;
+      color: rgba(255, 255, 255, 0.78);
+      line-height: 1.45;
+    }
+
+    .memory-form {
+      display: flex;
+      align-items: center;
+      gap: 6px;
+    }
+
+    .memory-input {
+      width: 180px;
+      height: 32px;
+      border: 1px solid var(--line);
+      border-radius: 9px;
+      padding: 0 10px;
+      outline: none;
+      background: rgba(255, 255, 255, 0.05);
+      color: var(--text);
+      font-size: 12px;
+      display: flex;
+      align-items: center;
+      overflow: hidden;
+      white-space: nowrap;
+    }
+
+    .memory-input:focus-visible {
+      border-color: var(--line-strong);
+    }
+
+    .memory-input:empty::before {
+      content: attr(data-placeholder);
+      color: var(--dim);
+      pointer-events: none;
+    }
+
+    .memory-status {
+      grid-column: 1 / -1;
+      color: var(--dim);
+      font-size: 12px;
+      min-height: 16px;
+    }
+
+    @keyframes spin {
+      to {
+        transform: rotate(360deg);
+      }
+    }
+
+    @keyframes pulse {
+      0%,
+      100% {
+        opacity: 0.25;
+      }
+
+      50% {
+        opacity: 0.9;
+      }
+    }
+
+    @media (max-width: 560px) {
+      .palette-shell {
+        min-width: 300px;
+        padding: 6px;
+      }
+
+      .input-row {
+        grid-template-columns: 22px minmax(74px, 104px) 1fr 30px minmax(76px, 96px);
+        gap: 6px;
+        padding: 0 10px 0 13px;
+      }
+
+      select {
+        padding-left: 7px;
+        font-size: 11px;
+      }
+
+      textarea {
+        font-size: 14px;
+      }
+
+      .memory-inner {
+        grid-template-columns: 1fr;
+      }
+
+      .memory-input {
+        width: 100%;
+      }
     }
   </style>
 </head>
+
 <body>
-  <main class="shell">
-    <section class="bar">
-      <div class="combo" id="projectCombo">
-        <input id="project" class="combo-input" aria-hidden="true">
-        <button id="projectButton" class="combo-trigger" type="button" title="AiChat project">Project</button>
-        <div id="projectMenu" class="combo-menu" role="listbox"></div>
+  <div class="palette-shell" role="main">
+    <div class="palette" role="region" aria-label="LLM command palette">
+      <div class="input-row">
+        <div id="statusMark" class="status-mark" title="Idle" aria-hidden="true"></div>
+        <div class="select-wrap">
+          <div id="projectSelect" class="select-control" role="combobox" tabindex="0" title="AiChat project"
+            aria-label="AiChat project" aria-expanded="false" data-value="">No project</div>
+          <div id="projectMenu" class="select-menu" role="listbox" aria-label="AiChat projects"></div>
+        </div>
+        <div id="promptInput" class="prompt-editor" contenteditable="true" spellcheck="true" role="textbox"
+          aria-multiline="true" data-placeholder="What can I help you with today?" aria-label="Prompt"></div>
+        <div id="memoryButton" class="tool-button" role="button" tabindex="0" title="Memories" aria-label="Memories">M</div>
+        <div class="select-wrap">
+          <div id="modelSelect" class="select-control" role="combobox" tabindex="0" title="Model" aria-label="Model"
+            aria-expanded="false" data-value="">Model</div>
+          <div id="modelMenu" class="select-menu" role="listbox" aria-label="Models"></div>
+        </div>
       </div>
-      <div id="mark" class="mark" aria-hidden="true">*</div>
-      <textarea id="prompt" rows="1" placeholder="What can I help you with today?"></textarea>
-      <button id="memoryToggle" title="Memory">M</button>
-      <div class="combo" id="modelCombo">
-        <input id="model" class="combo-input" aria-hidden="true">
-        <button id="modelButton" class="combo-trigger" type="button" title="Model">Model</button>
-        <div id="modelMenu" class="combo-menu" role="listbox"></div>
+
+      <div id="memoryPanel" class="memory-panel" role="region" aria-label="Memories">
+        <div class="memory-inner">
+          <div id="memoryList" class="memory-list"></div>
+          <div id="memoryForm" class="memory-form">
+            <div id="memoryInput" class="memory-input" contenteditable="true" role="textbox"
+              data-placeholder="Add memory" aria-label="Add memory text"></div>
+            <div id="addMemoryButton" class="icon-action" role="button" tabindex="0" title="Add memory"
+              aria-label="Add memory">+</div>
+            <div id="recallButton" class="icon-action" role="button" tabindex="0" title="Recall memories"
+              aria-label="Recall memories">R</div>
+          </div>
+          <div id="memoryStatus" class="memory-status"></div>
+        </div>
       </div>
-    </section>
-    <section id="output" class="output" aria-live="polite">
-      <div id="text"></div>
-      <div class="actions">
-        <button id="copy" title="Copy">C</button>
-        <button id="collapse" title="Collapse">-</button>
+
+      <div id="outputPanel" class="output-panel" aria-live="polite" role="region" aria-label="LLM response">
+        <div class="actions">
+          <div id="copyButton" class="icon-action" role="button" tabindex="0" title="Copy" aria-label="Copy">
+            <svg viewBox="0 0 16 16" aria-hidden="true">
+              <rect x="5.2" y="5.2" width="8" height="8" rx="1.4"></rect>
+              <path d="M10.8 5.2V3.8A1.4 1.4 0 0 0 9.4 2.4H3.8A1.4 1.4 0 0 0 2.4 3.8v5.6A1.4 1.4 0 0 0 3.8 10.8H5.2"></path>
+            </svg>
+          </div>
+          <div id="retryButton" class="icon-action" role="button" tabindex="0" title="Regenerate" aria-label="Regenerate">
+            <svg viewBox="0 0 16 16" aria-hidden="true">
+              <path d="M13.2 8A5.2 5.2 0 1 1 11.4 3.7"></path>
+              <path d="M11.2 2.2h2.4V4.6"></path>
+            </svg>
+          </div>
+          <div id="collapseButton" class="icon-action" role="button" tabindex="0" title="Collapse" aria-label="Collapse">
+            <svg viewBox="0 0 16 16" aria-hidden="true">
+              <path d="M4 4l8 8M12 4l-8 8"></path>
+            </svg>
+          </div>
+        </div>
+        <div class="output-scroll">
+          <div id="outputText" class="output-inner" tabindex="0" data-placeholder="Waiting for response"></div>
+          <div id="outputScrollbar" class="output-scrollbar" hidden>
+            <div id="outputThumb" class="output-thumb"></div>
+          </div>
+        </div>
       </div>
-    </section>
-    <section id="memory" class="memory" aria-live="polite">
-      <div id="memoryList"></div>
-      <div class="memory-actions">
-        <input id="memoryInput" placeholder="Save memory">
-        <button id="saveMemory" title="Save memory">+</button>
-        <button id="refreshMemory" title="Refresh memory">R</button>
-      </div>
-    </section>
-  </main>
+    </div>
+  </div>
 
   <script>
-    const promptInput = document.getElementById("prompt");
-    const projectSelect = document.getElementById("project");
-    const projectCombo = document.getElementById("projectCombo");
-    const projectButton = document.getElementById("projectButton");
-    const projectMenu = document.getElementById("projectMenu");
-    const modelSelect = document.getElementById("model");
-    const modelCombo = document.getElementById("modelCombo");
-    const modelButton = document.getElementById("modelButton");
-    const modelMenu = document.getElementById("modelMenu");
-    const output = document.getElementById("output");
-    const text = document.getElementById("text");
-    const mark = document.getElementById("mark");
-    const copy = document.getElementById("copy");
-    const collapse = document.getElementById("collapse");
-    const memoryToggle = document.getElementById("memoryToggle");
-    const memoryPanel = document.getElementById("memory");
-    const memoryList = document.getElementById("memoryList");
-    const memoryInput = document.getElementById("memoryInput");
-    const saveMemory = document.getElementById("saveMemory");
-    const refreshMemory = document.getElementById("refreshMemory");
+    const bridge = window.moliDesktop || null;
+    const llm = bridge && bridge.llm ? bridge.llm : null;
 
-    if (!window.moliDesktop) {
-      window.moliDesktop = {
-        getConfig: async () => ({
-          mode: "provider-direct",
-          aichat: { memory: { enabledInProviderDirect: false, defaultScope: "PROJECT", recallLimit: 8 } }
-        }),
-        requestResize: async () => {},
-        llm: {
-          getProjects: async () => [],
-          getModels: async () => [],
-          getMemoryCapabilities: async () => ({ canUseMemory: false, canViewMemory: false, canManageMemory: false }),
-          getMemories: async () => ({ items: [] }),
-          createMemory: async () => ({}),
-          deleteMemory: async () => {},
-          recallMemories: async () => ({ items: [] }),
-          streamChat: async () => ({ requestId: "preview" }),
-          onDelta: () => () => {},
-          onCompleted: () => () => {},
-          onError: () => () => {}
+    const state = {
+      mode: "provider-direct",
+      models: [],
+      projects: [],
+      projectStatus: "",
+      selectedModelId: "",
+      selectedProjectId: "",
+      requestId: "",
+      busy: false,
+      output: "",
+      lastPrompt: "",
+      memories: [],
+      memoryCapabilities: {
+        canUseMemory: false,
+        canViewMemory: false,
+        canManageMemory: false
+      },
+      config: {}
+    };
+
+    let _resizeFrame = 0;
+
+    const els = {
+      paletteShell: document.querySelector(".palette-shell"),
+      statusMark: document.getElementById("statusMark"),
+      projectSelect: document.getElementById("projectSelect"),
+      projectMenu: document.getElementById("projectMenu"),
+      modelSelect: document.getElementById("modelSelect"),
+      modelMenu: document.getElementById("modelMenu"),
+      promptInput: document.getElementById("promptInput"),
+      outputPanel: document.getElementById("outputPanel"),
+      outputText: document.getElementById("outputText"),
+      outputScrollbar: document.getElementById("outputScrollbar"),
+      outputThumb: document.getElementById("outputThumb"),
+      memoryButton: document.getElementById("memoryButton"),
+      memoryPanel: document.getElementById("memoryPanel"),
+      memoryList: document.getElementById("memoryList"),
+      memoryForm: document.getElementById("memoryForm"),
+      memoryInput: document.getElementById("memoryInput"),
+      addMemoryButton: document.getElementById("addMemoryButton"),
+      memoryStatus: document.getElementById("memoryStatus"),
+      recallButton: document.getElementById("recallButton"),
+      copyButton: document.getElementById("copyButton"),
+      retryButton: document.getElementById("retryButton"),
+      collapseButton: document.getElementById("collapseButton")
+    };
+
+    const fallbackModels = [
+      { id: "deepseek-v4-flash", label: "DeepSeek", provider: "deepseek", supportsStreaming: true, enabled: true },
+      { id: "kimi-k2.6", label: "Kimi", provider: "kimi", supportsStreaming: true, enabled: true },
+      { id: "glm-4.7-flash", label: "GLM", provider: "bigmodel", supportsStreaming: true, enabled: true }
+    ];
+    const MODEL_PAGE_SIZE = 20;
+
+    const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+    function getText(element) {
+      return (element.textContent || "").replace(/\u00a0/g, " ");
+    }
+
+    function setText(element, value) {
+      element.textContent = value || "";
+    }
+
+    function getSelectValue(control) {
+      return control.dataset.value || "";
+    }
+
+    function setDisabled(element, disabled) {
+      element.classList.toggle("disabled", Boolean(disabled));
+      element.setAttribute("aria-disabled", disabled ? "true" : "false");
+      if (element.hasAttribute("contenteditable")) {
+        element.setAttribute("contenteditable", disabled ? "false" : "true");
+      }
+    }
+
+    function invokeOnAction(element, handler) {
+      element.addEventListener("click", (event) => {
+        if (element.classList.contains("disabled")) return;
+        handler(event);
+      });
+      element.addEventListener("keydown", (event) => {
+        if (element.classList.contains("disabled")) return;
+        if (event.key === "Enter" || event.key === " ") {
+          event.preventDefault();
+          handler(event);
         }
-      };
-    }
-
-    let activeRequestId = null;
-    let currentText = "";
-    let config = { mode: "provider-direct", aichat: { memory: { enabledInProviderDirect: true, defaultScope: "PROJECT", recallLimit: 8 } } };
-    let memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
-
-    function mode() {
-      return config.mode || "provider-direct";
-    }
-
-    function selectedProjectId() {
-      return projectSelect.value || config.aichat?.defaultProjectId || "";
-    }
-
-    function setBusy(busy) {
-      mark.classList.toggle("busy", busy);
-      mark.textContent = busy ? "*" : "*";
-    }
-
-    function openOutput() {
-      output.classList.add("open");
-      requestResize();
-    }
-
-    function requestResize() {
-      const openMenu = projectCombo.classList.contains("open")
-        ? projectMenu
-        : modelCombo.classList.contains("open") ? modelMenu : null;
-      const menuBottom = openMenu ? openMenu.getBoundingClientRect().bottom + 8 : 72;
-      window.moliDesktop?.requestResize?.({
-        width: document.body.scrollWidth,
-        height: Math.max(72, Math.ceil(menuBottom))
-      }).catch(() => {});
-    }
-
-    function setError(message) {
-      currentText = message;
-      text.className = "error";
-      text.textContent = message;
-      openOutput();
-    }
-
-    const projectDropdown = { input: projectSelect, root: projectCombo, button: projectButton, menu: projectMenu };
-    const modelDropdown = { input: modelSelect, root: modelCombo, button: modelButton, menu: modelMenu };
-
-    function setupDropdown(dropdown) {
-      dropdown.button.addEventListener("click", () => {
-        const willOpen = !dropdown.root.classList.contains("open");
-        closeDropdowns();
-        dropdown.root.classList.toggle("open", willOpen);
-        requestResize();
       });
     }
 
-    function closeDropdowns() {
-      projectCombo.classList.remove("open");
-      modelCombo.classList.remove("open");
-      requestResize();
+    function asArray(value) {
+      return Array.isArray(value) ? value : [];
     }
 
-    function setDropdownFallback(dropdown, label, title) {
-      dropdown.input.value = "";
-      dropdown.button.textContent = label;
-      dropdown.button.title = title || label;
-      dropdown.menu.innerHTML = "";
-      const option = document.createElement("div");
-      option.className = "combo-option";
-      option.textContent = label;
-      option.title = title || label;
-      dropdown.menu.appendChild(option);
+    function getErrorMessage(error, fallback) {
+      if (!error) return fallback;
+      if (typeof error === "string") return error;
+      return error.message || error.Message || error.code || error.Code || fallback;
     }
 
-    function setDropdownOptions(dropdown, items, preferredValue, fallbackLabel) {
-      dropdown.menu.innerHTML = "";
-      if (!items.length) {
-        setDropdownFallback(dropdown, fallbackLabel);
+    function normalizeEvent(detail) {
+      const event = detail && (detail.event || detail.Event || detail);
+      return {
+        requestId: event.requestId || event.RequestId || detail.requestId || detail.RequestId || "",
+        delta: event.delta || event.Delta || "",
+        code: event.code || event.Code || "",
+        message: event.message || event.Message || ""
+      };
+    }
+
+    function setStatus(kind, title) {
+      els.statusMark.className = "status-mark" + (kind ? " " + kind : "");
+      els.statusMark.title = title || "Idle";
+    }
+
+    function getResponseMaxHeight() {
+      const raw = getComputedStyle(document.documentElement).getPropertyValue("--response-max-height");
+      const parsed = parseFloat(raw);
+      return Number.isFinite(parsed) && parsed > 0 ? parsed : 376;
+    }
+
+    function getShellChrome() {
+      const palette = document.querySelector(".palette");
+      const shellStyle = getComputedStyle(els.paletteShell);
+      const paletteStyle = getComputedStyle(palette);
+      return (parseFloat(shellStyle.paddingTop) || 0)
+        + (parseFloat(shellStyle.paddingBottom) || 0)
+        + (parseFloat(paletteStyle.borderTopWidth) || 0)
+        + (parseFloat(paletteStyle.borderBottomWidth) || 0);
+    }
+
+    function getChromeHeight() {
+      const inputRow = document.querySelector(".input-row");
+      const actions = document.querySelector(".actions");
+      const memoryH = els.memoryPanel.offsetHeight;
+      const actionsH = els.outputPanel.classList.contains("open") && actions ? actions.offsetHeight : 0;
+      const panelStyle = getComputedStyle(els.outputPanel);
+      const panelBorder = els.outputPanel.classList.contains("open")
+        ? (parseFloat(panelStyle.borderTopWidth) || 0) + (parseFloat(panelStyle.borderBottomWidth) || 0)
+        : 0;
+      return getShellChrome() + (inputRow ? inputRow.offsetHeight : 54) + memoryH + actionsH + panelBorder;
+    }
+
+    function measureOutputNaturalHeight() {
+      const el = els.outputText;
+      const prevHeight = el.style.height;
+      const prevMax = el.style.maxHeight;
+      el.style.height = "auto";
+      el.style.maxHeight = "none";
+      const natural = el.scrollHeight;
+      el.style.height = prevHeight;
+      el.style.maxHeight = prevMax;
+      return natural;
+    }
+
+    function getOutputScrollPortHeight(natural) {
+      const cssMax = getResponseMaxHeight();
+      const available = window.innerHeight - getChromeHeight();
+      if (available >= natural - 1) return Math.min(natural, cssMax);
+      if (available > 48) return Math.min(natural, cssMax, available);
+      return Math.min(natural, cssMax);
+    }
+
+    function syncOutputScrollbar() {
+      const scroller = els.outputText;
+      const track = els.outputScrollbar;
+      const thumb = els.outputThumb;
+      if (!scroller || !track || !thumb) return;
+      const canScroll = scroller.scrollHeight > scroller.clientHeight + 1;
+      track.hidden = !canScroll;
+      if (!canScroll) return;
+      const trackH = track.clientHeight;
+      const thumbH = Math.max(28, Math.floor(trackH * (scroller.clientHeight / scroller.scrollHeight)));
+      const maxTop = Math.max(0, trackH - thumbH);
+      const range = scroller.scrollHeight - scroller.clientHeight;
+      const progress = range > 0 ? scroller.scrollTop / range : 0;
+      thumb.style.height = thumbH + "px";
+      thumb.style.top = (maxTop * progress) + "px";
+    }
+
+    function syncOutputScrollbox() {
+      const natural = measureOutputNaturalHeight();
+      const port = getOutputScrollPortHeight(natural);
+      els.outputText.style.height = natural > port + 1 ? port + "px" : "";
+      syncOutputScrollbar();
+    }
+
+    function setOutput(text, options = {}) {
+      state.output = text || "";
+      els.outputText.classList.toggle("error", options.error === true);
+      els.outputText.textContent = state.output;
+      if (options.streaming) {
+        const caret = document.createElement("div");
+        caret.className = "stream-caret";
+        els.outputText.appendChild(caret);
+      }
+      els.outputPanel.classList.add("open");
+      requestHostResize();
+      syncOutputScrollbox();
+      els.outputText.scrollTop = els.outputText.scrollHeight;
+      syncOutputScrollbar();
+    }
+
+    function appendOutput(delta) {
+      state.output += delta || "";
+      setOutput(state.output, { streaming: state.busy });
+    }
+
+    function collapseOutput() {
+      els.outputPanel.classList.remove("open");
+      els.outputText.style.height = "";
+      els.outputText.style.maxHeight = "";
+      if (els.outputScrollbar) els.outputScrollbar.hidden = true;
+      closeSelects();
+      requestPaletteResize();
+    }
+
+    function bindOutputScrolling() {
+      let drag = null;
+      els.outputText.addEventListener("scroll", syncOutputScrollbar);
+      document.addEventListener("wheel", (event) => {
+        if (!els.outputPanel.classList.contains("open")) return;
+        if (event.target.closest(".select-menu, .memory-list")) return;
+        if (els.outputText.scrollHeight <= els.outputText.clientHeight + 1) return;
+        els.outputText.scrollTop += event.deltaY;
+        event.preventDefault();
+        syncOutputScrollbar();
+      }, { passive: false });
+
+      els.outputThumb.addEventListener("pointerdown", (event) => {
+        drag = {
+          pointerId: event.pointerId,
+          startY: event.clientY,
+          startTop: els.outputThumb.offsetTop
+        };
+        els.outputThumb.classList.add("dragging");
+        els.outputThumb.setPointerCapture(event.pointerId);
+        event.preventDefault();
+        event.stopPropagation();
+      });
+      els.outputThumb.addEventListener("pointermove", (event) => {
+        if (!drag || event.pointerId !== drag.pointerId) return;
+        const trackH = els.outputScrollbar.clientHeight;
+        const thumbH = els.outputThumb.offsetHeight;
+        const maxTop = Math.max(0, trackH - thumbH);
+        const top = Math.min(maxTop, Math.max(0, drag.startTop + (event.clientY - drag.startY)));
+        const range = els.outputText.scrollHeight - els.outputText.clientHeight;
+        els.outputText.scrollTop = maxTop > 0 && range > 0 ? (top / maxTop) * range : 0;
+        syncOutputScrollbar();
+      });
+      const endDrag = (event) => {
+        if (!drag || event.pointerId !== drag.pointerId) return;
+        drag = null;
+        els.outputThumb.classList.remove("dragging");
+      };
+      els.outputThumb.addEventListener("pointerup", endDrag);
+      els.outputThumb.addEventListener("pointercancel", endDrag);
+      els.outputScrollbar.addEventListener("pointerdown", (event) => {
+        if (event.target === els.outputThumb) return;
+        const rect = els.outputScrollbar.getBoundingClientRect();
+        const thumbH = els.outputThumb.offsetHeight;
+        const maxTop = Math.max(0, els.outputScrollbar.clientHeight - thumbH);
+        const top = Math.min(maxTop, Math.max(0, event.clientY - rect.top - thumbH / 2));
+        const range = els.outputText.scrollHeight - els.outputText.clientHeight;
+        els.outputText.scrollTop = maxTop > 0 && range > 0 ? (top / maxTop) * range : 0;
+        syncOutputScrollbar();
+      });
+    }
+
+    function resizeTextarea() {
+      els.promptInput.style.height = "0px";
+      const height = Math.min(66, Math.max(24, els.promptInput.scrollHeight));
+      els.promptInput.style.height = height + "px";
+    }
+
+    function isSelectOpen(control) {
+      return control.classList.contains("open");
+    }
+
+    function isPaletteExpanded() {
+      return els.outputPanel.classList.contains("open")
+        || els.memoryPanel.classList.contains("open")
+        || isSelectOpen(els.projectSelect)
+        || isSelectOpen(els.modelSelect);
+    }
+
+    function getOpenMenuExtent() {
+      let bottom = 0;
+      for (const control of [els.projectSelect, els.modelSelect]) {
+        if (!isSelectOpen(control)) continue;
+        const menu = control.nextElementSibling;
+        if (!menu) continue;
+        const rect = menu.getBoundingClientRect();
+        if (rect.height > 0) {
+          bottom = Math.max(bottom, Math.ceil(rect.bottom + 12));
+        }
+      }
+      return bottom;
+    }
+
+    function syncOpenMenuSpace() {
+      const extent = getOpenMenuExtent();
+      els.paletteShell.style.minHeight = extent > 0 ? extent + "px" : "";
+    }
+
+    function measureDesiredHeight() {
+      const outputH = els.outputPanel.classList.contains("open")
+        ? Math.min(measureOutputNaturalHeight(), getResponseMaxHeight())
+        : 0;
+      return Math.max(Math.ceil(getChromeHeight() + outputH + 15), getOpenMenuExtent());
+    }
+
+    function requestHostResize(explicitHeight) {
+      if (!bridge || typeof bridge.requestResize !== "function") return;
+      const screenHeight = window.screen && window.screen.availHeight ? window.screen.availHeight : 900;
+      const heightLimit = Math.floor(screenHeight * 0.5) + 88;
+      const apply = (height) => {
+        bridge.requestResize({ height }).catch(() => {});
+      };
+      if (_resizeFrame) {
+        cancelAnimationFrame(_resizeFrame);
+        _resizeFrame = 0;
+      }
+      if (explicitHeight != null) {
+        apply(explicitHeight);
         return;
       }
-
-      let selected = items.find((item) => item.value === preferredValue) || items[0];
-      for (const item of items) {
-        const option = document.createElement("div");
-        option.className = `combo-option${item.value === selected.value ? " selected" : ""}`;
-        option.textContent = item.label;
-        option.title = item.title || item.label;
-        option.dataset.value = item.value;
-        option.addEventListener("click", () => {
-          selected = item;
-          setDropdownValue(dropdown, item);
-          closeDropdowns();
-        });
-        dropdown.menu.appendChild(option);
-      }
-
-      setDropdownValue(dropdown, selected, false);
+      _resizeFrame = requestAnimationFrame(() => {
+        _resizeFrame = 0;
+        syncOpenMenuSpace();
+        apply(Math.min(measureDesiredHeight(), heightLimit));
+      });
     }
 
-    function setDropdownValue(dropdown, item, notify = true) {
-      dropdown.input.value = item.value;
-      dropdown.button.textContent = item.label;
-      dropdown.button.title = item.title || item.label;
-      for (const option of dropdown.menu.children) {
-        option.classList.toggle("selected", option.dataset.value === item.value);
+    function requestPaletteResize() {
+      if (!isPaletteExpanded()) {
+        syncOpenMenuSpace();
+        requestHostResize(72);
+        return;
       }
-      if (notify) {
-        dropdown.input.dispatchEvent(new Event("change"));
+      requestHostResize();
+    }
+
+    function scheduleSelectResize() {
+      requestAnimationFrame(() => requestPaletteResize());
+    }
+
+    function updatePanelLimits() {
+      const screenHeight = window.screen && window.screen.availHeight ? window.screen.availHeight : window.innerHeight || 900;
+      const panelMax = Math.max(180, Math.floor(screenHeight * 0.5));
+      document.documentElement.style.setProperty("--panel-max-height", panelMax + "px");
+      document.documentElement.style.setProperty("--response-max-height", Math.max(132, panelMax - 44) + "px");
+      if (els.outputPanel.classList.contains("open")) {
+        syncOutputScrollbox();
       }
+    }
+
+    function closeSelects() {
+      for (const control of [els.projectSelect, els.modelSelect]) {
+        control.classList.remove("open");
+        control.setAttribute("aria-expanded", "false");
+      }
+    }
+
+    function setSelectValue(control, menu, option) {
+      const value = option ? option.value : "";
+      const label = option ? option.label : control.dataset.emptyLabel || "";
+      control.dataset.value = value;
+      control.textContent = label;
+      control.title = option && option.title ? option.title : label;
+      for (const child of menu.children) {
+        child.classList.toggle("selected", child.dataset.value === value);
+      }
+      control.dispatchEvent(new CustomEvent("change", { detail: { value } }));
+    }
+
+    function setSelectOptions(control, menu, items, emptyLabel, selectedId, settings) {
+      const config = settings || {};
+      const autoSelectFirst = config.autoSelectFirst !== false;
+      const pageSize = config.pageSize || 0;
+      control.dataset.emptyLabel = emptyLabel;
+
+      const options = items
+        .map((item) => ({
+          value: item.id || item.Id || "",
+          label: item.label || item.name || item.Name || item.id || item.Id || emptyLabel,
+          title: [item.label || item.name || item.Name || item.id || item.Id, item.provider || item.Provider].filter(Boolean).join(" 路 ")
+        }))
+        .filter((item) => item.value);
+
+      menu._allOptions = options;
+      menu._pageSize = pageSize;
+      renderSelectPage(control, menu, true);
+
+      const selected = options.find((option) => option.value === selectedId)
+        || (autoSelectFirst ? options[0] : null)
+        || null;
+      setSelectValue(control, menu, selected || { value: "", label: emptyLabel, title: emptyLabel });
+    }
+
+    function renderSelectPage(control, menu, reset) {
+      const options = menu._allOptions || [];
+      const pageSize = menu._pageSize || 0;
+      if (reset) {
+        menu._renderedCount = 0;
+        menu.textContent = "";
+      }
+
+      const start = menu._renderedCount || 0;
+      const end = pageSize > 0 ? Math.min(options.length, start + pageSize) : options.length;
+      const selectedValue = control.dataset.value || "";
+      for (let index = start; index < end; index += 1) {
+        const option = options[index];
+        const item = document.createElement("div");
+        item.className = "select-option";
+        item.setAttribute("role", "option");
+        item.tabIndex = -1;
+        item.dataset.value = option.value;
+        item.textContent = option.label;
+        item.title = option.title || option.label;
+        if (option.value === selectedValue) item.classList.add("selected");
+        item.addEventListener("click", () => {
+          setSelectValue(control, menu, option);
+          closeSelects();
+          scheduleSelectResize();
+        });
+        menu.appendChild(item);
+      }
+
+      menu._renderedCount = end;
+      menu.style.overflow = end > 6 ? "auto" : "hidden";
+    }
+
+    function bindSelect(control, menu) {
+      invokeOnAction(control, () => {
+        const willOpen = !control.classList.contains("open");
+        closeSelects();
+        if (willOpen && menu._pageSize) {
+          renderSelectPage(control, menu, true);
+          const selected = (menu._allOptions || []).find((option) => option.value === (control.dataset.value || ""));
+          if (selected) {
+            for (const child of menu.children) {
+              child.classList.toggle("selected", child.dataset.value === selected.value);
+            }
+          }
+        }
+        control.classList.toggle("open", willOpen);
+        control.setAttribute("aria-expanded", willOpen ? "true" : "false");
+        scheduleSelectResize();
+      });
+      control.addEventListener("keydown", (event) => {
+        const options = [...menu.children];
+        if (!options.length) return;
+        const selectedIndex = Math.max(0, options.findIndex((item) => item.classList.contains("selected")));
+        if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+          event.preventDefault();
+          const nextIndex = event.key === "ArrowDown"
+            ? Math.min(options.length - 1, selectedIndex + 1)
+            : Math.max(0, selectedIndex - 1);
+          options[nextIndex].click();
+        } else if (event.key === "Escape") {
+          closeSelects();
+          scheduleSelectResize();
+        }
+      });
+      menu.addEventListener("scroll", () => {
+        if (!menu._pageSize) return;
+        const all = menu._allOptions || [];
+        if ((menu._renderedCount || 0) >= all.length) return;
+        if (menu.scrollTop + menu.clientHeight >= menu.scrollHeight - 24) {
+          renderSelectPage(control, menu, false);
+        }
+      });
+    }
+
+    function readFallbackConfig(config) {
+      const enabledModels = asArray(config.models)
+        .filter((model) => model && model.enabled !== false)
+        .map((model) => ({
+          id: model.id,
+          label: model.label || model.id,
+          provider: model.provider || "provider",
+          supportsStreaming: model.supportsStreaming !== false,
+          enabled: true
+        }))
+        .filter((model) => model.id);
+      return enabledModels.length ? enabledModels : fallbackModels;
     }
 
     async function loadConfig() {
       try {
-        config = { ...config, ...(await window.moliDesktop.getConfig() || {}) };
+        const config = bridge && typeof bridge.getConfig === "function" ? await bridge.getConfig() : null;
+        state.config = config || {};
       } catch {
+        state.config = {};
       }
+      state.mode = state.config.mode || "provider-direct";
+      state.selectedProjectId = (state.config.aichat && state.config.aichat.defaultProjectId) || "";
     }
 
     async function loadProjects() {
       try {
-        const projects = await window.moliDesktop.llm.getProjects();
-        const items = projects.map((project) => ({
-          value: project.id,
-          label: project.name || project.id,
-          title: `${project.projectType || "CHAT"} / ${project.memoryMode || "ISOLATED"}`
-        }));
-        setDropdownOptions(projectDropdown, items, config.aichat?.defaultProjectId || "", "No project");
+        if (!llm || typeof llm.getProjects !== "function") throw new Error("AiChat bridge unavailable.");
+        const result = await llm.getProjects();
+        const packed = result && !Array.isArray(result);
+        const status = String((packed ? (result.status || result.Status) : "ready") || "ready").toLowerCase();
+        const projects = packed ? asArray(result.projects || result.Projects) : asArray(result);
+        const message = packed ? (result.message || result.Message || "") : "";
+        state.projects = projects;
+        state.projectStatus = status;
+
+        if (status === "not-configured") {
+          setSelectOptions(els.projectSelect, els.projectMenu, [], "Not configured", "", { autoSelectFirst: false });
+          els.projectSelect.title = "AiChat is not configured.";
+          state.selectedProjectId = "";
+          return;
+        }
+
+        if (status === "not-connected") {
+          setSelectOptions(els.projectSelect, els.projectMenu, [], "Not connected", "", { autoSelectFirst: false });
+          els.projectSelect.title = message || "AiChat is not connected.";
+          state.selectedProjectId = "";
+          return;
+        }
+
+        const selectedId = projects.some((item) => (item.id || item.Id) === state.selectedProjectId)
+          ? state.selectedProjectId
+          : "";
+        setSelectOptions(
+          els.projectSelect,
+          els.projectMenu,
+          projects,
+          projects.length ? "Project" : "No project",
+          selectedId,
+          { autoSelectFirst: false }
+        );
+        state.selectedProjectId = getSelectValue(els.projectSelect);
       } catch (error) {
-        setDropdownFallback(projectDropdown, "Project error", error?.message || "AiChat projects could not be loaded");
+        state.projects = [];
+        state.projectStatus = "not-connected";
+        setSelectOptions(els.projectSelect, els.projectMenu, [], "Not connected", "", { autoSelectFirst: false });
+        els.projectSelect.title = getErrorMessage(error, "Project list unavailable.");
+        state.selectedProjectId = "";
       }
     }
 
     async function loadModels() {
       try {
-        const models = await window.moliDesktop.llm.getModels();
-        const items = models.map((model) => ({
-          value: model.id,
-          label: model.label || model.id,
-          title: `${model.provider} / ${model.id}`
-        }));
-        setDropdownOptions(modelDropdown, items, config.defaultModel || "", "No models");
+        if (!llm || typeof llm.getModels !== "function") throw new Error("LLM bridge unavailable.");
+        state.models = asArray(await llm.getModels()).filter((model) => model.enabled !== false && (model.id || model.Id));
       } catch {
-        setDropdownFallback(modelDropdown, "Model error");
+        state.models = readFallbackConfig(state.config);
+      }
+
+      if (!state.models.length) state.models = fallbackModels;
+      state.selectedModelId = state.config.defaultModel || state.selectedModelId || "";
+      setSelectOptions(els.modelSelect, els.modelMenu, state.models, "Model", state.selectedModelId, { pageSize: MODEL_PAGE_SIZE });
+      state.selectedModelId = getSelectValue(els.modelSelect);
+    }
+
+    function applyMemoryAvailability() {
+      const available = state.memoryCapabilities.canUseMemory ||
+        state.memoryCapabilities.canViewMemory ||
+        state.memoryCapabilities.canManageMemory;
+      setDisabled(els.memoryButton, !available);
+      els.memoryButton.title = available ? "Memories" : "Memory requires a configured AiChat account";
+      if (!available) {
+        els.memoryPanel.classList.remove("open");
+        els.memoryButton.classList.remove("active");
       }
     }
 
     async function loadMemoryCapabilities() {
-      try {
-        memoryCapabilities = await window.moliDesktop.llm.getMemoryCapabilities();
-      } catch {
-        memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
-      }
-
-      const memoryEnabled = mode() === "provider-direct" && config.aichat?.memory?.enabledInProviderDirect;
-      memoryToggle.disabled = !memoryEnabled || !memoryCapabilities.canViewMemory;
-      memoryInput.disabled = !memoryCapabilities.canManageMemory;
-      saveMemory.disabled = !memoryCapabilities.canManageMemory;
-      refreshMemory.disabled = !memoryCapabilities.canViewMemory;
-    }
-
-    async function recallMemory(content) {
-      if (mode() !== "provider-direct" || !config.aichat?.memory?.enabledInProviderDirect || !memoryCapabilities.canUseMemory) {
-        return [];
-      }
-
-      const projectId = selectedProjectId();
-      try {
-        const result = await window.moliDesktop.llm.recallMemories({
-          query: content,
-          scope: config.aichat.memory.defaultScope || "PROJECT",
-          projectId,
-          limit: config.aichat.memory.recallLimit || 8
-        });
-        return Array.isArray(result?.items) ? result.items : [];
-      } catch {
-        return [];
-      }
-    }
-
-    async function submitPrompt() {
-      const content = promptInput.value.trim();
-      const modelId = modelSelect.value;
-      if (!content || !modelId || activeRequestId) return;
-
-      currentText = "";
-      text.className = "";
-      text.textContent = "";
-      openOutput();
-      setBusy(true);
-
-      try {
-        const memories = await recallMemory(content);
-        const messages = [];
-        if (memories.length > 0) {
-          const memoryText = memories.map((item) => `- ${item.content || ""}`).filter(Boolean).join("\n");
-          if (memoryText) {
-            messages.push({ role: "system", content: `Relevant memory:\n${memoryText}` });
-          }
-        }
-        messages.push({ role: "user", content });
-
-        const response = await window.moliDesktop.llm.streamChat({
-          mode: mode(),
-          projectId: selectedProjectId(),
-          modelId,
-          messages,
-          options: {}
-        });
-        activeRequestId = response.requestId;
-      } catch (error) {
-        activeRequestId = null;
-        setBusy(false);
-        setError(error?.message || "LLM request could not be started.");
-      }
-    }
-
-    async function refreshMemories() {
-      if (!memoryCapabilities.canViewMemory) return;
-      const projectId = selectedProjectId();
-      memoryList.textContent = "Loading...";
-      try {
-        const scope = config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT";
-        const result = await window.moliDesktop.llm.getMemories({ scope, projectId });
-        const items = Array.isArray(result) ? result : Array.isArray(result?.items) ? result.items : [];
-        renderMemories(items);
-      } catch (error) {
-        memoryList.textContent = error?.message || "Memory unavailable.";
-      }
-    }
-
-    function renderMemories(items) {
-      memoryList.innerHTML = "";
-      if (!items.length) {
-        memoryList.textContent = "No memory";
+      if (state.mode === "aichat-api") {
+        state.memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
+        applyMemoryAvailability();
+        renderMemories("AiChat mode uses service-side memory.");
         return;
       }
 
-      for (const item of items) {
-        const row = document.createElement("div");
-        row.className = "memory-row";
-        const content = document.createElement("div");
-        content.className = "memory-content";
-        content.textContent = item.content || item.id || "";
-        row.appendChild(content);
-        const remove = document.createElement("button");
-        remove.textContent = "x";
-        remove.title = "Delete memory";
-        remove.disabled = !memoryCapabilities.canManageMemory;
-        remove.addEventListener("click", async () => {
-          if (!item.id) return;
-          await window.moliDesktop.llm.deleteMemory(item.id);
-          refreshMemories();
-        });
-        row.appendChild(remove);
-        memoryList.appendChild(row);
+      try {
+        if (!llm || typeof llm.getMemoryCapabilities !== "function") throw new Error("Memory bridge unavailable.");
+        const capabilities = await llm.getMemoryCapabilities();
+        state.memoryCapabilities = {
+          canUseMemory: Boolean(capabilities.canUseMemory ?? capabilities.CanUseMemory),
+          canViewMemory: Boolean(capabilities.canViewMemory ?? capabilities.CanViewMemory),
+          canManageMemory: Boolean(capabilities.canManageMemory ?? capabilities.CanManageMemory)
+        };
+      } catch {
+        state.memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
+      }
+      applyMemoryAvailability();
+    }
+
+    async function loadMemories() {
+      if (!state.memoryCapabilities.canViewMemory) {
+        renderMemories("Memory unavailable");
+        return;
+      }
+
+      try {
+        const scope = state.selectedProjectId ? "PROJECT" : "GLOBAL";
+        const result = await llm.getMemories({ scope, projectId: state.selectedProjectId || undefined });
+        const items = asArray(result.items || result.memories || result.data || result);
+        state.memories = items;
+        renderMemories(items.length ? "" : "No memories");
+      } catch (error) {
+        renderMemories(getErrorMessage(error, "Memory unavailable"));
       }
     }
 
-    promptInput.addEventListener("keydown", (event) => {
-      if (event.key === "Enter" && !event.shiftKey) {
-        event.preventDefault();
-        submitPrompt();
+    function getMemoryContent(item) {
+      return item.content || item.Content || item.text || item.Text || item.summary || item.Summary || "";
+    }
+
+    function getMemoryId(item) {
+      return item.id || item.Id || item.memoryId || item.MemoryId || "";
+    }
+
+    function renderMemories(status) {
+      els.memoryList.textContent = "";
+      for (const item of state.memories.slice(0, 12)) {
+        const row = document.createElement("div");
+        row.className = "memory-item";
+        const text = document.createElement("div");
+        text.className = "memory-text";
+        text.textContent = getMemoryContent(item) || "Memory";
+        row.appendChild(text);
+
+        if (state.memoryCapabilities.canManageMemory) {
+          const button = document.createElement("div");
+          button.className = "icon-action";
+          button.role = "button";
+          button.tabIndex = 0;
+          button.title = "Delete memory";
+          button.setAttribute("aria-label", "Delete memory");
+          button.textContent = "-";
+          invokeOnAction(button, () => deleteMemory(getMemoryId(item)));
+          row.appendChild(button);
+        }
+
+        els.memoryList.appendChild(row);
       }
 
-      if (event.key === "Escape") {
-        output.classList.remove("open");
-        memoryPanel.classList.remove("open");
-        requestResize();
+      if (!state.memories.length) {
+        els.memoryList.textContent = status || "";
       }
-    });
+      els.memoryStatus.textContent = status || "";
+      setDisabled(els.memoryInput, !state.memoryCapabilities.canManageMemory);
+      setDisabled(els.addMemoryButton, !state.memoryCapabilities.canManageMemory);
+      setDisabled(els.recallButton, !state.memoryCapabilities.canUseMemory);
+    }
 
-    promptInput.addEventListener("input", () => {
-      promptInput.style.height = "0";
-      promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`;
-    });
-
-    projectSelect.addEventListener("change", () => {
-      if (memoryPanel.classList.contains("open")) {
-        refreshMemories();
+    async function createMemory(content) {
+      if (!content.trim() || !state.memoryCapabilities.canManageMemory) return;
+      try {
+        const scope = state.selectedProjectId ? "PROJECT" : "GLOBAL";
+        await llm.createMemory({ scope, projectId: state.selectedProjectId || undefined, content: content.trim() });
+        setText(els.memoryInput, "");
+        await loadMemories();
+      } catch (error) {
+        renderMemories(getErrorMessage(error, "Could not create memory"));
       }
-    });
+    }
 
-    memoryToggle.addEventListener("click", () => {
-      memoryPanel.classList.toggle("open");
-      if (memoryPanel.classList.contains("open")) {
-        refreshMemories();
+    async function deleteMemory(memoryId) {
+      if (!memoryId) return;
+      try {
+        await llm.deleteMemory(memoryId);
+        await loadMemories();
+      } catch (error) {
+        renderMemories(getErrorMessage(error, "Could not delete memory"));
       }
-      requestResize();
-    });
+    }
 
-    refreshMemory.addEventListener("click", refreshMemories);
-    saveMemory.addEventListener("click", async () => {
-      const content = memoryInput.value.trim();
-      if (!content || !memoryCapabilities.canManageMemory) return;
-      await window.moliDesktop.llm.createMemory({
-        scope: config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT",
-        projectId: selectedProjectId(),
-        content
+    async function recallMemoryContext(prompt) {
+      if (state.mode === "aichat-api" || !state.memoryCapabilities.canUseMemory || !prompt.trim()) return "";
+      try {
+        const memoryConfig = state.config.aichat && state.config.aichat.memory ? state.config.aichat.memory : {};
+        const result = await llm.recallMemories({
+          query: prompt,
+          scope: memoryConfig.defaultScope || "ALL",
+          projectId: state.selectedProjectId || undefined,
+          limit: memoryConfig.recallLimit || 8
+        });
+        const items = asArray(result.items || result.memories || result.data || result);
+        const contents = items.map(getMemoryContent).filter(Boolean).slice(0, 8);
+        if (!contents.length) return "";
+        return "Relevant memory:\n" + contents.map((item) => "- " + item).join("\n");
+      } catch {
+        return "";
+      }
+    }
+
+    async function mockStream(prompt) {
+      state.requestId = "mock-" + Date.now();
+      const text = "This is a local render preview. In Moli.Desktop, this prompt is sent through the host LLM bridge with the selected project and model.\n\nPrompt: " + prompt;
+      for (const chunk of text.match(/.{1,12}/g) || []) {
+        if (!state.busy) return;
+        appendOutput(chunk);
+        await delay(35);
+      }
+      finishRequest();
+    }
+
+    async function submitPrompt(promptOverride) {
+      const prompt = (promptOverride || getText(els.promptInput) || "").trim();
+      if (!prompt || state.busy) return;
+      if (!state.selectedModelId) {
+        showError("No model is available.");
+        return;
+      }
+
+      state.busy = true;
+      state.output = "";
+      state.lastPrompt = prompt;
+      state.requestId = "";
+      setStatus("loading", "Generating");
+      setOutput("", { streaming: true });
+
+      const memoryContext = await recallMemoryContext(prompt);
+      const messages = [];
+      if (memoryContext) messages.push({ role: "system", content: memoryContext });
+      messages.push({ role: "user", content: prompt });
+
+      if (!llm || typeof llm.streamChat !== "function") {
+        await mockStream(prompt);
+        return;
+      }
+
+      try {
+        const result = await llm.streamChat({
+          mode: state.mode,
+          projectId: state.selectedProjectId || undefined,
+          modelId: state.selectedModelId,
+          messages,
+          options: state.config.request || undefined
+        });
+        state.requestId = result.requestId || result.RequestId || "";
+      } catch (error) {
+        showError(getErrorMessage(error, "Request failed."));
+        finishRequest(true);
+      }
+    }
+
+    function finishRequest(keepError) {
+      state.busy = false;
+      setStatus(keepError ? "error" : "", keepError ? "Error" : "Idle");
+      setOutput(state.output, { error: Boolean(keepError) });
+    }
+
+    function showError(message) {
+      state.output = message || "Request failed.";
+      setStatus("error", "Error");
+      setOutput(state.output, { error: true });
+      requestHostResize();
+    }
+
+    function handleDelta(detail) {
+      const event = normalizeEvent(detail);
+      if (event.requestId && state.requestId && event.requestId !== state.requestId) return;
+      appendOutput(event.delta);
+    }
+
+    function handleCompleted(detail) {
+      const event = normalizeEvent(detail);
+      if (event.requestId && state.requestId && event.requestId !== state.requestId) return;
+      finishRequest(false);
+    }
+
+    function handleError(detail) {
+      const event = normalizeEvent(detail);
+      if (event.requestId && state.requestId && event.requestId !== state.requestId) return;
+      showError(event.message || event.code || "Request failed.");
+      finishRequest(true);
+    }
+
+    function bindBridgeEvents() {
+      if (!llm) return;
+      if (typeof llm.onDelta === "function") llm.onDelta(handleDelta);
+      if (typeof llm.onCompleted === "function") llm.onCompleted(handleCompleted);
+      if (typeof llm.onError === "function") llm.onError(handleError);
+    }
+
+    function bindUi() {
+      bindSelect(els.projectSelect, els.projectMenu);
+      bindSelect(els.modelSelect, els.modelMenu);
+      bindOutputScrolling();
+
+      window.addEventListener("moli:interactable-changed", (event) => {
+        const detail = event.detail || {};
+        const enabled = Boolean(detail.enabled ?? detail.Enabled);
+        if (enabled) {
+          els.promptInput.focus({ preventScroll: true });
+        }
       });
-      memoryInput.value = "";
-      refreshMemories();
-    });
 
-    collapse.addEventListener("click", () => {
-      output.classList.remove("open");
-      requestResize();
-    });
-    copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {}));
-    document.addEventListener("click", (event) => {
-      if (!projectCombo.contains(event.target) && !modelCombo.contains(event.target)) {
-        closeDropdowns();
-      }
-    });
+      els.promptInput.addEventListener("input", resizeTextarea);
+      els.promptInput.addEventListener("keydown", (event) => {
+        if (event.key === "Enter" && !event.shiftKey) {
+          event.preventDefault();
+          submitPrompt();
+        } else if (event.key === "Escape") {
+          if (els.outputPanel.classList.contains("open")) collapseOutput();
+          else els.promptInput.blur();
+        }
+      });
 
-    window.addEventListener("DOMContentLoaded", async () => {
-      setupDropdown(projectDropdown);
-      setupDropdown(modelDropdown);
+      els.memoryInput.addEventListener("keydown", (event) => {
+        if (event.key === "Enter") {
+          event.preventDefault();
+          createMemory(getText(els.memoryInput));
+        }
+      });
+
+      window.addEventListener("keydown", (event) => {
+        if (event.key === "Escape" && els.outputPanel.classList.contains("open")) {
+          collapseOutput();
+        }
+      });
+
+      els.projectSelect.addEventListener("change", async () => {
+        state.selectedProjectId = getSelectValue(els.projectSelect);
+        if (els.memoryPanel.classList.contains("open")) await loadMemories();
+      });
+
+      els.modelSelect.addEventListener("change", () => {
+        state.selectedModelId = getSelectValue(els.modelSelect);
+      });
+
+      invokeOnAction(els.memoryButton, async () => {
+        const isOpen = !els.memoryPanel.classList.contains("open");
+        els.memoryPanel.classList.toggle("open", isOpen);
+        els.memoryButton.classList.toggle("active", isOpen);
+        if (isOpen) await loadMemories();
+        requestPaletteResize();
+      });
+
+      invokeOnAction(els.addMemoryButton, () => createMemory(getText(els.memoryInput)));
+
+      invokeOnAction(els.recallButton, async () => {
+        const context = await recallMemoryContext(getText(els.promptInput) || state.lastPrompt);
+        renderMemories(context ? "Memory recalled for next request" : "No relevant memory");
+      });
+
+      invokeOnAction(els.copyButton, async () => {
+        if (!state.output) return;
+        try {
+          await navigator.clipboard.writeText(state.output);
+        } catch {
+          const range = document.createRange();
+          range.selectNodeContents(els.outputText);
+          const selection = window.getSelection();
+          selection.removeAllRanges();
+          selection.addRange(range);
+        }
+      });
+
+      invokeOnAction(els.retryButton, () => submitPrompt(state.lastPrompt));
+      invokeOnAction(els.collapseButton, collapseOutput);
+
+      document.addEventListener("click", (event) => {
+        if (!els.projectSelect.parentElement.contains(event.target) && !els.modelSelect.parentElement.contains(event.target)) {
+          closeSelects();
+          scheduleSelectResize();
+        }
+      });
+    }
+
+    async function init() {
+      bindUi();
+      bindBridgeEvents();
+      updatePanelLimits();
+      setStatus("", "Idle");
+      resizeTextarea();
       await loadConfig();
       await Promise.all([loadProjects(), loadModels(), loadMemoryCapabilities()]);
-    });
+      renderMemories("");
+      requestHostResize(72);
+      els.promptInput.focus({ preventScroll: true });
+    }
 
-    window.moliDesktop?.llm?.onDelta?.((event) => {
-      if (event.requestId !== activeRequestId) return;
-      currentText += event.delta || "";
-      text.textContent = currentText;
-      output.scrollTop = output.scrollHeight;
-    });
-    window.moliDesktop?.llm?.onCompleted?.((event) => {
-      if (event.requestId !== activeRequestId) return;
-      activeRequestId = null;
-      setBusy(false);
-    });
-    window.moliDesktop?.llm?.onError?.((event) => {
-      if (event.requestId !== activeRequestId) return;
-      activeRequestId = null;
-      setBusy(false);
-      setError(event.message || "LLM request failed.");
-    });
+    window.addEventListener("resize", updatePanelLimits);
+
+    init();
   </script>
 </body>
+
 </html>

--
Gitblit v1.9.1