基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-05 4df6165fa93c7caeea86385312415e312de4d11f
samples/plugins/sample.llm-command-palette/index.html
@@ -34,21 +34,22 @@
    }
    .bar,
    .output {
    .output,
    .memory {
      width: 100%;
      border: 1px solid rgba(255, 255, 255, 0.16);
      background: rgba(30, 28, 27, 0.74);
      box-shadow: 0 18px 42px rgba(0, 0, 0, 0.24);
      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: 24px minmax(0, 1fr) 128px;
      grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px);
      align-items: center;
      gap: 14px;
      min-height: 56px;
      padding: 0 18px;
      padding: 0 20px;
      border-radius: 20px;
    }
@@ -89,19 +90,113 @@
      color: rgba(255, 255, 255, 0.46);
    }
    select {
    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%;
      min-width: 0;
    }
    .combo-input {
      display: none;
    }
    .combo-trigger {
      width: 100%;
      height: 34px;
      border: 0;
      outline: none;
      color: rgba(255, 255, 255, 0.82);
      background: rgba(255, 255, 255, 0.08);
      border-radius: 8px;
      padding: 0 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;
    }
    .output {
    .combo-trigger::after {
      content: "";
      position: absolute;
      right: 11px;
      top: 13px;
      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);
    }
    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;
    }
    .combo-menu {
      position: absolute;
      left: 0;
      right: 0;
      top: calc(100% + 6px);
      z-index: 10;
      display: none;
      max-height: 184px;
      overflow-y: auto;
      padding: 6px;
      border: 1px solid rgba(255, 255, 255, 0.13);
      border-radius: 10px;
      background: rgba(28, 26, 25, 0.92);
      box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26);
      backdrop-filter: blur(16px);
    }
    .combo.open .combo-menu {
      display: block;
    }
    .combo-option {
      min-height: 36px;
      display: flex;
      align-items: center;
      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;
      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;
@@ -113,15 +208,42 @@
      white-space: pre-wrap;
    }
    .output.open {
    .output.open,
    .memory.open {
      display: block;
      animation: panelIn 160ms ease-out;
    }
    .actions {
    @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 {
@@ -132,6 +254,13 @@
      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 {
      cursor: not-allowed;
      opacity: 0.52;
    }
    .error {
@@ -142,9 +271,19 @@
<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>
      <div id="mark" class="mark" aria-hidden="true">*</div>
      <textarea id="prompt" rows="1" placeholder="What can I help you with today?"></textarea>
      <select id="model" title="Model"></select>
      <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>
    </section>
    <section id="output" class="output" aria-live="polite">
      <div id="text"></div>
@@ -153,18 +292,73 @@
        <button id="collapse" title="Collapse">-</button>
      </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>
  <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");
    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: () => () => {}
        }
      };
    }
    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);
@@ -173,7 +367,18 @@
    function openOutput() {
      output.classList.add("open");
      window.moliDesktop?.requestResize?.({ width: document.body.scrollWidth, height: Math.min(window.innerHeight, document.body.scrollHeight) }).catch(() => {});
      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) {
@@ -183,26 +388,138 @@
      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 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 setDropdownOptions(dropdown, items, preferredValue, fallbackLabel) {
      dropdown.menu.innerHTML = "";
      if (!items.length) {
        setDropdownFallback(dropdown, fallbackLabel);
        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);
    }
    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);
      }
      if (notify) {
        dropdown.input.dispatchEvent(new Event("change"));
      }
    }
    async function loadConfig() {
      try {
        config = { ...config, ...(await window.moliDesktop.getConfig() || {}) };
      } catch {
      }
    }
    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");
      } catch (error) {
        setDropdownFallback(projectDropdown, "Project error", error?.message || "AiChat projects could not be loaded");
      }
    }
    async function loadModels() {
      try {
        const models = await window.moliDesktop.llm.getModels();
        modelSelect.innerHTML = "";
        for (const model of models) {
          const option = document.createElement("option");
          option.value = model.id;
          option.textContent = model.label || model.id;
          option.title = `${model.provider} / ${model.id}`;
          modelSelect.appendChild(option);
        }
        if (models.length === 0) {
          const option = document.createElement("option");
          option.textContent = "No models";
          option.value = "";
          modelSelect.appendChild(option);
        }
        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");
      } catch {
        modelSelect.innerHTML = "<option value=\"\">No models</option>";
        setDropdownFallback(modelDropdown, "Model error");
      }
    }
    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 [];
      }
    }
@@ -218,9 +535,21 @@
      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: [{ role: "user", content }],
          messages,
          options: {}
        });
        activeRequestId = response.requestId;
@@ -228,6 +557,48 @@
        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";
        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);
      }
    }
@@ -239,6 +610,8 @@
      if (event.key === "Escape") {
        output.classList.remove("open");
        memoryPanel.classList.remove("open");
        requestResize();
      }
    });
@@ -247,10 +620,51 @@
      promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`;
    });
    collapse.addEventListener("click", () => output.classList.remove("open"));
    copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {}));
    projectSelect.addEventListener("change", () => {
      if (memoryPanel.classList.contains("open")) {
        refreshMemories();
      }
    });
    window.addEventListener("DOMContentLoaded", loadModels);
    memoryToggle.addEventListener("click", () => {
      memoryPanel.classList.toggle("open");
      if (memoryPanel.classList.contains("open")) {
        refreshMemories();
      }
      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
      });
      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();
      }
    });
    window.addEventListener("DOMContentLoaded", async () => {
      setupDropdown(projectDropdown);
      setupDropdown(modelDropdown);
      await loadConfig();
      await Promise.all([loadProjects(), loadModels(), loadMemoryCapabilities()]);
    });
    window.moliDesktop?.llm?.onDelta?.((event) => {
      if (event.requestId !== activeRequestId) return;
      currentText += event.delta || "";