From 91c5597e379e3c12c4ae70e7785a7625b130d7a9 Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 25 Nov 2026 10:47:32 +0800 Subject: [PATCH] [feat] canvas: keep one compact row per model in the picker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A service that returns six models drew six blocks of switches: each selected row dumped its capability card and its availability check into the list, so the model names — the only thing the list is for — were buried. Selecting one model pushed the next one off the screen. Every row is now one line: checkbox, name, test button, and a disclosure control that opens that model's service capabilities and availability check for the row being edited. Nothing was removed from the details, only defaulted closed, and each row keeps its own open state. The fetch status moved from a separate status block into the heading, and the availability and capability cards gained a compact form that drops their placeholder line instead of printing "Not checked" on every row. Discovery now selects every model it returns for a new service, which is what the batch button was for: one API key normally covers the whole catalog. An edited selection is never replaced by a later refresh, and a list above the enable limit stays manual instead of becoming unsavable. The search box and the bulk row are gone with it. That is the part I would like reviewed rather than assumed: with discovery selecting everything the bulk control only repeated the checkboxes, and the list is short in practice, but a catalog of hundreds of models would now need the search box back. Each is a filterbar-sized addition; say the word and I will restore them. Refs #477. --- docs/guides/model-availability.md | 4 +- scripts/run-browser-suite.mjs | 1 + src/canvas/DraftAvailabilityCheck.tsx | 3 + src/canvas/ModelAvailabilityCard.tsx | 16 +- src/canvas/ModelCapabilityCard.tsx | 160 ++++++++------ src/canvas/ModelPicker.tsx | 135 +++++------- src/canvas/ModelServiceForm.tsx | 72 +++++-- src/canvas/model-settings.css | 178 ++++++++++------ src/i18n/messages/en-US/generation.ts | 18 +- src/i18n/messages/en-US/models.ts | 2 +- src/i18n/messages/zh-CN/generation.ts | 12 +- src/i18n/messages/zh-CN/models.ts | 2 +- tests/browser/capability_discovery.mjs | 34 ++- tests/browser/manifest.json | 8 + tests/browser/model_select_all.mjs | 277 +++++++++++++++++++++++++ tests/browser/provider_settings.mjs | 7 +- 16 files changed, 647 insertions(+), 282 deletions(-) create mode 100644 tests/browser/model_select_all.mjs diff --git a/docs/guides/model-availability.md b/docs/guides/model-availability.md index 46118d0df..ab1df6d4a 100644 --- a/docs/guides/model-availability.md +++ b/docs/guides/model-availability.md @@ -8,7 +8,7 @@ 模型接入可以读取服务的可选能力声明。自托管连接默认自动检查,其他连接默认关闭;服务级 `capabilityAutoCheck` 可以覆盖默认值。省略该字段会保留已有设置,旧配置无需转换。共享同一 `providerId` 的模型使用相同设置和查询缓存。独立服务及旧的独立配置保留自己的归属,相同 URL 和密钥不会合并它们。自动检查只查询能力接口,不生成内容、不唤醒模型。 -“检查服务能力”可以检查未保存的表单。草稿检查不会保存配置,也不会更新已保存模型的状态。显式刷新已保存模型可以检查关闭自动检查的服务。 +“检查服务能力”可以检查未保存的表单。草稿检查不会保存配置,也不会更新已保存模型的状态。显式刷新已保存模型可以检查关闭自动检查的服务。文本模型的行内不显示这项检查:每行的“测试”按钮会发送一条简短消息,已经能证明模型可用,该行只保留“服务能力”的文本与图片理解开关。 在“设置 → 模型接入”选择模型类别,展开服务卡片的“服务能力”,即可查看每种操作的状态和检查时间。编辑服务时,可在高级连接设置中调整“自动检查服务能力”。输入过程中不会查询;保存后在后台检查。生成按钮和助手会说明明确不可用的原因,并保留当前输入和选择。暂停观察到期后会解除该观察产生的禁用,提交时仍执行后端检查。 @@ -32,7 +32,7 @@ Example capability card showing operation states and declared input limits: Model connections can read an optional service capability declaration. Self-hosted connections check automatically by default; other connections require explicit enablement or a manual check. The optional service-level `capabilityAutoCheck` preference and query cache are shared by models with the same `providerId`. Independent providers and legacy standalone configuration IDs stay isolated even at the same URL with the same credential. Checks query declarations without inference or wake-up requests. -The unsaved form check uses an isolated draft identity. It saves neither configuration nor observations for saved connections. Explicit refresh can check selected saved connections even when automatic checks are disabled. +The unsaved form check uses an isolated draft identity. It saves neither configuration nor observations for saved connections. Explicit refresh can check selected saved connections even when automatic checks are disabled. Rows for text models do not show this check: their Test button sends a short message, which already proves the model answers, so the row keeps only the text and image-understanding switches under Service capabilities. In Settings → Model connections, select a category and expand Service capabilities on a connection card to see operation states and check times. Advanced connection settings contain Automatically check service capabilities. Typing does not query the service; saving starts a background check. Generation and assistant controls explain explicit unavailability while retaining inputs and selections. Pause observations expire locally; submission still runs the backend check. diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 9545f3f56..f60f293ed 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -33,6 +33,7 @@ const workflows = [ { name: "minimax h3", script: "tests/browser/minimax_h3.mjs" }, { name: "provider settings", script: "tests/browser/provider_settings.mjs" }, { name: "new model discovery", script: "tests/browser/new_model_discovery.mjs" }, + { name: "model select all", script: "tests/browser/model_select_all.mjs" }, { name: "Zhipu model settings feedback", script: "tests/browser/zhipu_provider.mjs" }, { name: "capability discovery", script: "tests/browser/capability_discovery.mjs" }, { name: "created node focus", script: "tests/browser/created_node_focus.mjs" }, diff --git a/src/canvas/DraftAvailabilityCheck.tsx b/src/canvas/DraftAvailabilityCheck.tsx index 6230c01fa..c859bee6a 100644 --- a/src/canvas/DraftAvailabilityCheck.tsx +++ b/src/canvas/DraftAvailabilityCheck.tsx @@ -12,10 +12,12 @@ export function DraftAvailabilityCheck({ connection, configId, modelId, + compact, }: { connection: ModelConfigInput; configId?: string; modelId: string; + compact?: boolean; }) { const signature = JSON.stringify([connection, configId, modelId]); const latest = useRef(signature); @@ -67,6 +69,7 @@ export function DraftAvailabilityCheck({ }; return ( void check()} diff --git a/src/canvas/ModelAvailabilityCard.tsx b/src/canvas/ModelAvailabilityCard.tsx index fbc311366..0d341624f 100644 --- a/src/canvas/ModelAvailabilityCard.tsx +++ b/src/canvas/ModelAvailabilityCard.tsx @@ -20,12 +20,15 @@ export function ModelAvailabilityCard({ checking = false, title, error, + compact = false, }: { value?: ModelAvailability | null; onRefresh?: () => void; checking?: boolean; title?: string; error?: string; + /** One line inside a model row: no card heading, chips instead of rows. */ + compact?: boolean; }) { const { t, locale } = useI18n(); const [tick, setTick] = useState(0); @@ -43,19 +46,26 @@ export function ModelAvailabilityCard({ const message = checking ? null : error || (notice ? availabilityReason(notice) : null); + // A row keeps the action but not the "not checked yet" placeholder: the + // button already says what it does, and the empty line only cost space. + const showMessage = !(compact && !error && notice === "not_checked"); const details = availabilityCardDetails(current?.operations ?? []); const commonSource = details.length > 0 && details.every((detail) => detail.source === details[0].source) ? details[0].source : null; + const messageNode = message && showMessage ? ( +

{message}

+ ) : null; return (
{title ?? t("availability.title")} + {compact && messageNode} {onRefresh && (
- {message &&

{message}

} + {!compact && messageNode} {current?.operations.length ? (
    {current.operations.map((item) => { diff --git a/src/canvas/ModelCapabilityCard.tsx b/src/canvas/ModelCapabilityCard.tsx index 41d66824c..71392b3da 100644 --- a/src/canvas/ModelCapabilityCard.tsx +++ b/src/canvas/ModelCapabilityCard.tsx @@ -23,6 +23,7 @@ export function ModelCapabilityCard({ disabled, onChange, onValidity, + compact = false, }: { modelId: string; connection: ModelConfigInput; @@ -30,6 +31,7 @@ export function ModelCapabilityCard({ saved?: ModelConfig; options: ModelOptions; disabled: boolean; + compact?: boolean; onChange: (patch: ModelOptions) => void; onValidity: (error: string) => void; }) { @@ -122,6 +124,92 @@ export function ModelCapabilityCard({ } }; if (connection.kind !== "agent" && !video) return null; + const agentInputs = connection.kind === "agent" && ( + <> +
    + + {t("models.service.capabilities")} + + + +
    + + ); + const officialFacts = official && ( +
    + + {t( + connection.protocol === "bigmodel_video" + ? "models.service.bigmodelVideoSummary" + : connection.protocol === "kling_video" + ? modelId === "kling-4.0-flash" + ? "models.service.klingFlashSummary" + : "models.service.klingSummary" + : "models.service.officialSummary", + )} + + {nativeCapabilities ? ( + <> + + {nativeCapabilities.outputs + .map((output) => output.resolution) + .join(" / ")} + + + {t("models.service.secondsRange", { + min: Math.min(...nativeDurations), + max: Math.max(...nativeDurations), + })} + + + ) : ( + !error && {t("models.service.loadingNative")} + )} + + {t( + connection.protocol === "bigmodel_video" + ? "models.service.bigmodelVideoReferences" + : connection.protocol === "kling_video" + ? "models.service.klingReferences" + : "models.service.officialReferences", + )} + +
    + ); + // Inside a model row the details stay on one line: the declared facts and + // the switches, without the card padding that used to open an empty block. + if (compact && (connection.kind === "agent" || official)) { + return ( +
    +
    + {agentInputs || officialFacts} + {error && ( +

    + {error} +

    + )} +
    +
    + ); + } return (
    {connection.kind === "agent" - ? t("models.service.inputCapabilities") + ? t("models.service.capabilities") : t("models.service.referenceOutput")}
    {connection.kind === "agent" ? ( - <> -
    - - -
    -

    - {t("models.service.imageInputNote")} -

    - + agentInputs ) : official ? ( -
    - - {t( - connection.protocol === "bigmodel_video" - ? "models.service.bigmodelVideoSummary" - : connection.protocol === "kling_video" - ? modelId === "kling-4.0-flash" - ? "models.service.klingFlashSummary" - : "models.service.klingSummary" - : "models.service.officialSummary", - )} - - {nativeCapabilities ? ( - <> - - {nativeCapabilities.outputs - .map((output) => output.resolution) - .join(" / ")} - - - {t("models.service.secondsRange", { - min: Math.min(...nativeDurations), - max: Math.max(...nativeDurations), - })} - - - ) : ( - !error && {t("models.service.loadingNative")} - )} - - {t( - connection.protocol === "bigmodel_video" - ? "models.service.bigmodelVideoReferences" - : connection.protocol === "kling_video" - ? "models.service.klingReferences" - : "models.service.officialReferences", - )} - -
    + officialFacts ) : ( <> {connection.protocol === "vllm_omni" && ( diff --git a/src/canvas/ModelPicker.tsx b/src/canvas/ModelPicker.tsx index eb5ded86e..36b96f061 100644 --- a/src/canvas/ModelPicker.tsx +++ b/src/canvas/ModelPicker.tsx @@ -41,20 +41,15 @@ export function ModelPicker({ }) { const t = useT(); const manualFieldId = useId(); - const [query, setQuery] = useState(""); - const [onlySelected, setOnlySelected] = useState(false); const [manualOpen, setManualOpen] = useState(false); + const [expanded, setExpanded] = useState([]); const [manualId, setManualId] = useState(""); const [manualModels, setManualModels] = useState([]); const [manualError, setManualError] = useState(""); + // Fetching already selects every model a new service returns, so the list + // needs no search box and no bulk selection row: the checkboxes are the + // selection, and a saved service keeps the subset the user chose. const ids = [...new Set([...available, ...manualModels, ...selected])]; - const visible = ids.filter( - (id) => - (!onlySelected || selected.includes(id)) && - id.toLowerCase().includes(query.toLowerCase().trim()), - ); - const allSelected = - visible.length > 0 && visible.every((id) => selected.includes(id)); const fetchLabel = loadsPreset ? "models.service.loadSupportedModels" : loaded ? "generation.picker.refresh" : "generation.picker.fetch"; @@ -63,7 +58,12 @@ export function ModelPicker({ status = t("generation.picker.fetching"); } else if (loaded && !error) { status = available.length - ? t(loadsPreset ? "generation.picker.loadedPreset" : "generation.picker.fetched", { count: available.length }) + ? t( + loadsPreset + ? "generation.picker.loadedPreset" + : "generation.picker.fetched", + { count: available.length }, + ) : t("generation.picker.noReturned"); } const addManual = () => { @@ -81,7 +81,6 @@ export function ModelPicker({ setManualId(""); setManualError(""); setManualOpen(false); - setQuery(""); }; return (
    -
    +

    {t("generation.picker.heading")}

    - - {t("generation.picker.selectedCount", { count: selected.length })} - +
    + {status && {status}} +
    -
    - {status &&

    {status}

    } -
    {error && (

    {error} @@ -174,48 +170,6 @@ export function ModelPicker({ )}

    )} - {ids.length > 4 && ( - <> -
    - - -
    -
    - - {t("generation.picker.count", { count: visible.length })} - - -
    - - )}
    {loading && !ids.length ? (
    @@ -232,35 +186,24 @@ export function ModelPicker({ : t("generation.picker.fetchHint")}

    - ) : !visible.length ? ( -
    - - {onlySelected && !selected.length - ? t("generation.picker.noSelection") - : t("generation.picker.noMatch")} - - -
    ) : ( - visible.map((id) => ( + ids.map((id) => { + const isSelected = selected.includes(id); + // Per-model details stay collapsed so every row keeps one line and + // the list shows as many models as possible. A saved row keeps its + // own open state while the user edits its capabilities. + const details = isSelected && renderDetails ? renderDetails : null; + const open = expanded.includes(id); + return (
    - )) + ); + }) )}
    {onTest && ids.length > 0 && ( diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 3d23f206a..621b4f1af 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -125,6 +125,9 @@ export function ModelServiceForm({ : [], ); const [modelIds, setModelIds] = useState(selectedModels); + // A fresh service starts with the preset's models selected. Once the user + // changes that selection, discovery must not silently replace it. + const [selectionEdited, setSelectionEdited] = useState(false); const [loaded, setLoaded] = useState(false); const [discovering, setDiscovering] = useState(false); const [discoveryError, setDiscoveryError] = useState(""); @@ -214,7 +217,21 @@ export function ModelServiceForm({ ? [...mediaPresetModels] : (await discoverModels(value, connection?.id)).models; setModelIds(models); - if (mediaPresetModels && !connection) setSelectedModels(models); + // One API key normally covers every model the service returns, so a new + // service starts with the discovered list selected, as presets already + // did. A saved service keeps the user's selection, an edited selection is + // never replaced, and a list above the enable limit stays manual instead + // of becoming unsavable. + if (mediaPresetModels) { + if (!connection) setSelectedModels(models); + } else if ( + !connection && + !selectionEdited && + models.length > 0 && + models.length <= 200 + ) { + setSelectedModels(models); + } setLoaded(true); setConnectionOpen(false); } catch (failure) { @@ -282,6 +299,7 @@ export function ModelServiceForm({ setConnection(undefined); const presetModels = [...(preset?.modelsByKind?.[kind] ?? [])]; setSelectedModels(presetModels); + setSelectionEdited(false); setModelIds(presetModels); setModelOptions({}); setModelErrors({}); @@ -326,6 +344,7 @@ export function ModelServiceForm({ : item.id === model.id), ); setSelectedModels(peers.map((item) => item.modelId)); + setSelectionEdited(false); setModelIds(peers.map((item) => item.modelId)); setLoaded(false); setDiscoveryError(""); @@ -540,31 +559,44 @@ export function ModelServiceForm({ onFetch={() => void loadModels()} onChange={(ids) => { setSelectedModels(ids); + setSelectionEdited(true); setError(""); }} onTest={kind === "agent" ? (id) => void test(id) : undefined} results={results} renderDetails={(id) => ( <> - - - setModelOptions((current) => ({ - ...current, - [id]: { ...current[id], ...patch }, - })) - } - onValidity={(message) => - setModelErrors((current) => ({ ...current, [id]: message })) - } - /> + {/* A text model is proved by the row's own test button, which + sends a real message, so the capability probe stays for the + kinds that have no test and whose operations and input rules + differ per service. */} + {kind !== "agent" && ( + + )} + + setModelOptions((current) => ({ + ...current, + [id]: { ...current[id], ...patch }, + })) + } + onValidity={(message) => + setModelErrors((current) => ({ ...current, [id]: message })) + } + /> )} /> diff --git a/src/canvas/model-settings.css b/src/canvas/model-settings.css index 0be4112d2..c4d394572 100644 --- a/src/canvas/model-settings.css +++ b/src/canvas/model-settings.css @@ -281,87 +281,42 @@ align-items: center; justify-content: space-between; gap: 10px; - margin-bottom: 14px; + margin-bottom: 12px; } -.cw-model-picker-heading > div:first-child { +.cw-model-picker-title { display: flex; - align-items: center; + align-items: baseline; gap: 10px; + min-width: 0; } .cw-model-picker-heading h4 { margin: 0; + flex: none; font-size: var(--settings-label-size); font-weight: 600; } -.cw-model-picker-heading span { +.cw-model-picker-status { + min-width: 0; +} +.cw-model-picker-status span { + display: block; + overflow: hidden; color: var(--settings-muted); font-size: var(--settings-caption-size); + text-overflow: ellipsis; + white-space: nowrap; } .cw-model-picker-actions { display: flex; + flex: none; align-items: center; gap: 3px; } -.cw-model-filterbar { - display: flex; - align-items: center; - gap: 10px; -} -.cw-model-search { - display: flex; - align-items: center; - gap: 8px; - flex: 1; - min-width: 0; - padding: 0 10px; - background: var(--settings-input); - border: 1px solid var(--settings-border); - border-radius: 8px; - color: var(--settings-muted); -} -.cw-settings-dialog .cw-model-settings .cw-model-search input { - width: 100%; - min-width: 0; - padding: 8px 0; - min-height: var(--settings-control-height); - border: 0; - background: transparent; - box-shadow: none; - font-size: var(--settings-control-size); -} -.cw-model-search:focus-within { - outline: 2px solid var(--cw-control-accent); - outline-offset: 1px; -} -.cw-settings-dialog .cw-model-search input:focus-visible { - outline: none; -} -.cw-settings-dialog .cw-model-filter { - min-height: var(--settings-control-height); - font-size: var(--settings-caption-size); - color: var(--settings-muted); -} -.cw-settings-dialog .cw-model-filter[aria-pressed="true"] { - color: var(--cw-control-accent); - background: var(--settings-active); - border-color: var(--cw-control-accent); -} -.cw-model-bulk { - display: flex; - align-items: center; - justify-content: space-between; - margin: 5px 0; - color: var(--settings-muted); - font-size: var(--settings-caption-size); -} -.cw-settings-dialog .cw-model-bulk button { - min-height: 30px; - font-size: var(--settings-caption-size); -} .cw-model-options { border: 1px solid var(--settings-border); border-radius: 8px; overflow: hidden; + margin-top: 10px; } .cw-model-option { display: flex; @@ -401,10 +356,83 @@ cursor: pointer; } .cw-settings-dialog .cw-model-row-test { + flex: none; min-height: 28px; padding: 2px 6px; + white-space: nowrap; font-size: var(--settings-caption-size); } +.cw-settings-dialog .cw-model-row-toggle { + flex: none; + min-height: 28px; + min-width: 28px; + padding: 2px; + color: var(--settings-muted); +} +.cw-settings-dialog .cw-model-row-toggle[aria-expanded="true"] { + color: var(--cw-control-accent); +} +.cw-model-option-details { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 14px; + flex-basis: 100%; + width: 100%; + min-width: 0; + padding: 2px 0 4px 24px; + border-top: 1px solid var(--settings-border); + margin-top: 4px; +} +.cw-model-option-details > .cw-model-availability { + border-top: 0; + padding: 0; +} +.cw-model-option-details > .cw-model-capability-card { + margin-top: 0; +} +.cw-model-option-details > .cw-model-note { + margin-top: 0; +} +.cw-model-capability-card.is-compact { + border: 0; + margin: 0; + padding: 0; + flex-basis: auto; + width: auto; + min-width: 0; +} +.cw-model-capability-card.is-compact fieldset { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px 12px; + padding: 0; +} +.cw-model-capability-card.is-compact .cw-model-modalities { + border: 0; + margin: 0; + padding: 0; + gap: 2px 12px; + align-items: center; + font-size: var(--settings-caption-size); +} +.cw-model-capability-card.is-compact .cw-model-modalities label { + font-size: var(--settings-caption-size); +} +.cw-model-modality-label { + color: var(--settings-muted); +} +.cw-model-capability-card.is-compact .cw-model-capability-facts { + gap: 4px 8px; +} +.cw-model-capability-card.is-compact .cw-model-capability-facts > span { + padding: 1px 6px; +} +.cw-model-capability-card.is-compact .cw-model-feedback { + flex-basis: 100%; + margin: 0; +} .cw-model-empty-state { display: flex; flex-direction: column; @@ -528,12 +556,6 @@ .cw-model-picker-actions { margin-left: auto; } - .cw-model-filterbar { - gap: 6px; - } - .cw-settings-dialog .cw-model-filter { - padding: 6px; - } .cw-model-service-models .cw-model-chip { max-width: 130px; } @@ -663,7 +685,7 @@ .cw-model-editor-scroll > .cw-provider-key { margin: 0 0 18px; } .cw-model-availability { padding: 12px 0; font-size: var(--settings-label-size, 13px); } -.cw-model-option > .cw-model-availability { flex-basis: 100%; width: 100%; min-width: 0; border-top: 1px solid var(--settings-border); } +.cw-model-option-details > .cw-model-availability { width: 100%; min-width: 0; } .cw-model-availability-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; } .cw-model-availability p, .cw-model-availability small { color: var(--settings-muted); } .cw-model-availability ul { display: grid; gap: 8px; margin: 10px 0; padding: 0; list-style: none; } @@ -679,3 +701,25 @@ .cw-model-input-details dd { margin: 0; } .cw-model-input-details small { display: block; } .cw-model-input-details summary small { display: inline; margin-inline-start: 8px; } + +/* Row details read as one compact line: declared chips, then state and action. */ +.cw-model-availability.is-compact { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px 10px; + flex: 1 1 auto; + min-width: 0; + padding: 0; + border: 0; + font-size: var(--settings-caption-size); +} +.cw-model-availability.is-compact strong { font-weight: 500; color: var(--settings-muted); } +.cw-model-availability.is-compact > ul { order: 2; display: flex; flex-wrap: wrap; align-items: center; gap: 2px 10px; margin: 0; } +.cw-model-availability.is-compact li { display: inline-flex; align-items: center; gap: 4px; grid-template-columns: none; } +.cw-model-availability.is-compact li > span:first-child { color: var(--settings-muted); } +.cw-model-availability.is-compact .cw-model-availability-heading { order: 1; justify-content: flex-start; gap: 6px; flex: none; } +.cw-model-availability.is-compact p { margin: 0; } +.cw-model-availability.is-compact small { flex: none; order: 3; } +.cw-model-availability.is-compact .cw-model-input-details { order: 4; flex-basis: 100%; margin: 0; } +.cw-model-availability.is-compact .cw-model-availability-heading .cw-settings-button { min-height: 24px; padding: 0 8px; } diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index c89c2c9c1..28a3aa148 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -207,10 +207,6 @@ export const generation = { "generation.picker.label": "Choose enabled models", "generation.picker.heading": "Models", - "generation.picker.selectedCount": { - one: "{count} selected", - other: "{count} selected", - }, "generation.picker.manual": "Add manually", "generation.picker.loading": "Fetching…", "generation.picker.refresh": "Refresh list", @@ -221,15 +217,8 @@ export const generation = { "generation.picker.addressRequired": "Enter the service address first.", "generation.picker.keyRequired": "Enter an API Key first.", "generation.picker.retry": "{error} You can retry or add a model manually.", - "generation.picker.search": "Search models", - "generation.picker.searchPlaceholder": "Search model names…", - "generation.picker.onlySelected": "Selected only", - "generation.picker.count": { - one: "{count} model", - other: "{count} models", - }, - "generation.picker.selectAll": "Select all current results", - "generation.picker.deselectAll": "Deselect all", + "generation.picker.showDetails": "Show service capabilities for {id}", + "generation.picker.hideDetails": "Hide service capabilities for {id}", "generation.picker.fetching": "Fetching the model list", "generation.picker.fetched": { one: "{count} model fetched", @@ -245,9 +234,6 @@ export const generation = { "generation.picker.manualHint": "You can add a model ID supported by the service.", "generation.picker.fetchHint": "Enter the service address, choose Fetch models, then select the models to enable.", - "generation.picker.noSelection": "No model selected yet", - "generation.picker.noMatch": "No matching models", - "generation.picker.showAll": "Show all models", "generation.picker.test": "Test", "generation.picker.testing": "Testing…", "generation.picker.testAria": "Test {id}", diff --git a/src/i18n/messages/en-US/models.ts b/src/i18n/messages/en-US/models.ts index 048319f0f..e2af05950 100644 --- a/src/i18n/messages/en-US/models.ts +++ b/src/i18n/messages/en-US/models.ts @@ -80,7 +80,7 @@ export const models = { "Enter the API base URL provided by your service.", "models.service.beijingWorkspaceUrl": "Use a Beijing API key. To use your workspace endpoint, enter https://.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 with your workspace ID.", - "models.service.inputCapabilities": "Input capabilities", + "models.service.capabilities": "Service capabilities", "models.service.referenceOutput": "References and output", "models.service.textInput": "Text", "models.service.imageInput": "Image understanding", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index 8008099b8..056acde24 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -195,7 +195,6 @@ export const generation = { "generation.picker.label": "选择启用的模型", "generation.picker.heading": "模型", - "generation.picker.selectedCount": "已选 {count} 个", "generation.picker.manual": "手动添加", "generation.picker.loading": "获取中…", "generation.picker.refresh": "刷新列表", @@ -206,12 +205,8 @@ export const generation = { "generation.picker.addressRequired": "请先填写服务地址。", "generation.picker.keyRequired": "请先填写 API Key。", "generation.picker.retry": "{error} 可重试或手动添加模型。", - "generation.picker.search": "搜索模型", - "generation.picker.searchPlaceholder": "搜索模型名称…", - "generation.picker.onlySelected": "仅看已选", - "generation.picker.count": "{count} 个模型", - "generation.picker.selectAll": "全选当前结果", - "generation.picker.deselectAll": "取消当前全选", + "generation.picker.showDetails": "展开 {id} 的服务能力", + "generation.picker.hideDetails": "收起 {id} 的服务能力", "generation.picker.fetching": "正在获取模型列表", "generation.picker.fetched": "已获取 {count} 个模型", "generation.picker.loadedPreset": "已载入 {count} 个预设模型", @@ -221,9 +216,6 @@ export const generation = { "generation.picker.manualHint": "可以手动添加服务支持的模型 ID。", "generation.picker.fetchHint": "填写服务地址后点击“获取模型”,勾选需要启用的模型。", - "generation.picker.noSelection": "还没有选择模型", - "generation.picker.noMatch": "没有匹配的模型", - "generation.picker.showAll": "显示全部模型", "generation.picker.test": "测试", "generation.picker.testing": "测试中…", "generation.picker.testAria": "测试 {id}", diff --git a/src/i18n/messages/zh-CN/models.ts b/src/i18n/messages/zh-CN/models.ts index b742580b1..1935b653b 100644 --- a/src/i18n/messages/zh-CN/models.ts +++ b/src/i18n/messages/zh-CN/models.ts @@ -71,7 +71,7 @@ export const models = { "填写服务提供的 API 根地址。", "models.service.beijingWorkspaceUrl": "使用北京地域的 API Key。如需使用业务空间专属地址,请将 https://.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 中的 替换为你的业务空间 ID。", - "models.service.inputCapabilities": "输入能力", + "models.service.capabilities": "服务能力", "models.service.referenceOutput": "参考与输出能力", "models.service.textInput": "文本", "models.service.imageInput": "图片理解", diff --git a/tests/browser/capability_discovery.mjs b/tests/browser/capability_discovery.mjs index 6db4d8f52..a63e2fbb6 100644 --- a/tests/browser/capability_discovery.mjs +++ b/tests/browser/capability_discovery.mjs @@ -260,6 +260,15 @@ try { .locator(".cw-model-manual") .getByRole("button", { name: "Add", exact: true }) .click(); + // Per-model details are collapsed so rows stay one line; open the row that + // owns this draft check before inspecting or screenshotting it. + const draftRow = page + .locator(".cw-model-option") + .filter({ has: page.getByRole("checkbox", { name: served, exact: true }) }); + const draftToggle = draftRow.locator(".cw-model-row-toggle"); + if ((await draftToggle.getAttribute("aria-expanded")) !== "true") + await draftToggle.click(); + await draftRow.locator(".cw-model-option-details").waitFor(); const draft = page.locator(".cw-model-editor .cw-model-availability"); async function presentInBothLanguages(state, expected) { for (const locale of ["en-US", "zh-CN"]) { @@ -313,6 +322,7 @@ try { .querySelector(".cw-model-availability") .getBoundingClientRect(); const label = element.querySelector("label").getBoundingClientRect(); + const row = element.getBoundingClientRect(); const scroller = element .closest(".cw-model-editor-scroll") .getBoundingClientRect(); @@ -326,17 +336,22 @@ try { labelBottom: label.bottom, labelWidth: label.width, cardWidth: card.width, + rowWidth: row.width, visibleTop: scroller.top, visibleBottom: Math.min(scroller.bottom, footer.top), }; }); assert.ok( bounds.cardTop >= bounds.labelBottom, - `${state}: capability card occupies the row below the model`, + `${state}: details occupy the row below the model line`, ); assert.ok( - bounds.labelWidth >= bounds.cardWidth * 0.9, - `${state}: model identity retains the available width`, + bounds.cardWidth <= bounds.rowWidth, + `${state}: details stay inside the model row`, + ); + assert.ok( + Math.round(bounds.labelWidth) >= Math.round(bounds.rowWidth) - 200, + `${state}: model identity keeps the row width: ${JSON.stringify(bounds)}`, ); assert.ok( bounds.cardTop >= bounds.visibleTop - 1 && @@ -362,13 +377,16 @@ try { } assert.equal( await draft.getByText("Not checked", { exact: true }).count(), - 1, + 0, + "a compact row does not spend a line on the unchecked placeholder", ); const previousQueries = queries; - await presentInBothLanguages("unchecked", { - "en-US": "Not checked", - "zh-CN": "尚未检查", - }); + await presentInBothLanguages("unchecked", null); + assert.equal( + await draft.getByRole("button", { name: /^(检查|Check)$/ }).count(), + 1, + "the compact row keeps the check action without a placeholder line", + ); await page .getByLabel("Service URL (Base URL)", { exact: true }) .fill(serviceUrl + "/"); diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 43c346644..05c6073c7 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -573,6 +573,14 @@ ], "note": "Discovers a new text model from a loopback GET /models service, saves it, and selects it in the assistant." }, + { + "file": "model_select_all.mjs", + "previewSafe": true, + "lanes": [ + "gate" + ], + "note": "Discovers a loopback GET /models catalog, keeps one checkbox per model with per-row capability details, keeps an edited selection across refresh, and saves one service with every model enabled." + }, { "file": "zhipu_catalog_fixture.mjs", "helper": true, diff --git a/tests/browser/model_select_all.mjs b/tests/browser/model_select_all.mjs new file mode 100644 index 000000000..7797e2f6f --- /dev/null +++ b/tests/browser/model_select_all.mjs @@ -0,0 +1,277 @@ +/** Model selection in service configuration (issue #477). + * + * A user with one API key wants every model the service returns enabled. A new + * service therefore starts with the discovered list selected, and each row is + * its own checkbox: there is no search box and no bulk select-all row, because + * fetching already answers "select everything", while a saved service keeps the + * subset the user chose. + * + * Start creation_server.py on 8019 and its Vite proxy on 5179; override with + * CREATION_WEB_URL and CREATION_API_URL. MODEL_SELECT_SCREENSHOT_DIR holds + * screenshots. + */ +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; +import { join } from "node:path"; +import { launchBrowser } from "./engine.mjs"; +import { + startZhipuCatalog, + zhipuBaseURL as canonicalURL, + zhipuFixtureKey as fixtureKey, + zhipuModelsPath, +} from "./zhipu_catalog_fixture.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const output = process.env.MODEL_SELECT_SCREENSHOT_DIR ?? "/tmp/opendirector-model-select-evidence"; +const bundled = ["glm-5.3", "glm-5.3-flash", "glm-5.2"]; +// The service returns none of the bundled IDs, so a stale selection would be +// visible as extra rows the service no longer offers. +const modelIds = ["glm-4.5", "glm-4.5-air", "glm-4.6", "glm-4.6-flash", "glm-4.7", "glm-4.7-air"]; +const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; + +async function call(path, { method = "GET", body } = {}) { + const response = await fetch(api + path, { + method, + headers, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + assert.ok(response.ok, `Fixture API ${method} ${path}: ${response.status}`); + return response.status === 204 ? null : response.json(); +} + +async function deleteService(configId) { + // Deleting one member removes the service, so later members answer 404. + const response = await fetch(`${api}/api/model-services/${configId}`, { method: "DELETE", headers }); + assert.ok(response.ok || response.status === 404, `Fixture API DELETE model service: ${response.status}`); +} + +const health = await call("/api/creation-test-health"); +assert.equal(health.isolated, true, "Run only against creation_server.py"); +assert.equal(health.provider, "fixture"); +const webHealth = await (await fetch(`${base}/api/creation-test-health`, { headers })).json(); +assert.equal(webHealth.root, health.root, "Web proxy must use the same isolated API"); + +// A previous run on the same fixture server must not look like this run's save. +const removed = new Set(); +for (const config of await call("/api/model-configs")) { + const service = config.providerId ?? config.id; + if (config.url.replace(/\/+$/, "") !== canonicalURL || removed.has(service)) continue; + await deleteService(config.id); + removed.add(service); +} + +await mkdir(output, { recursive: true }); +const copy = { + "zh-CN": { + settings: "设置", models: "模型接入", agentOverview: "文本模型", add: "添加服务", + provider: "提供商", zhipu: "智谱 BigModel", fetch: "获取模型", fetched: "已获取 6 个模型", + save: "保存服务", cancel: "取消", manage: "管理", refresh: "刷新列表", + enabled: "将启用 6 个模型", none: "请选择至少一个模型", + showDetails: id => `展开 ${id} 的服务能力`, + hideDetails: id => `收起 ${id} 的服务能力`, + capabilities: "服务能力", textInput: "文本", imageInput: "图片理解", + }, + "en-US": { + settings: "Settings", models: "Model connections", agentOverview: "Text model", add: "Add service", + provider: "Provider", zhipu: "Zhipu BigModel", fetch: "Fetch models", fetched: "6 models fetched", + save: "Save service", cancel: "Cancel", manage: "Manage", refresh: "Refresh list", + enabled: "Will enable 6 models", none: "Select at least one model", + showDetails: id => `Show service capabilities for ${id}`, + hideDetails: id => `Hide service capabilities for ${id}`, + capabilities: "Service capabilities", textInput: "Text", imageInput: "Image understanding", + }, +}; + +const browser = await launchBrowser(); +let createdService = null; +let catalog = null; +try { + const page = await browser.newPage({ locale: "zh-CN", viewport: { width: 1500, height: 1000 } }); + page.setDefaultTimeout(15000); + await page.addInitScript(() => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + localStorage.setItem("opendirector.locale.v1", "zh-CN"); + }); + catalog = await startZhipuCatalog(page, () => ({ status: 200, ids: modelIds, ready: Promise.resolve() })); + const button = (name, scope = page) => scope.getByRole("button", { name, exact: true }); + const picker = page.locator(".cw-model-picker"); + const footer = page.locator(".cw-model-save-status"); + const checked = () => + page.locator(".cw-model-option").evaluateAll(rows => + rows.filter(row => row.querySelector('input[type="checkbox"]').checked).length); + const rowOf = (id, scope = page) => scope.locator(".cw-model-option") + .filter({ has: scope.getByRole("checkbox", { name: id, exact: true }) }); + async function openAgentServices(labels, target = page) { + await button(labels.settings, target).click(); + await button(labels.models, target).click(); + await target.locator(".cw-model-setup-row") + .filter({ has: target.getByText(labels.agentOverview, { exact: true }) }) + .getByRole("button").click(); + } + async function newProject(locale) { + const id = crypto.randomUUID(); + await call(`/api/creation/projects/${id}/commands`, { + method: "POST", + body: { commandId: crypto.randomUUID(), projectId: id, type: "project.create", + payload: { name: `Model select all ${locale} ${id.slice(0, 8)}` } }, + }); + return `${base}/ai-tool/ai-canvas/${id}?creation=unified`; + } + + await page.goto(await newProject("zh-CN")); + await openAgentServices(copy["zh-CN"]); + await button(copy["zh-CN"].add).click(); + await page.getByRole("combobox", { name: copy["zh-CN"].provider, exact: true }).click(); + await page.getByRole("option", { name: copy["zh-CN"].zhipu, exact: true }).click(); + assert.equal(await page.locator(".cw-model-option").count(), bundled.length, "The preset starts with its bundled models"); + assert.equal(await checked(), bundled.length); + await page.getByLabel("API Key", { exact: true }).fill(fixtureKey); + + // Discovery replaces the bundled list and selects everything it returned. + await button(copy["zh-CN"].fetch).click(); + await picker.getByText(copy["zh-CN"].fetched, { exact: true }).waitFor(); + assert.deepEqual(catalog.requests, [{ method: "GET", path: zhipuModelsPath, authorized: true }]); + assert.deepEqual( + await page.locator(".cw-model-option").evaluateAll(rows => rows.map(row => row.querySelector("label").innerText.split("\n")[0].trim())), + modelIds, + "A stale bundled selection must not survive discovery", + ); + assert.equal(await checked(), modelIds.length, "One API key selects every discovered model"); + await footer.getByText(copy["zh-CN"].enabled, { exact: true }).waitFor(); + + // One count, one control per model: no search box and no bulk row. + const toolbar = await picker.evaluate(element => ({ + heading: element.querySelector(".cw-model-picker-heading").innerText, + extra: element.querySelectorAll(".cw-model-filterbar, .cw-model-search, .cw-model-bulk-action").length, + })); + assert.match(toolbar.heading, /已获取 6 个模型/, `fetch feedback stays in the heading: ${toolbar.heading}`); + assert.doesNotMatch(toolbar.heading, /已选/, "the heading does not repeat the selection count"); + assert.equal(toolbar.extra, 0, "the picker offers neither search nor bulk selection"); + + // A selected model keeps one compact line: capabilities and the availability + // check live behind a per-row disclosure instead of expanding every row. + const heights = await page.locator(".cw-model-option").evaluateAll(rows => + rows.map(row => Math.round(row.getBoundingClientRect().height))); + assert.deepEqual(heights.map(height => height <= 48), modelIds.map(() => true), + `selected rows keep one line: ${heights}`); + assert.equal(await page.locator(".cw-model-option-details").count(), 0, + "details start collapsed"); + const firstRow = rowOf(modelIds[0]); + const detailsToggle = firstRow.getByRole("button", { name: copy["zh-CN"].showDetails(modelIds[0]), exact: true }); + assert.equal(await detailsToggle.getAttribute("aria-expanded"), "false"); + await detailsToggle.click(); + const details = page.locator(".cw-model-option-details"); + await details.getByText(copy["zh-CN"].capabilities, { exact: true }).waitFor(); + assert.equal(await details.getByText(copy["zh-CN"].textInput, { exact: true }).count(), 1); + assert.equal(await details.getByText(copy["zh-CN"].imageInput, { exact: true }).count(), 1); + assert.equal(await details.count(), 1, "expanding one model shows its details only"); + assert.ok(await firstRow.evaluate(row => row.getBoundingClientRect().height) > 48, + "an expanded row grows past one line"); + assert.equal(await checked(), modelIds.length, "expanding details keeps the selection"); + await firstRow.getByRole("button", { name: copy["zh-CN"].hideDetails(modelIds[0]), exact: true }).click(); + assert.equal(await page.locator(".cw-model-option-details").count(), 0, + "the row collapses again"); + await page.screenshot({ path: join(output, "zh-CN-selected.png"), fullPage: true }); + + // A selection the user edited survives discovery, so refresh never re-enables + // a model the user turned off. + await page.getByRole("checkbox", { name: modelIds[0], exact: true }).uncheck(); + assert.equal(await checked(), modelIds.length - 1); + await button(copy["zh-CN"].refresh).click(); + await picker.getByText(copy["zh-CN"].fetched, { exact: true }).waitFor(); + assert.equal(await page.getByRole("checkbox", { name: modelIds[0], exact: true }).isChecked(), false, + "Discovery must not overwrite an edited selection"); + assert.equal(await checked(), modelIds.length - 1); + + // Clearing every checkbox asks for a selection instead of saving nothing. + for (const id of modelIds) + await page.getByRole("checkbox", { name: id, exact: true }).uncheck(); + assert.equal(await checked(), 0); + await footer.getByText(copy["zh-CN"].none, { exact: true }).waitFor(); + await page.screenshot({ path: join(output, "zh-CN-none.png"), fullPage: true }); + for (const id of modelIds) + await page.getByRole("checkbox", { name: id, exact: true }).check(); + assert.equal(await checked(), modelIds.length); + + // One save writes every enabled model. + const beforeSave = (await call("/api/model-configs")).length; + await button(copy["zh-CN"].save).click(); + await button(copy["zh-CN"].add).waitFor(); + const configs = await call("/api/model-configs"); + const services = new Set(configs.filter(config => config.url.replace(/\/+$/, "") === canonicalURL) + .map(config => config.providerId ?? config.id)); + assert.equal(services.size, 1, "One save creates one model service"); + const [serviceId] = services; + createdService = serviceId; + const saved = configs.filter(config => config.providerId === serviceId); + assert.deepEqual(saved.map(config => config.modelId).sort(), [...modelIds].sort()); + assert.equal(saved.every(config => config.kind === "agent" && config.url === canonicalURL), true); + assert.equal(configs.length - beforeSave, modelIds.length, "One save writes a config per enabled model"); + + // The same rows and labels are translated in English. + const english = await browser.newPage({ locale: "en-US", viewport: { width: 1500, height: 1000 } }); + try { + english.setDefaultTimeout(15000); + await english.addInitScript(() => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + localStorage.setItem("opendirector.locale.v1", "en-US"); + }); + await english.goto(await newProject("en-US")); + await openAgentServices(copy["en-US"], english); + await english.locator(".cw-model-service").filter({ hasText: canonicalURL }).first() + .getByRole("button", { name: copy["en-US"].manage, exact: true }).click(); + const englishPicker = english.locator(".cw-model-picker"); + await englishPicker.locator(".cw-model-option").first().waitFor(); + assert.equal(await englishPicker.locator(".cw-model-filterbar, .cw-model-search, .cw-model-bulk-action").count(), 0, + "the English picker offers neither search nor bulk selection"); + const englishFirst = english.locator(".cw-model-option").first(); + const englishToggle = englishFirst.getByRole("button", { name: copy["en-US"].showDetails(modelIds[0]), exact: true }); + assert.equal((await englishToggle.getAttribute("aria-label")), copy["en-US"].showDetails(modelIds[0])); + await englishToggle.click(); + const englishDetails = english.locator(".cw-model-option-details"); + await englishDetails.getByText(copy["en-US"].capabilities, { exact: true }).waitFor(); + assert.equal(await englishDetails.getByText(copy["en-US"].imageInput, { exact: true }).count(), 1); + assert.doesNotMatch(await englishDetails.innerText(), /[\u3400-\u9fff]/); + await english.screenshot({ path: join(output, "en-US-selected.png"), fullPage: true }); + assert.equal( + await english.locator(".cw-model-option").evaluateAll(rows => + rows.filter(row => row.querySelector('input[type="checkbox"]').checked).length), + modelIds.length, + "a saved service opens with its enabled models checked", + ); + await english.getByRole("button", { name: copy["en-US"].cancel, exact: true }).click(); + await english.locator(".cw-model-service").filter({ hasText: canonicalURL }).first() + .getByRole("button", { name: copy["en-US"].manage, exact: true }).waitFor(); + } finally { + await english.close(); + } + + assert.equal(catalog.requests.length, 2, "Only the Chinese page discovers models"); + assert.ok(catalog.requests.every((request) => + request.method === "GET" && request.path === zhipuModelsPath && request.authorized)); + console.log(JSON.stringify({ + passed: true, + checks: [ + "discovery selects every returned model for a new service", + "a stale bundled selection does not survive discovery", + "the picker has no search box and no bulk selection row", + "the toolbar shows one count only", + "selected models stay one line until their capability details are expanded", + "an edited selection survives refresh", + "clearing every checkbox asks for a selection", + "one save writes one service with every enabled model", + "both languages label the capability row", + ], + })); +} finally { + // Leave the shared fixture server without the service this run created. + if (createdService) { + for (const config of await call("/api/model-configs")) { + if (config.providerId === createdService || config.id === createdService) + await deleteService(config.id); + } + } + await browser.close(); + catalog?.close(); +} diff --git a/tests/browser/provider_settings.mjs b/tests/browser/provider_settings.mjs index 99b119186..c621e76b9 100644 --- a/tests/browser/provider_settings.mjs +++ b/tests/browser/provider_settings.mjs @@ -104,6 +104,9 @@ try { } finally { await page.unroute(discoveryEndpoint); } + // Per-model details are collapsed; open the native video model to read its + // declared capabilities. + await page.locator(".cw-model-row-toggle").first().click(); await page .getByText("Text-to-video / first-last frame / multimodal references", { exact: true }).first() .waitFor(); @@ -135,9 +138,9 @@ try { .locator(".cw-model-option") .filter({ hasText: "image-card" }); const textCard = page.locator(".cw-model-option").filter({ hasText: "text-card" }); - await textCard.locator("summary").click(); + await textCard.locator(".cw-model-row-toggle").click(); await textCard.getByRole("checkbox", { name: "Image understanding", exact: true }).uncheck(); - await card.locator("summary").click(); + await card.locator(".cw-model-row-toggle").click(); await card.getByRole("checkbox", { name: "Image understanding", exact: true }).check(); await page.screenshot({ path: "/tmp/provider-settings-agent.png" }); await page.getByRole("button", { name: "Save service", exact: true }).click();