'use strict'; window.AssistantModelPicker = { mount(root, { api, isActive, getConversation, onSelect, onError, onChange }) { const host = root.querySelector('.aw-compose-tools'), button = document.createElement('button'); button.type = 'button'; button.id = 'assistant-model-picker'; button.className = 'btn btn-sm aw-model-picker'; button.setAttribute('aria-haspopup', 'listbox'); button.textContent = '请选择模型'; host.querySelector('#assistant-commands').after(button); const popup = document.createElement('div'); popup.className = 'aw-model-popup'; popup.hidden = true; host.append(popup); let data = { providers: [], defaultSelection: null }, conversation = null, disposed = false, generation = 0, loaded = false, lastRefreshAt = 0, refreshPromise = null; const alive = () => !disposed && isActive(); function available() { return data.providers .filter((p) => p.enabled !== false && p.hasApiKey !== false) .flatMap((p) => p.models.map((m) => ({ provider: p, model: m }))); } function selected() { return conversation?.modelSelection || data.defaultSelection; } function current() { const choice = selected(); return available().find( (row) => row.provider.id === choice?.providerId && row.model.id === choice?.modelId, ); } function capability(m) { return m?.inputModalities?.includes('image') ? '视觉' : ''; } function label() { const row = current(); const text = row ? row.provider.name + ' / ' + (row.model.name || row.model.id) : '请选择模型'; button.textContent = text + (row && capability(row.model) ? ' · 视觉' : ''); button.title = row ? capability(row.model) ? '支持图像输入;PNG、JPEG 按视觉内容发送,PDF 提取文字。' : '文本附件和 PDF 文字可用;图片请选择视觉模型。' : ''; button.setAttribute('aria-label', '选择模型:' + button.textContent); button.disabled = !!conversation?.archived || !!conversation?.deletedAt; const header = root.querySelector('.aw-model'); if (header) header.textContent = row ? row.model.name || row.model.id : '模型未选择'; } function close() { generation++; popup.hidden = true; popup.replaceChildren(); button.setAttribute('aria-expanded', 'false'); } function showFailure(error, at) { if (!alive() || generation !== at) return; popup.hidden = false; button.setAttribute('aria-expanded', 'true'); popup.innerHTML = ''; popup.querySelector('[data-model-retry]').onclick = () => void open(); onError(error); } async function refresh({ force = false } = {}) { const now = Date.now(); if (!force && loaded && now - lastRefreshAt < 30000) return data; if (refreshPromise && !force) return refreshPromise; const work = (async () => { const next = await api('/assistant/providers'); if (!alive()) return; data = next; loaded = true; lastRefreshAt = Date.now(); label(); onChange?.(); return next; })(); refreshPromise = work; try { return await work; } finally { if (refreshPromise === work) refreshPromise = null; } } async function open() { const at = ++generation; try { await refresh(); if (!alive() || generation !== at) return; popup.hidden = false; button.setAttribute('aria-expanded', 'true'); popup.innerHTML = '
'; const search = popup.querySelector('input'), options = popup.querySelector('[role=listbox]'); let index = 0, rows = []; function draw() { const query = search.value.trim().toLowerCase(); rows = available().filter((row) => (row.provider.name + ' ' + row.model.name + ' ' + row.model.id) .toLowerCase() .includes(query), ); options.replaceChildren(); let previous = null; for (const [i, row] of rows.entries()) { if (previous !== row.provider.id) { const heading = document.createElement('div'); heading.className = 'small text-secondary px-2 py-1'; heading.textContent = row.provider.name; options.append(heading); previous = row.provider.id; } const item = document.createElement('button'); item.type = 'button'; item.className = 'aw-model-option'; item.role = 'option'; item.setAttribute('aria-label', row.model.name || row.model.id); item.setAttribute('aria-selected', String(i === index)); item.textContent = (row.model.name || row.model.id) + (capability(row.model) ? ' · 视觉' : '') + (selected()?.providerId === row.provider.id && selected()?.modelId === row.model.id ? ' ✓' : ''); item.title = row.model.id; item.onclick = () => choose(row); options.append(item); } if (!rows.length) { options.innerHTML = '

暂无匹配的可用模型。

前往助手设置'; } } async function choose(row) { if (!alive() || generation !== at) return; const buttons = [...options.querySelectorAll('button')]; buttons.forEach((b) => (b.disabled = true)); try { await onSelect({ providerId: row.provider.id, modelId: row.model.id }); if (alive() && generation === at) { conversation = getConversation(); label(); close(); button.focus(); } } catch (error) { if (alive() && generation === at) { onError(error); buttons.forEach((b) => (b.disabled = false)); } } } search.oninput = () => { index = 0; draw(); }; search.onkeydown = (event) => { if (event.isComposing) return; if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); button.focus(); } else if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); index = (index + (event.key === 'ArrowDown' ? 1 : -1) + Math.max(1, rows.length)) % Math.max(1, rows.length); draw(); } else if (['Enter', 'Tab'].includes(event.key) && !event.shiftKey && rows[index]) { event.preventDefault(); void choose(rows[index]); } }; draw(); search.focus(); } catch (error) { showFailure(error, at); } } button.onclick = () => { if (popup.hidden) void open(); else close(); }; return { refresh, open, close, failure: (error) => showFailure(error, generation), get usable() { return !!current(); }, get supportsVision() { return current()?.model.inputModalities?.includes('image') === true; }, update(c) { if (conversation?.id !== c?.id) close(); conversation = c; label(); }, dispose() { disposed = true; close(); button.remove(); popup.remove(); }, }; }, };