Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
Improve API connection setup with a complete service directory (#99)
澄潭04acd088caa9
diff --git a/apps/desktop/src/features/model-connections/ConnectionDirectory.tsx b/apps/desktop/src/features/model-connections/ConnectionDirectory.tsxnew file mode 100644index 00000000..5873244d--- /dev/null+++ b/apps/desktop/src/features/model-connections/ConnectionDirectory.tsx@@ -0,0 +1,60 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { ProviderIcon } from '../../ui/ProviderIcon';+import { UiIcon } from '../../ui/UiIcon';+import { connectionTemplate } from '../../ui/provider-identity';+import { connectionDirectory, filterConnectionDirectory } from './connection-directory';+import type { BillingFilter, DirectoryProvider } from './connection-directory';+import type { ComputeConnectionOption } from './types';++export function ConnectionDirectory({ options, loading, language, free, onSelect, onCustom, onReload }: {+ options: ComputeConnectionOption[];+ loading: boolean;+ language: 'zh' | 'en';+ free: boolean;+ onSelect: (option: ComputeConnectionOption) => void;+ onCustom: () => void;+ onReload: () => void;+}) {+ const zh = language === 'zh';+ const [query, setQuery] = useState('');+ const [billing, setBilling] = useState<BillingFilter>('all');+ const [provider, setProvider] = useState<DirectoryProvider | null>(null);+ const content = useRef<HTMLElement>(null);+ const directory = useMemo(() => connectionDirectory(options, language, connectionTemplate), [options, language]);+ const visible = useMemo(() => filterConnectionDirectory(directory, query, billing), [directory, query, billing]);+ const productCount = directory.reduce((sum, item) => sum + item.products.length, 0);+ useEffect(() => {+ if (loading) return;+ const frame = requestAnimationFrame(() => {+ content.current?.querySelector<HTMLElement>(provider ? '.connection-product-card:not(:disabled)' : 'input[type=search]')?.focus();+ content.current?.closest('.modal-body')?.scrollTo({ top: 0 });+ });+ return () => cancelAnimationFrame(frame);+ }, [provider, loading]);+ const billingLabel = (value: ComputeConnectionOption['billing_class']) => ({+ paid: zh ? '按量付费' : 'Pay as you go',+ subscription: zh ? '套餐' : 'Plan',+ free: zh ? '免费资源' : 'Free resources',+ unknown: zh ? '计费方式待确认' : 'Billing unconfirmed',+ })[value];++ if (loading) return <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{zh ? '正在读取服务目录' : 'Loading services'}</strong><p>{zh ? '正在确认当前版本支持的接入方式。' : 'Checking connections supported by this version.'}</p></div></div>;+ if (provider) return <section className="connection-directory" ref={content}>+ <button className="btn btn-quiet connection-directory-back" type="button" onClick={() => setProvider(null)}><UiIcon name="arrowLeft" />{zh ? '所有供应商' : 'All providers'}</button>+ <div className="connection-product-heading"><ProviderIcon optionId={provider.products[0].option.connection_option_id} language={language} /><div><h3>{provider.name}</h3><p>{zh ? '选择与你的 API Key 对应的产品' : 'Choose the product associated with your API key'}</p></div></div>+ <div className="connection-product-list">{provider.products.map(product => <button className="connection-product-card" key={product.option.connection_option_id} type="button" disabled={!product.option.registered_check_available} onClick={() => onSelect(product.option)}>+ <span className="row-main"><strong>{product.name}</strong><span>{connectionTemplate(product.option.connection_option_id)?.description[language] || product.option.display_name}</span></span>+ <span className="connection-billing">{billingLabel(product.option.billing_class)}</span><UiIcon name="chevronRight" />+ </button>)}</div>+ </section>;+ return <section className="connection-directory" ref={content}>+ <div className="connection-directory-intro"><h3>{free ? (zh ? '选择免费资源' : 'Choose free resources') : (zh ? '选择 API 服务' : 'Choose an API service')}</h3><p>{zh ? `当前支持 ${directory.length} 家供应商 · ${productCount} 种接入方式` : `${directory.length} providers · ${productCount} connection options`}</p></div>+ <label className="field"><span className="sr-only">{zh ? '搜索供应商或产品' : 'Search providers or products'}</span><span className="connection-search"><UiIcon name="search" /><input className="input" data-autofocus type="search" value={query} placeholder={zh ? '搜索供应商或产品,如百炼、Coding Plan' : 'Search providers or products, e.g. Coding Plan'} onChange={event => setQuery(event.target.value)} /></span></label>+ {!free && <div className="connection-billing-filters" role="group" aria-label={zh ? '计费方式' : 'Billing'}>{(['all', 'paid', 'subscription', 'free'] as const).map(value => <button type="button" key={value} aria-pressed={billing === value} onClick={() => setBilling(value)}>{value === 'all' ? (zh ? '全部' : 'All') : billingLabel(value)}</button>)}</div>}+ {visible.length ? <div className="connection-provider-grid">{visible.map(item => <button className="connection-provider-card" type="button" key={item.id} disabled={!item.products.some(product => product.option.registered_check_available)} onClick={() => item.products.length === 1 ? onSelect(item.products[0].option) : setProvider(item)}>+ <ProviderIcon optionId={item.products[0].option.connection_option_id} language={language} /><strong>{item.name}</strong><span>{item.products.length > 1 ? (zh ? `${item.products.length} 种接入方式` : `${item.products.length} options`) : billingLabel(item.products[0].option.billing_class)}</span>+ </button>)}</div> : <div className="connection-directory-empty" role="status"><p>{options.length ? (zh ? '没有找到匹配的服务' : 'No matching service') : (zh ? '暂时无法读取服务目录' : 'The service directory is unavailable')}</p>{options.length ? <button type="button" className="btn" onClick={() => { setQuery(''); setBilling('all'); }}>{zh ? '清除筛选' : 'Clear filters'}</button> : <button type="button" className="btn" onClick={onReload}>{zh ? '重新读取' : 'Reload'}</button>}</div>}+ {(query || billing !== 'all') && <p className="field-help" role="status">{zh ? `显示 ${visible.length} / ${directory.length} 家供应商` : `Showing ${visible.length} of ${directory.length} providers`}</p>}+ {!free && <button className="connection-custom-entry" type="button" onClick={onCustom}><UiIcon name="plus" /><span><strong>{zh ? '自定义 API' : 'Custom API'}</strong><span>{zh ? '连接代理服务、本地模型或其他兼容服务' : 'Connect a proxy, local models or another compatible service'}</span></span><UiIcon name="chevronRight" /></button>}+ </section>;+}diff --git a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsxindex 81f8124b..bec8c2ad 100644--- a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx+++ b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx@@ -1,10 +1,10 @@import { connectionName, connectionTemplate } from '../../ui/provider-identity';-import { ConnectionTemplatePicker } from './ConnectionTemplatePicker';import { ProviderIcon } from '../../ui/ProviderIcon';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { invoke } from '@tauri-apps/api/core';import { Dialog } from '../../ui/Dialog';+import { Disclosure } from '../../ui/Disclosure';import { UiIcon } from '../../ui/UiIcon';import { confirmDiscard, useDiscardGuard } from '../../ui/discard-guard';import { saveFailureDefinitelyPreAdmission } from '../subscriptions/model';@@ -39,18 +39,20 @@ import type {import { checkFailureCode, modelAvailabilityMessage } from './copy';import { metadataModelPrefill } from './metadata-prefill';import { customApiPrefillOptions, metadataProviderCandidates, metadataProviderOption, registeredModelCandidates, sortRegisteredOptions, templateEndpointForProtocol } from './registered-metadata';+import { ConnectionDirectory } from './ConnectionDirectory';+import { ConnectionEditingSession } from './connection-session';+import './connection-flow.css';import {connectionErrorMessage,ManualModelEditor,manualModelError,manualModelIdError,- registeredConnectionLabel,safeConnectionErrorCode,validEndpoint,} from './form-support';type Phase = 'editing' | 'checking' | 'saving';-type Screen = 'connection' | 'manual' | 'models';+type Screen = 'catalog' | 'connection' | 'manual' | 'models';function emptyAdditionalEndpoint(protocol: UpstreamProtocol, authentication: ModelConnectionDraft['authentication']): ModelConnectionEndpointDraft {return {@@ -66,8 +68,11 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const zh = language === 'zh';const [custom, setCustom] = useState(props.initialDraft.entry_kind === 'custom_api');const free = props.initialDraft.entry_kind === 'free_api_key';- const [draft, setDraft] = useState<ModelConnectionDraft>(props.initialDraft);- const [screen, setScreen] = useState<Screen>('connection');+ const catalogEnabled = props.initialDraft.entry_kind !== 'custom_api' && !props.initialDraft.existing_source_id;+ const [draft, setDraft] = useState<ModelConnectionDraft>(() => ({ ...props.initialDraft,+ display_name: props.initialDraft.display_name || (catalogEnabled ? '' : zh ? '自定义 API' : 'Custom API'),+ }));+ const [screen, setScreen] = useState<Screen>(catalogEnabled ? 'catalog' : 'connection');const [phase, setPhase] = useState<Phase>('editing');const [result, setResult] = useState<ModelConnectionCheckView | null>(null);const [selected, setSelected] = useState<Set<string>>(new Set());@@ -89,14 +94,20 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const applyDispatchedRef = useRef(false);const aliveRef = useRef(true);const saveCompletedRef = useRef(false);- const dirty = JSON.stringify(draft) !== JSON.stringify(props.initialDraft) || Boolean(protectedInputRef.current);+ const editingSession = useRef(new ConnectionEditingSession());+ const editingKey = useRef<string | null>(catalogEnabled ? null : 'custom');+ const pendingSecret = useRef<string | null>(null);+ const flow = useRef<HTMLElement>(null);+ const dirty = JSON.stringify(draft) !== JSON.stringify({ ...props.initialDraft,+ display_name: props.initialDraft.display_name || (catalogEnabled ? '' : zh ? '自定义 API' : 'Custom API'),+ })+ || Boolean(protectedInputRef.current) || editingSession.current.hasDrafts;const registeredOptions = useMemo(() => sortRegisteredOptions(connectionOptions?.options.filter(option =>option.origin !== 'agent_subscription' && (!free || option.billing_class === 'free')) ?? []), [connectionOptions, free]);const registeredOption = registeredOptions.find(option => option.connection_option_id === registeredOptionId)- ?? registeredOptions[0]?? null;- const registeredLabel = registeredConnectionLabel(registeredOption, zh);+ const productName = registeredOption ? connectionName(registeredOption.connection_option_id, language, registeredOption.display_name) : '';const registeredCandidates = useMemo(() => registeredOption? registeredModelCandidates(registeredOption, connectionOptions?.metadata_catalog): [], [registeredOption, connectionOptions]);@@ -122,6 +133,11 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {protectedInputRef.current = null;if (input && !applyDispatchedRef.current) void backend.releaseProtectedInput(input).catch(() => undefined);}, [backend]);+ const releaseSession = useCallback(() => {+ editingSession.current.clear(input => { void backend.releaseProtectedInput(input).catch(() => undefined); });+ pendingSecret.current = null;+ if (password.current) password.current.value = '';+ }, [backend]);const loadConnectionOptions = useCallback(async () => {setOptionsLoading(true);@@ -131,13 +147,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {if (!aliveRef.current) return;setConnectionOptions(options);const executable = sortRegisteredOptions(options.options.filter(option => option.origin !== 'agent_subscription' && (!free || option.billing_class === 'free')));- setRegisteredOptionId(current => executable.some(option => option.connection_option_id === current)- ? current- : executable[0]?.connection_option_id ?? '');- if (!custom && executable[0] && !draftRef.current.display_name.trim()) {- const name = suggestedName(connectionName(executable[0].connection_option_id, language, executable[0].display_name));- setDraft(current => { const next = { ...current, display_name: name }; draftRef.current = next; return next; });- }+ setRegisteredOptionId(current => executable.some(option => option.connection_option_id === current) ? current : '');if (!custom && executable.length === 0) {setError('MODEL_CONNECTION_OPTION_UNAVAILABLE');}@@ -174,7 +184,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {protocol_profile_revision: 1, authentication: value.authentication_semantics ?? { kind: 'bearer' as const } }));invalidate(current => ({...current,- display_name: provider.display_name,+ display_name: current.display_name && current.display_name !== (zh ? '自定义 API' : 'Custom API') ? current.display_name : provider.display_name,display_template_id: null,base_url: endpoint?.base_url ?? provider.base_url_candidates[0],base_kind: 'api_root',@@ -227,6 +237,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {}function selectMetadataPrefill(key: string) {+ if (key !== metadataPrefillKey && password.current) password.current.value = '';setMetadataPrefillKey(key);const prefill = metadataPrefills.find(value => value.key === key);if (prefill?.kind === 'template') selectRegisteredTemplate(prefill.option);@@ -234,6 +245,23 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {}useEffect(() => { draftRef.current = draft; }, [draft]);+ useLayoutEffect(() => {+ if (screen === 'connection' && phase === 'editing' && pendingSecret.current !== null && password.current) {+ password.current.value = pendingSecret.current;+ pendingSecret.current = null;+ }+ }, [screen, phase, registeredOptionId, custom]);+ useEffect(() => {+ if (phase !== 'editing') return;+ const frame = requestAnimationFrame(() => {+ const visible = (element: HTMLElement) => element.getClientRects().length > 0 && !element.matches(':disabled');+ const target = Array.from(flow.current?.querySelectorAll<HTMLElement>('[data-autofocus]') ?? []).find(visible)+ ?? Array.from(flow.current?.querySelectorAll<HTMLElement>('input, button, summary') ?? []).find(visible);+ target?.focus();+ flow.current?.closest('.modal-body')?.scrollTo({ top: 0 });+ });+ return () => cancelAnimationFrame(frame);+ }, [screen, phase]);useEffect(() => {if (!error || phase !== 'editing') return;requestAnimationFrame(() => errorFeedback.current?.scrollIntoView({ block: 'nearest' }));@@ -245,8 +273,9 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const checkId = activeCheckRef.current;if (checkId) void backend.cancelModelConnectionCheck(checkId).catch(() => undefined);releaseProtectedInput();+ releaseSession();};- }, [backend, releaseProtectedInput]);+ }, [backend, releaseProtectedInput, releaseSession]);useEffect(() => { void loadConnectionOptions(); }, [loadConnectionOptions]);const invalidate = useCallback((@@ -282,6 +311,42 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {if (nextScreen) setScreen(nextScreen);}, [backend, releaseProtectedInput]);+ function retainEditingDraft() {+ if (!editingKey.current) return;+ editingSession.current.stash(editingKey.current, {+ draft: draftRef.current, custom, metadataPrefillKey,+ secret: password.current?.value ?? '', protectedInput: protectedInputRef.current,+ });+ protectedInputRef.current = null;+ if (password.current) password.current.value = '';+ editingKey.current = null;+ }++ function chooseConnection(option: ComputeConnectionOptions['options'][number] | null) {+ const key = option?.connection_option_id ?? 'custom';+ retainEditingDraft();+ const saved = editingSession.current.take(key);+ const endpoint = [...(option?.endpoints ?? [])].sort((a, b) => a.stable_preference - b.stable_preference)[0];+ const next = saved?.draft ?? { ...props.initialDraft,+ entry_kind: option ? (free ? 'free_api_key' as const : 'preset_api' as const) : 'custom_api' as const,+ display_name: suggestedName(option ? connectionName(option.connection_option_id, language, option.display_name) : (zh ? '自定义 API' : 'Custom API')),+ lineage_ref: clientOperationId('lineage'), candidate_ref: null, check_id: '', models: [],+ authentication: endpoint?.authentication_semantics ?? { kind: 'bearer' as const },+ };+ setCustom(saved?.custom ?? !option);+ setRegisteredOptionId(option?.connection_option_id ?? '');+ setMetadataPrefillKey(saved?.metadataPrefillKey ?? '');+ protectedInputRef.current = saved?.protectedInput ?? null;+ pendingSecret.current = saved?.secret ?? '';+ editingKey.current = key;+ invalidate(() => next, false, 'connection');+ }++ function returnToCatalog() {+ retainEditingDraft();+ invalidate(current => current, false, 'catalog');+ }+function updateManualModel(model: ModelDeclaration) {invalidate(current => ({ ...current, models: current.models.map(value => value.client_id === model.client_id ? model : value) }), false, 'manual');}@@ -402,6 +467,10 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {if (idError) { setError(idError); return; }const passwordElement = password.current;const enteredSecret = passwordElement?.value ?? '';+ if (!current.display_name.trim() || new TextEncoder().encode(current.display_name.trim()).length > 256 || current.display_name.includes('\0')) {+ setError('MODEL_CONNECTION_NAME_REQUIRED');+ return;+ }const connectionReady = custom? validEndpoint(current.base_url): Boolean(connectionOptions && registeredOption);@@ -418,10 +487,12 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {if (validation) { setError(validation); return; }}const checkId = clientOperationId('check');- const checkingDraft = { ...current, display_name: current.display_name.trim() || `${zh ? '自定义 API' : 'Custom API'} · ${custom ? new URL(current.base_url).hostname : ''}`, candidate_ref: enteredSecret ? null : current.candidate_ref, check_id: checkId };+ const checkingDraft = { ...current, display_name: current.display_name.trim(), candidate_ref: enteredSecret ? null : current.candidate_ref, check_id: checkId };draftRef.current = checkingDraft;setDraft(checkingDraft);activeCheckRef.current = checkId;+ setResult(null);+ setSelected(new Set());// A manual capability declaration must be checked again before it can be// saved. Keep that check cancellable; only lock the dialog after the// checked candidate crosses into the save phase.@@ -430,11 +501,11 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {try {if (checkingDraft.authentication.kind !== 'none' && enteredSecret) {newlyRegistered = (await backend.registerProtectedInput(enteredSecret)).input_candidate;- if (passwordElement) passwordElement.value = '';if (activeCheckRef.current !== checkId) {await backend.releaseProtectedInput(newlyRegistered);return;}+ if (passwordElement) passwordElement.value = '';releaseProtectedInput();protectedInputRef.current = newlyRegistered;}@@ -445,6 +516,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {...(inputCandidate ? { input_candidate: inputCandidate } : {}),}): await backend.checkRegisteredModelConnection({+ display_name: checkingDraft.display_name,inference_model_id: inferenceModelId,models: checkingDraft.models.filter(model => model.upstream_model_id).map(({ client_id: _clientId, ...model }) => ({ ...model, display_name: model.display_name.trim() || model.upstream_model_id })),connection_option_id: registeredOption!.connection_option_id,@@ -535,6 +607,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {if (checkId) void backend.cancelModelConnectionCheck(checkId).catch(() => undefined);setPhase('editing');setError('');+ if (screen === 'models') setScreen('connection');}function discardAndClose(kind: 'back' | 'cancel') {@@ -546,6 +619,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {cancelActiveCheck();}releaseProtectedInput();+ releaseSession();if (kind === 'back') props.onBack(); else props.onCancel();props.restoreFocus();}@@ -556,6 +630,12 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {return true;}+ async function requestClose(kind: 'back' | 'cancel') {+ if (phase === 'saving') return;+ if (dirty && !saveCompletedRef.current && !(await confirmDiscard(language))) return;+ discardAndClose(kind);+ }+async function openDocumentation(event: React.MouseEvent<HTMLAnchorElement>, url?: string) {if (!("__TAURI_INTERNALS__" in window)) return;event.preventDefault();@@ -589,32 +669,36 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const selectedCount = useMemo(() => result ? selectedModelRefsForSave(result, selected, true).length : 0, [result, selected]);const busy = phase !== 'editing';const optionUnavailable = error === 'MODEL_CONNECTION_OPTIONS_UNAVAILABLE' || error === 'MODEL_CONNECTION_OPTION_UNAVAILABLE';- const title = screen === 'models'- ? (zh ? '选择模型' : 'Select models')- : screen === 'manual'- ? (zh ? '补充未知模型' : 'Complete unknown model details')- : props.appendTo ? (zh ? `向「${props.appendTo.display_name}」添加模型` : `Add models to “${props.appendTo.display_name}”`) : custom ? (zh ? '自定义 API' : 'Custom API') : (zh ? '连接 API' : 'Connect an API');+ const title = props.appendTo ? (zh ? `向「${props.appendTo.display_name}」添加模型` : `Add models to “${props.appendTo.display_name}”`) : zh ? '连接 API' : 'Connect an API';+ const step = screen === 'catalog' ? 0 : screen === 'connection' ? 1 : 2;const footer = busy- ? <button className="btn" type="button" disabled={phase === 'saving'} onClick={() => discardAndClose('cancel')}>{phase === 'saving' ? (zh ? '正在保存…' : 'Saving…') : (zh ? '取消检查' : 'Cancel check')}</button>- : screen === 'connection'- ? <><button className="btn" type="button" onClick={() => discardAndClose('back')}>{zh ? '返回' : 'Back'}</button><button className="btn btn-primary" type="submit" form="mc-connection-form" disabled={!props.mutable || (!custom && (optionsLoading || !registeredOption))}>{zh ? '检查接入' : 'Check connection'}</button></>+ ? <button className="btn" type="button" disabled={phase === 'saving'} onClick={cancelActiveCheck}>{phase === 'saving' ? (zh ? '正在保存…' : 'Saving…') : (zh ? '取消检查' : 'Cancel check')}</button>+ : screen === 'catalog'+ ? <><button className="btn" type="button" onClick={() => void requestClose('back')}>{zh ? '返回' : 'Back'}</button><span className="field-help">{zh ? '选择服务后继续配置' : 'Choose a service to continue'}</span></>+ : screen === 'connection'+ ? <><button className="btn" type="button" onClick={() => catalogEnabled ? returnToCatalog() : void requestClose('back')}>{zh ? '返回' : 'Back'}</button><button className="btn btn-primary" type="submit" form="mc-connection-form" disabled={!props.mutable || (!custom && (optionsLoading || !registeredOption))}>{zh ? '检查并继续' : 'Check and continue'}</button></>: screen === 'manual'- ? <><button className="btn" type="button" onClick={backWithinFlow}>{zh ? '返回' : 'Back'}</button><button className="btn btn-primary" type="submit" form="mc-manual-form" disabled={!props.mutable}>{zh ? '保存接入' : 'Save connection'}</button></>- : <><button className="btn" type="button" onClick={backWithinFlow}>{zh ? '返回' : 'Back'}</button><button className="btn btn-primary" type="button" disabled={!props.mutable || !selectedCount} onClick={() => void saveSelected()}>{zh ? '保存接入' : 'Save connection'}</button></>;+ ? <><button className="btn" type="button" onClick={backWithinFlow}>{zh ? '返回' : 'Back'}</button><button className="btn btn-primary" type="submit" form="mc-manual-form" disabled={!props.mutable}>{zh ? '检查并保存' : 'Check and save'}</button></>+ : <><button className="btn" type="button" onClick={backWithinFlow}>{zh ? '返回' : 'Back'}</button><span className="connection-selection-count">{zh ? `已选择 ${selectedCount} 个模型` : `${selectedCount} models selected`}</span><button className="btn btn-primary" type="button" disabled={!props.mutable || !selectedCount} onClick={() => void saveSelected()}>{zh ? '保存连接' : 'Save connection'}</button></>;- return <Dialog open title={title} closeLabel={phase === 'saving' ? (zh ? '正在保存' : 'Saving') : (zh ? '取消添加' : 'Cancel')} closeDisabled={phase === 'saving'} onClose={() => discardAndClose('cancel')} footer={footer}>- <section className="connection-flow" aria-label={zh ? '添加模型连接' : 'Add model connection'}>+ return <Dialog open title={title} className="connection-dialog" closeLabel={phase === 'saving' ? (zh ? '正在保存' : 'Saving') : (zh ? '取消添加' : 'Cancel')} closeDisabled={phase === 'saving'} onClose={() => void requestClose('cancel')} footer={footer}>+ <section className="connection-flow" ref={flow} aria-label={zh ? '添加模型连接' : 'Add model connection'}>+ <ol className="connection-steps" aria-label={zh ? '连接步骤' : 'Connection steps'}>{(zh ? ['选择服务', '配置连接', '选择模型'] : ['Choose service', 'Configure', 'Choose models']).map((label, index) => <li key={label} className={index < step ? 'complete' : index === step ? 'current' : ''} aria-current={index === step ? 'step' : undefined}><span>{index < step ? <UiIcon name="check" /> : index + 1}</span>{label}</li>)}</ol>{props.appendTo && <p className="field-help">{zh ? '复用此接入的端点和凭据。检查后添加模型,已有模型与启停状态将保留。' : 'Reuse saved endpoints and credentials. Add models after checking; existing models and enabled state are retained.'}</p>}{!props.mutable && !busy && <div className="callout warn" role="status"><UiIcon name="warning" /><span>{zh ? '本机服务连接中断。当前输入已保留,重新连接后再保存。' : 'The local service disconnected. Your input is retained; reconnect before saving.'}</span></div>}- {busy ? <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{phase === 'checking' ? (zh ? '正在检查接入' : 'Checking connection') : (zh ? '正在保存接入' : 'Saving connection')}</strong><p>{phase === 'checking' ? (zh ? '检查配置,并在提供目录时读取模型。' : 'Checking configuration and reading the model directory when configured.') : (zh ? '保存所选模型与凭据。' : 'Saving the selected models and credential.')}</p></div></div> : <>+ {busy && <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{phase === 'checking' ? (zh ? '正在检查接入' : 'Checking connection') : (zh ? '正在保存接入' : 'Saving connection')}</strong><p>{phase === 'checking' ? (zh ? '检查配置,并在提供目录时读取模型。' : 'Checking configuration and reading the model directory when configured.') : (zh ? '保存所选模型与凭据。' : 'Saving the selected models and credential.')}</p></div></div>}+ <div className="connection-screen" hidden={busy}>+ {screen === 'catalog' && <ConnectionDirectory options={registeredOptions} loading={optionsLoading} language={language} free={free} onSelect={chooseConnection} onCustom={() => chooseConnection(null)} onReload={() => void loadConnectionOptions()} />}<form hidden={screen !== 'connection'} id="mc-connection-form" onSubmit={event => { event.preventDefault(); void runCheck(false); }}><fieldset className="connection-fields" disabled={!props.mutable || Boolean(props.appendTo)}>- {!custom && !free && <button className="btn btn-quiet" type="button" onClick={() => { setCustom(true); invalidate(current => ({ ...current, entry_kind: 'custom_api' }), true, 'connection'); }}>{zh ? '自定义 API' : 'Custom API'}</button>}+ <div className="connection-config-heading"><ProviderIcon optionId={custom ? draft.display_template_id : registeredOption?.connection_option_id} language={language} /><div><h3>{custom ? (zh ? '自定义 API' : 'Custom API') : productName}</h3><p>{custom ? (zh ? '填写服务地址,连接兼容的模型服务' : 'Connect a compatible model service') : connectionTemplate(registeredOption?.connection_option_id)?.description[language]}</p></div></div>+ <label className="field"><span className="field-label">{zh ? '连接名称' : 'Connection name'}</span><input className="input" maxLength={60} data-autofocus={screen === 'connection' || undefined} value={draft.display_name} placeholder={zh ? '例如:团队模型服务' : 'e.g. Team models'} onChange={event => invalidate(current => ({ ...current, display_name: event.target.value }), false, 'connection')} /><span className="field-help">{zh ? '用于区分不同账号或用途,保存后可在模型列表中看到。' : 'Distinguish accounts or purposes. This name appears in your model list.'}</span></label>+ {draft.authentication.kind !== 'none' && <label className="field"><span className="field-label">API Key</span><input className="input" disabled={!custom && (optionsLoading || !registeredOption)} ref={password} type="password" autoComplete="off" spellCheck={false} placeholder={protectedInputRef.current ? '••••••••••••••••' : draft.existing_source_id ? (zh ? '留空使用已保存的 Key' : 'Leave blank to use the saved key') : (zh ? '粘贴此产品的 API Key' : 'Paste this product’s API key')} onChange={() => invalidate(current => ({ ...current, candidate_ref: null }), true, 'connection')} /></label>}+ {!custom && registeredOption && <div className="connection-key-help"><span className="field-help">{zh ? '请使用上方产品对应的 Key。' : 'Use the key for the product shown above.'}</span>{connectionTemplate(registeredOption.connection_option_id)?.documentation_url && <a href={connectionTemplate(registeredOption.connection_option_id)?.documentation_url} target="_blank" rel="noreferrer" onClick={event => void openDocumentation(event, connectionTemplate(registeredOption.connection_option_id)?.documentation_url)}>{zh ? '获取 API Key' : 'Get an API key'}<UiIcon name="arrow" /></a>}{externalLinkError && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{zh ? '无法打开默认浏览器;当前表单内容已保留。' : 'The default browser could not be opened. Your form input is retained.'}</span></div>}</div>}{custom ? <>- <ProviderIcon optionId={draft.display_template_id} language={language} />- {!optionsLoading && metadataPrefills.length > 0 && <div className="connection-fields metadata-prefill-fields">- <label className="field"><span className="field-label">{zh ? '接入模板(可选)' : 'Connection template (optional)'}</span><select className="select" value={metadataPrefillKey} onChange={event => selectMetadataPrefill(event.target.value)}>- <option value="">{zh ? '手动填写' : 'Enter manually'}</option>+ {!optionsLoading && metadataPrefills.length > 0 && <Disclosure className="connection-details" language={language} label={zh ? '使用接入资料预填(可选)' : 'Use connection prefill (optional)'}><div className="connection-fields metadata-prefill-fields">+ <label className="field"><span className="field-label">{zh ? '接入资料预填(可选)' : 'Connection prefill (optional)'}</span><select className="select" value={metadataPrefillKey} onChange={event => selectMetadataPrefill(event.target.value)}>+ <option value="">{zh ? '不使用预填' : 'No prefill'}</option><optgroup label={zh ? '内置接入' : 'Built-in connections'}>{metadataPrefills.filter(prefill => prefill.kind === 'template').map(prefill => <option key={prefill.key} value={prefill.key}>{connectionName(prefill.option.connection_option_id, language, prefill.option.display_name)}</option>)}</optgroup>@@ -623,8 +707,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {{selectedPrefill && <p className="field-help">{zh? `已收录 ${metadataCandidates.length} 个模型,检查接入后统一选择;未知能力采用可编辑兜底:上下文 200K、输出 32K、工具与流式开启、视觉关闭、思考开关。`: `${metadataCandidates.length} models in this catalog. Choose after checking the connection; missing capabilities use editable defaults (200K context, 32K output, tools and streaming on, vision off, reasoning toggle).`}</p>}- </div>}- <label className="field"><span className="field-label">{zh ? '接入名称' : 'Connection name'}</span><input className="input" data-autofocus value={draft.display_name} placeholder={zh ? '例如:团队模型服务' : 'e.g. Team models'} onChange={event => invalidate(current => ({ ...current, display_name: event.target.value }), false, 'connection')} /></label>+ </div></Disclosure>}<label className="field"><span className="field-label">Base URL</span><input className="input" inputMode="url" value={draft.base_url} placeholder="https://example.com/v1" onChange={event => invalidate(current => ({ ...current, base_url: event.target.value }), true, 'connection')} /></label><label className="field"><span className="field-label">{zh ? '协议' : 'Protocol'}</span><select className="select" value={draft.protocol} onChange={event => {const protocol = event.target.value as UpstreamProtocol;@@ -660,24 +743,9 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {</> : optionsLoading? <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{zh ? '正在读取接入方式' : 'Loading connection'}</strong><p>{zh ? '从本机可信目录确认当前支持的产品。' : 'Checking supported products in the local trusted catalog.'}</p></div></div>: registeredOption- ? <ConnectionTemplatePicker options={registeredOptions} value={registeredOption.connection_option_id} language={language} onChange={id => {- setRegisteredOptionId(id);- const option = registeredOptions.find(value => value.connection_option_id === id)!;- invalidate(current => ({ ...current, candidate_ref: null, models: [], display_name: suggestedName(connectionName(id, language, option.display_name)) }), true, 'connection');- }} />+ ? <Disclosure className="connection-details" language={language} label={zh ? '连接配置 · 已自动填写' : 'Connection settings · configured automatically'}><div className="connection-endpoint-list">{registeredOption.endpoints?.map(endpoint => <div key={`${endpoint.protocol}-${endpoint.base_url}-${endpoint.request_path}`}><strong>{({ chat_completions: 'OpenAI Chat Completions', responses: 'OpenAI Responses', messages: 'Anthropic Messages' })[endpoint.protocol]}</strong><code>{endpoint.base_url.replace(/\/+$/, '')}/{endpoint.request_path.replace(/^\/+/, '')}</code></div>)}{Boolean(registeredOption.endpoints?.length) && <button className="btn btn-quiet" type="button" onClick={() => selectRegisteredTemplate(registeredOption, true)}>{zh ? '自定义连接配置' : 'Customize connection settings'}</button>}</div></Disclosure>: <div className="callout warn"><UiIcon name="warning" /><div><strong>{zh ? '当前没有可用的内置接入' : 'No built-in connection is available'}</strong><p>{connectionErrorMessage(error || 'MODEL_CONNECTION_OPTION_UNAVAILABLE', zh)}</p><button className="btn" type="button" onClick={() => void loadConnectionOptions()}>{zh ? '重新读取' : 'Reload'}</button></div></div>}- {!custom && <label className="field"><span className="field-label">{zh ? '接入名称' : 'Connection name'}</span><input className="input" maxLength={60} value={draft.display_name} placeholder={zh ? '例如:百炼 · 团队' : 'e.g. Bailian · Team'} onChange={event => invalidate(current => ({ ...current, display_name: event.target.value }), false, 'connection')} /><span className="field-help">{zh ? '同一模板可以保存多份独立接入,分别管理凭据和模型。' : 'Save independent connections from the same template, each with its own keys and models.'}</span></label>}- {!custom && registeredOption && <section>- <ProviderIcon optionId={registeredOption.connection_option_id} language={language} />- <p>{connectionTemplate(registeredOption.connection_option_id)?.description[language]}</p>- <a href={connectionTemplate(registeredOption.connection_option_id)?.documentation_url} target="_blank" rel="noreferrer" onClick={event => void openDocumentation(event, connectionTemplate(registeredOption.connection_option_id)?.documentation_url)}>{zh ? '官方说明与获取 Key' : 'Official guide and API keys'}</a>- {externalLinkError && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{zh ? '无法打开默认浏览器;当前表单内容已保留。' : 'The default browser could not be opened. Your form input is retained.'}</span></div>}- <p className="field-help">{zh- ? `已收录 ${registeredCandidates.length} 个模型,填写 Key 后统一选择。具体可用范围取决于账号和套餐。`- : `${registeredCandidates.length} models in this catalog. Enter your key, then choose models. Availability depends on your account and plan.`}</p>- {registeredOption.endpoints?.length && <button className="btn btn-quiet" type="button" onClick={() => selectRegisteredTemplate(registeredOption, true)}>{zh ? '自定义此模板的连接配置' : 'Customize this template connection'}</button>}- </section>}- {custom && <>+ {custom && <Disclosure className="connection-details" language={language} label={zh ? '高级设置' : 'Advanced settings'}><div className="connection-fields"><label className="field"><span className="field-label">{zh ? '请求路径(可选覆盖)' : 'Request path (optional override)'}</span><input className="input" value={draft.request_path_override ?? ''} onChange={event => invalidate(current => ({ ...current, request_path_override: event.target.value || null }), true, 'connection')} /></label><label className="field"><span className="field-label">{zh ? '模型目录路径(可选)' : 'Model directory path (optional)'}</span><input className="input" placeholder="/v1/models" value={draft.inventory_path_override ?? ''} onChange={event => invalidate(current => ({ ...current, inventory_path_override: event.target.value || null }), true, 'connection')} /></label><label className="field"><span className="field-label">{zh ? '认证方式' : 'Authentication'}</span><select className="select" value={draft.authentication.kind} onChange={event => invalidate(current => ({ ...current, authentication: event.target.value === 'api_key_header' ? { kind: 'api_key_header', header: 'x-api-key' } : event.target.value === 'none' ? { kind: 'none' } : { kind: 'bearer' } }), true, 'connection')}><option value="none">{zh ? '无认证' : 'None'}</option><option value="bearer">Bearer Token</option><option value="api_key_header">{zh ? '自定义 Header' : 'Custom header'}</option></select></label>@@ -704,10 +772,9 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {}}>{zh ? '添加协议端点' : 'Add protocol endpoint'}</button>}<p className="field-help">{zh ? '这些端点与上方端点共用同一个 API Key;修改端点无需重新输入已保存的 Key。' : 'All endpoints share one API key. Editing endpoints does not require re-entering a saved key.'}</p></div>- </>}- {draft.authentication.kind !== 'none' && <label className="field"><span className="field-label">API Key</span><input className="input" disabled={!custom && (optionsLoading || !registeredOption)} data-autofocus={!custom || undefined} ref={password} type="password" autoComplete="off" spellCheck={false} placeholder={protectedInputRef.current ? '••••••••••••••••' : undefined} onChange={() => invalidate(current => ({ ...current, candidate_ref: null }), true, 'connection')} /></label>}+ </div></Disclosure>}{!custom && <p className="field-help">{zh ? '检查连接配置;提供目录时读取模型,不发送推理请求。' : 'Checks connection settings and reads the model directory when available, without inference requests.'}</p>}- <button className="btn" type="button" onClick={() => invalidate(current => ({ ...current, models: current.models.length ? current.models : [blankModel()] }), false, 'manual')}>{zh ? '手工维护模型' : 'Edit models manually'}</button>+ <button className="btn btn-quiet connection-manual-entry" type="button" onClick={() => invalidate(current => ({ ...current, models: current.models.length ? current.models : [blankModel()] }), false, 'manual')}>{zh ? '手工维护模型' : 'Edit models manually'}</button></fieldset></form>@@ -717,6 +784,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {</form>}{screen === 'models' && result && <section className="model-selection" aria-live="polite">+ <div className="connection-config-heading"><ProviderIcon optionId={custom ? draft.display_template_id : registeredOption?.connection_option_id} language={language} /><div><h3>{draft.display_name}</h3><p>{custom ? (zh ? '自定义 API' : 'Custom API') : productName}</p></div></div><p className="v3-select-intro">{zh ? '选择需要接入的模型,已知能力会自动匹配。' : 'Choose models to connect. Known capabilities are matched automatically.'}</p>{result.reachability === 'transport_failed' && <p className="field-help">{zh ? '目录连接失败;保留已有模型声明,推理可用性仍未知。' : 'The directory connection failed. Model declarations are retained; inference availability remains unknown.'}</p>}{result.authentication === 'unknown' && <p className="field-help">{zh ? '凭据尚未验证。' : 'Credentials have not been verified.'}</p>}@@ -725,16 +793,16 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {<button className="btn btn-quiet" type="button" onClick={() => invalidate(current => ({ ...current, models: result.candidate.models.filter(model => selected.has(model.model_ref)).map(model => current.models.find(value => value.upstream_model_id === model.upstream_model_id) ?? blankModel(model.upstream_model_id, model.display_name)) }), false, 'manual')}>{zh ? '编辑所选模型 / 添加模型' : 'Edit selected models / add model'}</button>{['not_run', 'empty', 'unavailable', 'invalid'].includes(result.directory) && <p className="field-help">{zh ? '未取得模型目录,保留内置或手工声明的模型。' : 'No model directory was obtained. Built-in and manually declared models are retained.'}</p>}{result.directory === 'partial' && <div className="callout warn"><UiIcon name="warning" /><span>{zh ? '模型目录只读取到一部分。可以先保存已确认的模型,稍后再重新检查。' : 'Only part of the model catalog was read. You can save confirmed models and check again later.'}</span></div>}- <fieldset className="v3-catalog model-result-list" disabled={!props.mutable}><legend className="sr-only">{zh ? '选择保存的模型' : 'Select models to save'}</legend>{result.candidate.models.map(model => {+ <fieldset className="v3-catalog model-result-list" disabled={!props.mutable}><legend className="sr-only">{zh ? '选择保存的模型' : 'Select models to save'}</legend>{result.candidate.models.map((model, index) => {const canSelect = modelCanBeSelected(result, model, true);- return <div className="model-result-row" key={model.model_ref}><label className="check-row"><input type="checkbox" disabled={!canSelect} checked={canSelect && selected.has(model.model_ref)} onChange={event => setSelected(current => { const next = new Set(current); if (event.target.checked) next.add(model.model_ref); else next.delete(model.model_ref); setError(''); return next; })} /><div><strong>{model.display_name}</strong><span>{draft.display_name || registeredLabel.title}{model.fact_basis === 'runtime_fallback' ? ` · ${zh ? '运行时保守兜底' : 'Conservative runtime fallback'}` : ''}{!canSelect ? ` · ${modelAvailabilityMessage(model.reason, zh)}` : ''}</span></div></label>{custom && !canSelect && <button className="btn btn-quiet" type="button" onClick={() => {+ return <div className="model-result-row" key={model.model_ref}><label className="check-row"><input type="checkbox" data-autofocus={index === 0 || undefined} disabled={!canSelect} checked={canSelect && selected.has(model.model_ref)} onChange={event => setSelected(current => { const next = new Set(current); if (event.target.checked) next.add(model.model_ref); else next.delete(model.model_ref); setError(''); return next; })} /><div><strong>{model.display_name}</strong><span>{draft.display_name}{model.fact_basis === 'runtime_fallback' ? ` · ${zh ? '运行时保守兜底' : 'Conservative runtime fallback'}` : ''}{!canSelect ? ` · ${modelAvailabilityMessage(model.reason, zh)}` : ''}</span></div></label>{custom && !canSelect && <button className="btn btn-quiet" type="button" onClick={() => {const prefilled = draftRef.current.models.find(value => value.upstream_model_id === model.upstream_model_id);const manualDraft = { ...draftRef.current, edit_revision: draftRef.current.edit_revision + 1, check_id: '', models: [prefilled ?? blankModel(model.upstream_model_id, model.display_name)] };draftRef.current = manualDraft; setDraft(manualDraft); setResult(null); setScreen('manual'); setError('');}}>{zh ? '补充能力' : 'Add capability details'}</button>}</div>;})}</fieldset></section>}- </>}+ </div>{error && !busy && !optionUnavailable && <div ref={errorFeedback} role="alert" className="callout bad" data-error-code={error}><UiIcon name="warning" /><span>{connectionErrorMessage(error, zh)}</span></div>}</section></Dialog>;diff --git a/apps/desktop/src/features/model-connections/README.md b/apps/desktop/src/features/model-connections/README.mdindex 61f4898f..42e9d6cd 100644--- a/apps/desktop/src/features/model-connections/README.md+++ b/apps/desktop/src/features/model-connections/README.md@@ -2,6 +2,13 @@`ModelConnectionForm` is the MVP-12 domain component for preset API, custom API, direct-free, and API-key-free entries. Its host supplies one `ModelConnectionBackend` implemented through the native protected-input bridge and Client Core. The component does not register Tauri commands or mount itself in the global shell.+`ConnectionDirectory` groups the executable options into a complete branded provider+directory, with product selection, search and billing filters. The form owns the+service → configuration → model steps and editable source name. `ConnectionEditingSession`+retains each product's draft and credential only while that dialog is open; returning+between steps preserves it, while closing or saving releases unused protected inputs.+Saved-source edit and append enter configuration directly and retain their lifecycle rules.+The password field is uncontrolled. Its value is passed only to `registerProtectedInput` and cleared immediately; checks, previews, public state, and callbacks use the returned safe candidate reference. Editing the target, protocol, or authentication releases that reference and invalidates the prior check. Once Apply is dispatched, the component stops releasing the protected input because the save operation may have taken ownership, including when the response is uncertain.Each edit has a client `edit_revision`; every check has a unique `check_id`. A result is rendered only when those values, the candidate lineage, and both returned copies of `input_digest` agree. Save uses the backend `candidate_revision`, maps the enable checkbox to `save_ready`, and uses `save_disabled` for a disabled draft. `complete` facts still pass through backend Preview and Apply authorization.@@ -13,4 +20,4 @@ discovered, removed, or unavailable models are never automatically selected.The composition owner must provide the real Tauri/Client Core adapter, open/return navigation, current revision set, protected-input lifecycle, and save recovery callbacks. The feature intentionally does not implement storage, transaction recovery, routing compilation, or the “My models” page.-The connection-options response may also carry the complete client-bundled current metadata snapshot. Registered options are shown only when the current registry has a native API option, provider-key authentication, and at least one exact model capability. Custom API users may select source-scoped provider/model records for editable prefill. Each field is gated by its `usable_for` scenario; unknown or conditional fields stay blank, credentials are never inferred, lifecycle data is warning-only, and nested cost hints are explicitly presented as “not a price.” A connection check remains mandatory before any selected metadata can be saved.+The connection-options response also carries the client-bundled current metadata snapshot. The directory uses executable native API options; model candidates and capability prefill come from the selected option and its matching metadata. Custom API prefill offers those same native options and keeps the configuration editable. Unknown capabilities use the form's editable defaults. Credentials are never inferred, lifecycle data is warning-only, and nested cost hints are explicitly presented as “not a price.” A connection check remains mandatory before selected metadata can be saved.diff --git a/apps/desktop/src/features/model-connections/connection-directory.ts b/apps/desktop/src/features/model-connections/connection-directory.tsnew file mode 100644index 00000000..c98ae209--- /dev/null+++ b/apps/desktop/src/features/model-connections/connection-directory.ts@@ -0,0 +1,48 @@+import type { ComputeConnectionOption } from './types';++type Identity = { provider_id: string; name: { zh: string; en: string } };+export type DirectoryProduct = {+ option: ComputeConnectionOption;+ name: string;+ searchText: string;+};+export type DirectoryProvider = {+ id: string;+ name: string;+ products: DirectoryProduct[];+};+export type BillingFilter = 'all' | ComputeConnectionOption['billing_class'];++/** Unknown catalog entries remain visible even when the bundled branding has no match. */+export function connectionDirectory(+ options: ComputeConnectionOption[],+ language: 'zh' | 'en',+ identity: (optionId: string) => Identity | undefined,+): DirectoryProvider[] {+ const providers = new Map<string, DirectoryProvider>();+ for (const option of options) {+ if (option.origin === 'agent_subscription') continue;+ const template = identity(option.connection_option_id);+ const name = template?.name[language] || option.display_name;+ const providerName = name.split(' · ')[0];+ const providerId = template?.provider_id || option.connector_id || option.connection_option_id;+ const provider = providers.get(providerId) ?? { id: providerId, name: providerName, products: [] };+ provider.products.push({ option, name, searchText: [+ providerId, providerName, name, template?.name.zh, template?.name.en,+ option.display_name, option.connection_option_id,+ option.billing_class === 'subscription' && `${name} ${option.display_name}`.toLocaleLowerCase().includes('coding') ? 'coding plan' : '',+ ].filter(Boolean).join(' ').toLocaleLowerCase() });+ providers.set(providerId, provider);+ }+ return [...providers.values()];+}++export function filterConnectionDirectory(providers: DirectoryProvider[], query: string, billing: BillingFilter): DirectoryProvider[] {+ const needle = query.trim().toLocaleLowerCase();+ return providers.flatMap(provider => {+ const products = provider.products.filter(product =>+ (billing === 'all' || product.option.billing_class === billing)+ && (!needle || product.searchText.includes(needle)));+ return products.length ? [{ ...provider, products }] : [];+ });+}diff --git a/apps/desktop/src/features/model-connections/connection-flow.css b/apps/desktop/src/features/model-connections/connection-flow.cssnew file mode 100644index 00000000..877839f0--- /dev/null+++ b/apps/desktop/src/features/model-connections/connection-flow.css@@ -0,0 +1,63 @@+.modal.connection-dialog { width:min(680px,calc(100vw - 48px)); }+.connection-flow [hidden] { display:none !important; }+.connection-flow,.connection-screen,.connection-directory { display:grid;gap:18px;min-width:0; }+.connection-steps { display:flex;align-items:center;justify-content:space-between;gap:12px;list-style:none;padding:0 0 18px;margin:0;border-bottom:1px solid var(--divider); }+.connection-steps li { display:flex;align-items:center;gap:8px;color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale)); }+.connection-steps li>span { display:grid;place-items:center;flex:none;width:24px;height:24px;border-radius:50%;background:var(--panel-solid);border:1px solid var(--border);font-size:calc(11px * var(--hr-text-scale)); }+.connection-steps .current { color:var(--accent-bright);font-weight:600; }+.connection-steps .current>span { background:var(--accent);border-color:var(--accent);color:white; }+.connection-steps .complete>span { color:var(--accent-bright);background:var(--accent-soft);border-color:transparent; }+.connection-steps .icon { width:14px;height:14px; }+.connection-directory-intro h3,.connection-config-heading h3,.connection-product-heading h3 { margin:0;font-size:calc(16px * var(--hr-text-scale));font-weight:600; }+.connection-directory-intro p,.connection-config-heading p,.connection-product-heading p { margin:6px 0 0;color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale));line-height:1.6; }+.connection-search { display:block;position:relative; }+.connection-search>.icon { position:absolute;left:12px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:var(--text-muted); }+.connection-search>.input { width:100%;padding-left:36px; }+.connection-billing-filters { display:flex;flex-wrap:wrap;gap:6px; }+.connection-billing-filters button { border:1px solid transparent;border-radius:8px;padding:6px 12px;background:transparent;color:var(--text-muted);font:inherit;font-size:calc(12px * var(--hr-text-scale));cursor:pointer; }+.connection-billing-filters button[aria-pressed=true] { color:var(--accent-bright);background:var(--accent-soft);border-color:color-mix(in srgb,var(--accent) 24%,transparent); }+.connection-provider-grid { display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px; }+.connection-provider-card { display:grid;grid-template-columns:34px minmax(0,1fr);align-items:center;column-gap:10px;row-gap:3px;min-height:72px;padding:12px;text-align:left;border:1px solid var(--border);border-radius:11px;background:var(--panel-solid);color:var(--text);cursor:pointer; }+.connection-provider-card>.provider-icon { grid-row:1/3;width:34px;height:34px; }+.connection-provider-card>strong { font-size:calc(13px * var(--hr-text-scale));font-weight:600;overflow-wrap:anywhere; }+.connection-provider-card>span:last-child { color:var(--text-muted);font-size:calc(11px * var(--hr-text-scale)); }+.connection-provider-card:hover,.connection-product-card:hover,.connection-custom-entry:hover { border-color:var(--accent);background:var(--accent-soft); }+.connection-provider-card:focus-visible,.connection-product-card:focus-visible,.connection-custom-entry:focus-visible,.connection-billing-filters button:focus-visible { outline:2px solid var(--accent);outline-offset:2px; }+.connection-provider-card:disabled,.connection-product-card:disabled { cursor:default;opacity:.5; }+.connection-custom-entry { display:flex;align-items:center;gap:12px;padding:14px;border:1px dashed var(--border-strong);border-radius:11px;background:transparent;text-align:left;color:var(--text);cursor:pointer; }+.connection-custom-entry>span { display:grid;gap:4px;flex:1; }+.connection-custom-entry strong { font-size:calc(13px * var(--hr-text-scale));font-weight:600; }+.connection-custom-entry>span>span { color:var(--text-muted);font-size:calc(11px * var(--hr-text-scale));line-height:1.6; }+.connection-product-heading,.connection-config-heading { display:flex;align-items:center;gap:12px;min-width:0; }+.connection-config-heading { padding:14px;background:var(--accent-soft);border-radius:12px; }+.connection-config-heading>div,.connection-product-heading>div { min-width:0;overflow-wrap:anywhere; }+.connection-product-heading>.provider-icon,.connection-config-heading>.provider-icon { flex:none;width:40px;height:40px; }+.connection-product-list { display:grid;gap:10px; }+.connection-product-card { display:flex;align-items:center;gap:12px;padding:16px;text-align:left;background:var(--panel-solid);border:1px solid var(--border);border-radius:11px;color:var(--text);cursor:pointer; }+.connection-product-card .row-main { display:grid;gap:6px;flex:1;min-width:0; }+.connection-product-card strong { font-size:calc(14px * var(--hr-text-scale)); }+.connection-product-card .row-main>span { color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale));line-height:1.6; }+.connection-billing { flex:none;padding:4px 8px;border-radius:6px;background:var(--accent-soft);color:var(--accent-bright);font-size:calc(11px * var(--hr-text-scale)); }+.connection-directory-back,.connection-manual-entry { justify-self:start; }+.connection-directory-empty { padding:28px 12px;text-align:center;color:var(--text-muted); }+.connection-key-help { display:flex;align-items:center;flex-wrap:wrap;justify-content:space-between;gap:8px;margin-top:-8px; }+.connection-key-help>a { display:flex;align-items:center;gap:4px;color:var(--accent-bright);font-size:calc(12px * var(--hr-text-scale)); }+.connection-key-help>a>.icon { width:13px;height:13px; }+.connection-details { border:1px solid var(--border);border-radius:10px;min-width:0; }+.connection-details>summary { cursor:pointer;padding:12px 14px;font-size:calc(12px * var(--hr-text-scale));color:var(--text-soft); }+.connection-details>div { padding:4px 14px 14px; }+.connection-endpoint-list { display:grid;gap:14px; }+.connection-endpoint-list>div { display:grid;gap:4px;min-width:0; }+.connection-endpoint-list strong { font-size:calc(12px * var(--hr-text-scale));font-weight:500; }+.connection-endpoint-list code { overflow-wrap:anywhere;color:var(--text-muted);font-size:calc(11px * var(--hr-text-scale)); }+.connection-selection-count { color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale)); }+@media(max-width:560px) {+ .modal.connection-dialog { width:calc(100vw - 24px);max-height:calc(100dvh - 24px); }+ .connection-dialog .modal-head,.connection-dialog .modal-body,.connection-dialog .modal-foot { padding:16px; }+ .connection-steps { gap:6px; }+ .connection-steps li { gap:5px;font-size:calc(11px * var(--hr-text-scale)); }+ .connection-provider-grid { grid-template-columns:repeat(2,minmax(0,1fr));gap:8px; }+ .connection-provider-card { padding:10px;column-gap:8px; }+ .connection-product-card { flex-wrap:wrap; }+ .connection-product-card .row-main { flex-basis:100%; }+}diff --git a/apps/desktop/src/features/model-connections/connection-session.ts b/apps/desktop/src/features/model-connections/connection-session.tsnew file mode 100644index 00000000..43c059c3--- /dev/null+++ b/apps/desktop/src/features/model-connections/connection-session.ts@@ -0,0 +1,30 @@+import type { ComputeCandidateRef, ModelConnectionDraft } from './types';++export type ConnectionEditingDraft = {+ draft: ModelConnectionDraft;+ custom: boolean;+ metadataPrefillKey: string;+ secret: string;+ protectedInput: ComputeCandidateRef | null;+};++/** Credentials live only in this dialog's memory; never in a serializable UI draft. */+export class ConnectionEditingSession {+ private drafts = new Map<string, ConnectionEditingDraft>();++ get hasDrafts() { return this.drafts.size > 0; }+ stash(key: string, value: ConnectionEditingDraft) { this.drafts.set(key, value); }+ take(key: string) {+ const value = this.drafts.get(key);+ this.drafts.delete(key);+ return value;+ }+ clear(release: (input: ComputeCandidateRef) => void) {+ for (const value of this.drafts.values()) {+ value.secret = '';+ if (value.protectedInput) release(value.protectedInput);+ value.protectedInput = null;+ }+ this.drafts.clear();+ }+}diff --git a/apps/desktop/src/features/model-connections/form-support.tsx b/apps/desktop/src/features/model-connections/form-support.tsxindex 42209cdc..1306b93f 100644--- a/apps/desktop/src/features/model-connections/form-support.tsx+++ b/apps/desktop/src/features/model-connections/form-support.tsx@@ -18,7 +18,8 @@ export function connectionErrorMessage(code: string, zh: boolean): string {if (code === 'MODEL_SAVE_RECHECK_REQUIRED') return zh? '本次保存未生效。请重新检查接入后再保存;如使用 API Key,请重新输入。模型选择和非敏感配置已保留。': 'This save did not take effect. Check the connection again before saving; re-enter the API key if used. Model choices and non-sensitive settings are retained.';- if (code === 'MODEL_CONNECTION_FIELDS_REQUIRED') return zh ? '请填写 API Key 和有效的连接地址。' : 'Enter an API key and a valid endpoint.';+ if (code === 'MODEL_CONNECTION_NAME_REQUIRED') return zh ? '请填写连接名称,名称过长时请缩短。' : 'Enter a connection name; shorten it if it is too long.';+ if (code === 'MODEL_CONNECTION_FIELDS_REQUIRED') return zh ? '请填写有效的连接地址。' : 'Enter a valid endpoint.';if (code === 'MODEL_CONNECTION_KEY_REQUIRED') return zh ? '请填写 API Key。' : 'Enter an API key.';if (code === 'MODEL_CONNECTION_AUTHENTICATION_REJECTED') return zh? '凭据未通过检查。请检查 API Key 后重试,输入已保留。'diff --git a/apps/desktop/src/features/model-connections/types.ts b/apps/desktop/src/features/model-connections/types.tsindex be03cb5b..7df74b31 100644--- a/apps/desktop/src/features/model-connections/types.ts+++ b/apps/desktop/src/features/model-connections/types.ts@@ -342,6 +342,7 @@ export type ModelConnectionCheckRequest = {input_candidate?: ComputeCandidateRef;};export type RegisteredModelConnectionCheckRequest = {+ display_name: string;inference_model_id?: string | null;models?: Omit<ModelDeclaration, 'client_id'>[];connection_option_id: string;diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsxindex a1eaa851..6dcae3a2 100644--- a/apps/desktop/src/features/models/Models.tsx+++ b/apps/desktop/src/features/models/Models.tsx@@ -478,6 +478,9 @@ export function Models(props: Props) {function connectionLabel(source: ManagedSource, language: 'zh' | 'en') {const product = connectionName(source.connection_identity?.connection_option_id, language, source.connection_identity?.product_label ?? '');const access = sourceAccess(source);+ if (access === 'api' && source.display_name) {+ return product && product !== source.display_name ? `${source.display_name} · ${product}` : source.display_name;+ }if (product) {if (source.display_name && source.display_name !== product) return `${source.display_name} · ${product}`;if (access === 'subscription') return `${source.display_name || product} · OAuth`;diff --git a/apps/desktop/src/ui/Dialog.tsx b/apps/desktop/src/ui/Dialog.tsxindex 13e539f6..c39a64c8 100644--- a/apps/desktop/src/ui/Dialog.tsx+++ b/apps/desktop/src/ui/Dialog.tsx@@ -24,6 +24,7 @@ export function Dialog({children,footer,variant = 'modal',+ className = '',}: {open: boolean;title: string;@@ -34,6 +35,7 @@ export function Dialog({children: React.ReactNode;footer?: React.ReactNode;variant?: 'modal' | 'drawer';+ className?: string;}) {const panel = useRef<HTMLElement>(null);const returnTarget = useRef<HTMLElement | null>(null);@@ -59,7 +61,7 @@ export function Dialog({branch = branch.parentElement;}const frame = requestAnimationFrame(() => {- const first = panel.current?.querySelector<HTMLElement>('[data-autofocus]')+ const first = Array.from(panel.current?.querySelectorAll<HTMLElement>('[data-autofocus]') ?? []).find(element => element.getClientRects().length > 0 && !element.matches(':disabled'))?? Array.from(panel.current?.querySelector<HTMLElement>('.modal-body')?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0)?? Array.from(panel.current?.querySelector<HTMLElement>('.modal-foot')?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0)?? Array.from(panel.current?.querySelectorAll<HTMLElement>(focusableSelector) ?? []).find(element => element.getClientRects().length > 0);@@ -87,7 +89,7 @@ export function Dialog({><sectionref={panel}- className={`modal${variant === 'drawer' ? ' oc-drawer-panel' : ''}`}+ className={`modal${variant === 'drawer' ? ' oc-drawer-panel' : ''} ${className}`.trim()}role="dialog"aria-modal="true"aria-labelledby={titleId}diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex 2327a460..71f22e90 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -9,6 +9,7 @@ proves native authorization, persistence, process cleanup or real model calls.| User capability | Representative tests | Unique guarantee || --- | --- | --- |+| Connect an API through the service directory | [Connection flow scenarios](v3/visual/connection-flow-active.mjs), [directory and draft rules](connection-directory.test.mjs) | Full branded directory, separate product drafts and keys, checked source name, cancellation, explicit model selection and inherited append behavior. Uses production styles; native save and live calls need separate acceptance. || Enable or edit Codex routing | `codex.enable.draft-cancel`, `codex.routing.fixed-binding`, `codex.routing.mixed-native-default` in [Agent scenarios](v3/browser/agent-trust-scenarios.mjs) | Cancelling never applies; configured fixed overrides, native reasoning and the chosen default survive save; service responsibility is explained. || Configure Claude routing and collaboration | `claude.enable.shared-presets`, `agent.configuration.independent-facets`, `claude.collaboration.check-before-save`, `claude.collaboration.retry-preserves-edit` | Ordinary Claude entry and account Default limitations remain clear; prerequisite checks precede mutation; retry preserves edits. || Enable, recover or disable Qoder task collaboration | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore` | No model connection or published Plan is required; required capability checks happen during save. Login and changed-Skill failures retain edits and enabled collaboration with the shared retry action; restore keeps model configuration unchanged. |diff --git a/apps/desktop/tests/connection-directory.test.mjs b/apps/desktop/tests/connection-directory.test.mjsnew file mode 100644index 00000000..4f7daca8--- /dev/null+++ b/apps/desktop/tests/connection-directory.test.mjs@@ -0,0 +1,49 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { connectionDirectory, filterConnectionDirectory } from '../src/features/model-connections/connection-directory.ts';+import { ConnectionEditingSession } from '../src/features/model-connections/connection-session.ts';++const read = path => JSON.parse(readFileSync(new URL(path, import.meta.url), 'utf8'));+const registry = read('../../../assets/release-facts/current/bundle/connector-registry.json');+const templates = read('../../../assets/model-data/current/runtime-projection.json').connection_templates;+const lookup = id => templates.find(item => item.connection_option_id === id);+const directory = connectionDirectory(registry.connection_options, 'zh', lookup);++test('the directory contains every current API option and excludes subscription login', () => {+ const native = registry.connection_options.filter(item => item.origin !== 'agent_subscription');+ assert.deepEqual(directory.flatMap(provider => provider.products.map(product => product.option.connection_option_id)).sort(),+ native.map(option => option.connection_option_id).sort());+ assert.equal(directory.length, 13);+ assert.equal(native.length, 18);+ assert.equal(directory.find(provider => provider.id === 'bailian').products.length, 3);+ const future = { ...native[0], connection_option_id: 'future.api', connector_id: 'future.connector', display_name: 'Future service' };+ assert.equal(connectionDirectory([...native, future], 'zh', lookup).at(-1).products[0].option.connection_option_id, 'future.api');+});++test('search finds product names in either language and billing filters retain only matching products', () => {+ assert.equal(filterConnectionDirectory(directory, '百炼', 'all')[0].products.length, 3);+ assert.ok(filterConnectionDirectory(directory, 'Coding Plan', 'all').length > 1);+ const free = filterConnectionDirectory(directory, '', 'free');+ assert.equal(free.flatMap(provider => provider.products).length, 5);+ assert.ok(free.every(provider => provider.products.every(product => product.option.billing_class === 'free')));+ assert.equal(filterConnectionDirectory(directory, 'not-a-provider', 'all').length, 0);+});++test('editing credentials stay scoped to a product and unused protected inputs are released', () => {+ const session = new ConnectionEditingSession();+ const input = id => ({ candidate_ref: id, candidate_revision: 1 });+ const first = { draft: { display_name: 'Team' }, custom: false, metadataPrefillKey: '', secret: 'fixture-first', protectedInput: input('first') };+ const second = { draft: { display_name: 'Personal' }, custom: false, metadataPrefillKey: '', secret: 'fixture-second', protectedInput: input('second') };+ session.stash('first', first);+ session.stash('second', second);+ assert.equal(session.take('other'), undefined);+ assert.equal(session.take('first'), first);+ assert.equal(session.take('first'), undefined);+ const released = [];+ session.clear(value => released.push(value.candidate_ref));+ assert.deepEqual(released, ['second']);+ assert.equal(second.secret, '');+ assert.equal(second.protectedInput, null);+ assert.equal(session.hasDrafts, false);+});diff --git a/apps/desktop/tests/v3/browser/connection-flow.html b/apps/desktop/tests/v3/browser/connection-flow.htmlnew file mode 100644index 00000000..84d4c632--- /dev/null+++ b/apps/desktop/tests/v3/browser/connection-flow.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="zh-CN">+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>API connection flow acceptance</title></head>+ <body><div id="root"></div><script type="module" src="./connection-flow.tsx"></script></body>+</html>diff --git a/apps/desktop/tests/v3/browser/connection-flow.tsx b/apps/desktop/tests/v3/browser/connection-flow.tsxnew file mode 100644index 00000000..b8f58a40--- /dev/null+++ b/apps/desktop/tests/v3/browser/connection-flow.tsx@@ -0,0 +1,63 @@+import { useMemo, useState } from 'react';+import { createRoot } from 'react-dom/client';+import { ModelConnectionForm } from '../../../src/features/model-connections/ModelConnectionForm';+import { newModelConnectionDraft } from '../../../src/product/ModelManagementPage';+import { Models } from '../../../src/features/models/Models';+import type { ModelConnectionBackend } from '../../../src/features/model-connections/types';+import { mockProductInvoke, readyManagement } from './product-fixtures';+import { PresentationRoot } from '../../../src/ui/PresentationRoot';+import '../../../src/occami/styles.css';++const params = new URLSearchParams(location.search);+const kind = params.get('kind') === 'free' ? 'free' : params.get('kind') === 'custom' ? 'custom' : 'known';+const trace = { checks: [] as unknown[], registered: [] as string[], released: [] as string[], saves: [] as unknown[] };+const pendingChecks: (() => void)[] = [];+Object.assign(window, { connectionFlowTrace: trace, finishConnectionFlowCheck: () => pendingChecks.shift()?.() });++function Harness() {+ const [open, setOpen] = useState(true);+ const [savedName, setSavedName] = useState('');+ const appendTo = params.has('append') ? { ...readyManagement.sources[0], display_name: '已有 · 接入', state: 'disabled' as const } : undefined;+ const initial = useMemo(() => appendTo ? { ...newModelConnectionDraft('custom'),+ existing_source_id: appendTo.source_id, display_name: appendTo.display_name, base_url: 'https://api.example.test',+ } : newModelConnectionDraft(kind), []);+ const language = params.get('lang') === 'en' ? 'en' : 'zh';+ const backend = useMemo<ModelConnectionBackend>(() => {+ const invoke = async (command: string, payload?: Record<string, unknown>) => mockProductInvoke(command, payload, kind === 'custom' && !appendTo ? 'unknown_model' : 'ready') as any;+ const check = async (command: string, request: any) => {+ if (params.get('hold_check')) await new Promise<void>(resolve => pendingChecks.push(resolve));+ const result = await invoke(command, { request });+ const ref = request.input_candidate?.candidate_ref ?? 'candidate/no-auth';+ return { ...result, candidate: { ...result.candidate, candidate: { candidate_ref: ref, candidate_revision: 2 },+ correlation: { ...result.candidate.correlation, candidate_ref: ref } } };+ };+ return {+ listConnectionOptions: () => invoke('compute_connection_options'),+ registerProtectedInput: async secret => {+ // Test labels identify fixture credentials without putting them into a wire draft.+ trace.registered.push(secret === 'fixture-key-a' ? 'a' : secret === 'fixture-key-b' ? 'b' : 'other');+ return { input_candidate: { candidate_ref: `input/${trace.registered.length}`, candidate_revision: 1 } };+ },+ releaseProtectedInput: async input => { trace.released.push(input.candidate_ref); },+ checkModelConnection: async request => { trace.checks.push(request); setSavedName(request.draft.display_name); return check('check_model_connection', request); },+ checkRegisteredModelConnection: async request => { trace.checks.push(request); setSavedName(request.display_name); return check('check_registered_model_connection', request); },+ cancelModelConnectionCheck: async () => undefined,+ previewComputeSave: async change => { trace.saves.push(change); return invoke('preview_compute_save', { change }); },+ applyComputeSave: request => invoke('apply_compute_save', { request }),+ getComputeSaveResult: operation => invoke('get_compute_save_result', { operation }),+ };+ }, []);+ const management = useMemo(() => ({ ...readyManagement, sources: readyManagement.sources.map(source =>+ source.provenance === 'registered' ? { ...source, display_name: savedName || '团队模型服务' } : source) }), [savedName]);+ return <PresentationRoot language={language} theme={params.get('theme') === 'dark' ? 'dark' : 'light'} textScale={params.get('scale') === '2' ? 2 : 1}>+ <Models language={language} snapshot={management} mutable onRefresh={async () => undefined}+ onPrepareKeyInput={async () => ({ candidate_ref: 'input/saved', candidate_revision: 1 })}+ onPreview={async () => { throw new Error('Credential editing is outside this fixture'); }}+ onApply={async () => 'saved'} onDiscardProtectedInputs={() => undefined} />+ {open && <ModelConnectionForm language={language} initialDraft={initial} expectedRevisions={readyManagement.revisions} mutable backend={backend}+ appendTo={appendTo} existingNames={params.has('occupied') ? ['百炼 · Token Plan', '百炼 · Token Plan · 2'] : []}+ onBack={() => setOpen(false)} onCancel={() => setOpen(false)} onSaveAccepted={() => undefined}+ onSaveResult={() => setOpen(false)} onSaveUncertain={() => setOpen(false)} restoreFocus={() => undefined} />}+ </PresentationRoot>;+}+createRoot(document.getElementById('root')!).render(<Harness />);diff --git a/apps/desktop/tests/v3/browser/main.tsx b/apps/desktop/tests/v3/browser/main.tsxindex d09f3cca..c8d6f313 100644--- a/apps/desktop/tests/v3/browser/main.tsx+++ b/apps/desktop/tests/v3/browser/main.tsx@@ -89,12 +89,16 @@ function Harness() {if (capture === 'api_failure') {clickButton('添加模型');await wait(120);- clickButton('连接 API');+ clickButton('新建 API 接入');await wait(120);+ clickButton('百炼');+ await wait(40);+ clickButton('百炼 · 按量付费');+ await wait(40);const password = document.querySelector<HTMLInputElement>('.modal input[type="password"]');if (password) setNativeValue(password, 'fixture-secret');await wait(40);- clickButton('检查接入');+ clickButton('检查并继续');} else if (capture === 'all_candidates') {await wait(420);clickButton('添加模型');diff --git a/apps/desktop/tests/v3/browser/product-fixtures.ts b/apps/desktop/tests/v3/browser/product-fixtures.tsindex 6124a3d1..0c1ac317 100644--- a/apps/desktop/tests/v3/browser/product-fixtures.ts+++ b/apps/desktop/tests/v3/browser/product-fixtures.ts@@ -8,6 +8,8 @@ import type { SubscriptionCandidate, SubscriptionCheckResult } from '../../../srimport type { Draft, Plan } from '../../../src/plan-editor';import type { DesktopSnapshot } from '../../../src/product/home-projections';import { fixture as legacyHomeFixture } from '../../mvp16/browser/fixtures';+import connectionRegistry from '../../../../../assets/release-facts/current/bundle/connector-registry.json';+import modelProjection from '../../../../../assets/model-data/current/runtime-projection.json';export type ProductScenario = 'fresh' | 'ready' | 'collaboration' | 'gap' | 'configured_no_sessions' | 'drift' | 'cooling' | 'free_exhausted' | 'api_failure' | 'unknown_model' | 'agent_blocked' | 'task_cancelled';@@ -469,13 +471,15 @@ export function mockProductInvoke(command: string, payload: Record<string, any>connector_registry_digest: 'sha256:fixture-registry', model_data_digest: 'sha256:fixture-models',cross_reference_digest: 'sha256:fixture-cross-reference',},- options: [{- connection_option_id: 'bailian.payg.cn.v1', display_name: 'Bailian Pay As You Go China',- connector_id: 'connector.bailian.p0', connector_revision: 1,- endpoint_profile_id: 'endpoint.bailian.payg.cn.v1', endpoint_profile_revision: 1,- billing_class: 'paid', authentication: 'provider_api_key',- model_configuration_ids: ['model.bailian.qwen3-max-2026-01-23'],- }],+ options: connectionRegistry.connection_options.map(option => {+ const connector = connectionRegistry.connectors.find(item => item.connector_id === option.connector_id)!;+ const profile = connectionRegistry.endpoint_profiles.find(item => item.endpoint_profile_id === option.endpoint_profile_id)!;+ const template = modelProjection.connection_templates.find(item => item.connection_option_id === option.connection_option_id);+ return { ...option, authentication: connector.authentication, registered_check_available: option.origin !== 'agent_subscription',+ model_configuration_ids: [], endpoints: profile.protocol_endpoints.map(endpoint => ({ ...endpoint,+ authentication_semantics: template?.endpoint_defaults.find(item => item.protocol_endpoint_id === endpoint.protocol_endpoint_id)?.authentication_semantics ?? { kind: 'bearer' },+ })) };+ }),};if (command === 'compute_subscriptions') return { discovery_state: 'complete', candidates: [{...localSubscriptionCandidate,@@ -802,7 +806,7 @@ export function mockProductInvoke(command: string, payload: Record<string, any>candidate: {candidate: { candidate_ref: 'candidate/protected', candidate_revision: 2 },correlation: { candidate_ref: 'candidate/protected', edit_revision: draft.edit_revision, check_id: draft.check_id, input_digest: digest },- producer: 'native', provenance: registered ? 'registered' : 'user_configured', display_name: registered ? 'Bailian Pay As You Go China' : draft.display_name,+ producer: 'native', provenance: registered ? 'registered' : 'user_configured', display_name: draft.display_name,models: customUnknown ? declaredModels.map((model: any, index: number) => ({model_ref: `model-ref/custom-${index}`,upstream_model_id: model.upstream_model_id,diff --git a/apps/desktop/tests/v3/visual/connection-flow-active.mjs b/apps/desktop/tests/v3/visual/connection-flow-active.mjsnew file mode 100644index 00000000..fec69a5c--- /dev/null+++ b/apps/desktop/tests/v3/visual/connection-flow-active.mjs@@ -0,0 +1,235 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { connectPage, evaluate, waitFor } from './cdp-client.mjs';++const [port, base, output] = process.argv.slice(2);+const client = await connectPage(Number(port));+const keepAlive = setInterval(() => {}, 1000);+const results = [];+const screenshot = async name => {+ const shot = await client.send('Page.captureScreenshot', { format: 'png' });+ await writeFile(path.join(output, `${name}.png`), Buffer.from(shot.data, 'base64'));+};+const open = async (query = '', viewport = { width: 1200, height: 813 }, page = 'connection-flow.html') => {+ const url = `${base}${page}?${query}&run=${crypto.randomUUID()}`;+ await client.send('Page.enable'); await client.send('Runtime.enable');+ await client.send('Emulation.setDeviceMetricsOverride', { ...viewport, deviceScaleFactor: 1, mobile: false });+ await client.send('Page.navigate', { url });+ await waitFor(client, `location.href === ${JSON.stringify(url)} && document.readyState === 'complete'`);+ await evaluate(client, 'document.fonts.ready.then(() => true)');+ await waitFor(client, `document.querySelector('.connection-flow') && !document.querySelector('.oc-spinner')`);+};+const click = async (selector, text = '') => {+ const expression = `Array.from(document.querySelectorAll(${JSON.stringify(selector)})).find(item => item.getClientRects().length && !item.disabled && (!${JSON.stringify(text)} || item.textContent.trim() === ${JSON.stringify(text)} || item.querySelector('strong')?.textContent === ${JSON.stringify(text)}))`;+ await waitFor(client, `Boolean(${expression})`);+ const point = await evaluate(client, `(() => { const item = ${expression}; item.scrollIntoView({block:'center',behavior:'instant'}); const rect=item.getBoundingClientRect();return {x:rect.x+rect.width/2,y:rect.y+rect.height/2}; })()`);+ await client.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...point, button: 'left', clickCount: 1 });+ await client.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...point, button: 'left', clickCount: 1 });+};+const field = async (label, value) => {+ const selector = `Array.from(document.querySelectorAll('.field')).find(item => item.getClientRects().length && item.querySelector('.field-label,.sr-only')?.textContent === ${JSON.stringify(label)})?.querySelector('input,select')`;+ await waitFor(client, `Boolean(${selector})`);+ await evaluate(client, `(() => {const input=${selector};const prototype=input instanceof HTMLSelectElement?HTMLSelectElement.prototype:HTMLInputElement.prototype;Object.getOwnPropertyDescriptor(prototype,'value').set.call(input,${JSON.stringify(value)});input.dispatchEvent(new Event(input instanceof HTMLSelectElement?'change':'input',{bubbles:true}));})()`);+};+const provider = async name => {+ await click('.connection-provider-card', name);+ await waitFor(client, `document.querySelector('#mc-connection-form').getClientRects().length > 0`);+};+const backToCatalog = async () => {+ await click('.modal-foot button', '返回');+ await waitFor(client, `document.querySelectorAll('.connection-provider-card').length > 0`);+};+const run = async (name, task) => {+ const started = performance.now();+ try { await task(); results.push({ name, state: 'green', elapsedMs: performance.now() - started }); }+ catch (error) { await screenshot(`failure-${results.length}`).catch(() => undefined); results.push({ name, state: 'red', error: error.stack || String(error), elapsedMs: performance.now() - started }); }+};+try {+ await mkdir(output, { recursive: true });+ await run('complete branded directory, search, plans and free scope', async () => {+ await open();+ await waitFor(client, `Array.from(document.querySelectorAll('.connection-provider-card img')).every(image=>image.complete&&image.naturalWidth>0)`);+ const facts = await evaluate(client, `({count:document.querySelectorAll('.connection-provider-card').length,intro:document.querySelector('.connection-directory-intro').textContent,logos:Array.from(document.querySelectorAll('.connection-provider-card img')).every(image=>image.complete&&image.naturalWidth>0)})`);+ assert.equal(facts.count, 13); assert.match(facts.intro, /13.*18/); assert.ok(facts.logos);+ await screenshot('catalog');+ await field('搜索供应商或产品', 'Coding Plan');+ await waitFor(client, `document.querySelectorAll('.connection-provider-card').length === 4`);+ await evaluate(client, `(() => {const input=document.querySelector('input[type=search]');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(input,'');input.dispatchEvent(new Event('input',{bubbles:true}));})()`);+ await waitFor(client, `document.querySelectorAll('.connection-provider-card').length === 13`);+ await click('.connection-billing-filters button', '免费资源');+ await waitFor(client, `document.querySelectorAll('.connection-provider-card').length === 5`);+ await click('.connection-billing-filters button', '全部');+ await click('.connection-provider-card', '百炼3 种接入方式');+ await waitFor(client, `document.querySelectorAll('.connection-product-card').length === 3`);+ await screenshot('products');+ await click('.connection-product-card', '百炼 · Token Plan');+ await waitFor(client, `document.querySelector('#mc-connection-form').getClientRects().length > 0`);+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input:not([type=password])').value`), '百炼 · Token Plan');+ await open('kind=free');+ assert.equal(await evaluate(client, `document.querySelectorAll('.connection-provider-card').length`), 5);+ assert.equal(await evaluate(client, `document.querySelector('.connection-custom-entry')`), null);+ });+ await run('names and keys return to their own product; save uses the checked name', async () => {+ await open();+ await provider('Anthropic按量付费');+ await field('连接名称', '团队 · 生产'); await field('API Key', 'fixture-key-a');+ await screenshot('configuration');+ await backToCatalog(); await provider('DeepSeek按量付费');+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input[type=password]').value`), '');+ await field('连接名称', '个人 · 备用'); await field('API Key', 'fixture-key-b');+ await backToCatalog(); await provider('Anthropic按量付费');+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input:not([type=password])').value`), '团队 · 生产');+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input[type=password]').value === 'fixture-key-a'`), true);+ await click('.modal-foot button', '检查并继续');+ await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ assert.equal(await evaluate(client, `document.querySelector('.model-selection h3').textContent`), '团队 · 生产');+ assert.ok(await evaluate(client, `Array.from(document.querySelectorAll('.modal-foot button')).find(item=>item.textContent==='保存连接').disabled`));+ await click('.modal-foot button', '返回'); await backToCatalog(); await provider('DeepSeek按量付费');+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input[type=password]').value === 'fixture-key-b'`), true);+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.model-selection input[type=checkbox]');+ await screenshot('models');+ await click('.modal-foot button', '保存连接'); await waitFor(client, `!document.querySelector('.modal')`);+ const trace = await evaluate(client, 'window.connectionFlowTrace');+ assert.deepEqual(trace.registered, ['a', 'b']);+ assert.deepEqual(trace.checks.map(item => item.display_name), ['团队 · 生产', '个人 · 备用']);+ assert.notEqual(trace.checks[0].connection_option_id, trace.checks[1].connection_option_id);+ assert.notEqual(trace.checks[0].lineage_ref, trace.checks[1].lineage_ref);+ assert.ok(trace.checks.every(item => !('secret' in item) && item.inference_model_id === null));+ assert.equal(trace.saves.length, 1); assert.equal(trace.saves[0].selected_model_refs.length, 1);+ assert.deepEqual(trace.released, ['input/1']);+ assert.ok(await evaluate(client, `Array.from(document.querySelectorAll('.row-meta')).some(item=>item.textContent.includes('个人 · 备用'))`));+ });+ await run('name is required and editing it invalidates the old checked selection', async () => {+ await open(); await provider('Anthropic按量付费');+ await field('连接名称', ' '); await field('API Key', 'fixture-key-a');+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('[data-error-code=MODEL_CONNECTION_NAME_REQUIRED]'))`);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.checks.length'), 0);+ await field('连接名称', '第一次'); await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.model-selection input[type=checkbox]'); await click('.modal-foot button', '返回');+ await field('连接名称', '修改后'); await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ const trace = await evaluate(client, 'window.connectionFlowTrace');+ assert.deepEqual(trace.checks.map(item=>item.display_name), ['第一次', '修改后']);+ assert.equal(trace.registered.length, 1);+ assert.ok(await evaluate(client, `Array.from(document.querySelectorAll('.modal-foot button')).find(item=>item.textContent==='保存连接').disabled`));+ });+ await run('custom no-auth and manual model declarations remain usable', async () => {+ await open('kind=custom');+ await field('连接名称', '本地模型'); await field('Base URL', 'http://127.0.0.1:51234/v1');+ await click('summary', '高级设置展开'); await field('认证方式', 'none');+ await waitFor(client, `!document.querySelector('#mc-connection-form input[type=password]')`);+ await click('#mc-connection-form button', '手工维护模型');+ await waitFor(client, `Boolean(document.querySelector('#mc-manual-form'))`);+ await field('模型 ID', 'local-test-model');+ await click('.modal-foot button', '检查并保存'); await waitFor(client, `!document.querySelector('.modal')`);+ const trace = await evaluate(client, 'window.connectionFlowTrace');+ assert.equal(trace.registered.length, 0); assert.equal(trace.saves.length, 1);+ assert.equal(trace.checks[0].draft.authentication.kind, 'none');+ assert.equal(trace.checks[0].draft.models[0].upstream_model_id, 'local-test-model');+ assert.equal(trace.checks[0].draft.display_name, '本地模型');+ });+ await run('cancel preserves the credential and ignores late check results', async () => {+ await open('hold_check=1'); await provider('Anthropic按量付费');+ await field('连接名称', '取消后继续'); await field('API Key', 'fixture-key-a');+ await click('.modal-foot button', '检查并继续');+ await waitFor(client, 'window.connectionFlowTrace.checks.length === 1');+ await click('.modal-foot button', '取消检查');+ await waitFor(client, `document.querySelector('#mc-connection-form').getClientRects().length > 0`);+ await evaluate(client, 'window.finishConnectionFlowCheck()');+ await field('连接名称', '继续检查'); await click('.modal-foot button', '检查并继续');+ await waitFor(client, 'window.connectionFlowTrace.checks.length === 2');+ await evaluate(client, 'window.finishConnectionFlowCheck()');+ await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ assert.equal(await evaluate(client, `document.querySelector('.model-selection h3').textContent`), '继续检查');+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.registered.length'), 1);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.saves.length'), 0);+ });+ await run('close guards changed drafts and releases every unsaved product credential', async () => {+ await open('kind=custom'); await click('.modal-head button');+ await waitFor(client, `!document.querySelector('.modal') && !document.querySelector('.discard-dialog')`);+ await open(); await provider('Anthropic按量付费'); await field('API Key', 'fixture-key-a');+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.modal-foot button', '返回'); await backToCatalog(); await provider('DeepSeek按量付费'); await field('API Key', 'fixture-key-b');+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.modal-head button'); await waitFor(client, `Boolean(document.querySelector('.discard-dialog'))`);+ await click('.discard-dialog button', '继续编辑');+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.released.length'), 0);+ await click('.modal-head button'); await click('.discard-dialog button', '放弃修改');+ await waitFor(client, `!document.querySelector('.modal')`);+ assert.deepEqual((await evaluate(client, 'window.connectionFlowTrace.released')).sort(), ['input/1', 'input/2']);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.saves.length'), 0);+ });+ await run('existing names are distinguished before any credential or check request', async () => {+ await open('occupied=1');+ await click('.connection-provider-card', '百炼3 种接入方式');+ await click('.connection-product-card', '百炼 · Token Plan');+ await waitFor(client, `document.querySelector('#mc-connection-form').getClientRects().length > 0`);+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input:not([type=password])').value`), '百炼 · Token Plan · 3');+ await field('连接名称', '百炼 · Token Plan'); await field('API Key', 'fixture-key-a');+ await click('.modal-foot button', '检查并继续');+ await waitFor(client, `Boolean(document.querySelector('[data-error-code=CONNECTION_NAME_CONFLICT]'))`);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.registered.length'), 0);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.checks.length'), 0);+ assert.ok(await evaluate(client, `document.querySelector('#mc-connection-form input[type=password]').value === 'fixture-key-a'`));+ });+ await run('a selected model remains selected after an explicit tool check', async () => {+ await open(); await provider('Anthropic按量付费'); await field('API Key', 'fixture-key-a');+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.model-selection input[type=checkbox]');+ await click('.model-selection button');+ await waitFor(client, `window.connectionFlowTrace.checks.length === 2 && Boolean(document.querySelector('.model-selection')) && !document.querySelector('.oc-spinner')`);+ assert.equal(await evaluate(client, `document.querySelectorAll('.model-selection input:checked').length`), 1);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.registered.length'), 1);+ assert.equal(await evaluate(client, 'window.connectionFlowTrace.saves.length'), 0);+ assert.ok(await evaluate(client, 'window.connectionFlowTrace.checks[1].inference_model_id'));+ });+ await run('append keeps saved configuration locked and preserves disabled state', async () => {+ await open('append=1');+ assert.equal(await evaluate(client, 'document.querySelectorAll(".connection-provider-card").length'), 0);+ assert.ok(await evaluate(client, `Array.from(document.querySelectorAll('#mc-connection-form input, #mc-connection-form select')).every(item=>item.matches(':disabled'))`));+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input:not([type=password])').value`), '已有 · 接入');+ await click('.modal-foot button', '检查并继续'); await waitFor(client, `Boolean(document.querySelector('.model-selection'))`);+ await click('.model-selection input[type=checkbox]'); await click('.modal-foot button', '保存连接');+ await waitFor(client, `!document.querySelector('.modal')`);+ const trace = await evaluate(client, 'window.connectionFlowTrace');+ assert.equal(trace.registered.length, 0);+ assert.equal(trace.saves.length, 1);+ assert.equal(trace.saves[0].edit.action, 'append_models');+ assert.equal(trace.saves[0].intent, 'save_disabled');+ assert.deepEqual(trace.saves[0].key_edits, []);+ assert.equal(trace.saves[0].selected_model_refs.length, 1);+ });+ await run('maximum text size fits the minimum window in both languages', async () => {+ for (const lang of ['zh', 'en']) {+ await open(`lang=${lang}&scale=2`, { width: 755, height: 600 });+ await click('.connection-custom-entry');+ await field(lang === 'zh' ? '连接名称' : 'Connection name', '团队模型服务 Team model service — production');+ await click('.connection-details .disclosure-label', lang === 'zh' ? '高级设置' : 'Advanced settings');+ await click('.modal-foot button', lang === 'zh' ? '检查并继续' : 'Check and continue');+ await waitFor(client, `Boolean(document.querySelector('[data-error-code=MODEL_CONNECTION_FIELDS_REQUIRED]'))`);+ const rect = await evaluate(client, `(() => {const dialog=document.querySelector('.modal').getBoundingClientRect(),footer=document.querySelector('.modal-foot').getBoundingClientRect();return {left:dialog.left,right:dialog.right,bottom:footer.bottom,viewport:innerWidth,height:innerHeight,overflow:document.querySelector('.modal-body').scrollWidth-document.querySelector('.modal-body').clientWidth};})()`);+ assert.ok(rect.left >= 0 && rect.right <= rect.viewport + 1 && rect.bottom <= rect.height + 1 && rect.overflow <= 1, JSON.stringify(rect));+ await screenshot(`maximum-text-${lang}`);+ }+ });+ await run('dialog, footer and branding fit narrow layouts in both themes', async () => {+ for (const width of [320, 736, 1280]) for (const theme of ['light', 'dark']) {+ await open(`lang=en&theme=${theme}`, { width, height: 813 });+ const rect = await evaluate(client, `(() => {const dialog=document.querySelector('.modal').getBoundingClientRect(),footer=document.querySelector('.modal-foot').getBoundingClientRect();return {left:dialog.left,right:dialog.right,bottom:footer.bottom,viewport:innerWidth,height:innerHeight,overflow:document.querySelector('.modal-body').scrollWidth-document.querySelector('.modal-body').clientWidth};})()`);+ assert.ok(rect.left >= 0 && rect.right <= rect.viewport + 1 && rect.bottom <= rect.height + 1 && rect.overflow <= 1, JSON.stringify(rect));+ await screenshot(`catalog-${width}-${theme}`);+ }+ });+ await run('the model page failure capture follows the real add-API entry and retains its draft', async () => {+ await open('page=models&scenario=api_failure&capture=api_failure', { width: 1200, height: 813 }, 'index.html');+ await waitFor(client, `Boolean(document.querySelector('[data-error-code=MODEL_CONNECTION_AUTHENTICATION_REJECTED]'))`);+ assert.equal(await evaluate(client, `document.querySelector('#mc-connection-form input:not([type=password])').value`), '百炼 · 按量付费');+ assert.ok(await evaluate(client, `document.querySelector('#mc-connection-form input[type=password]').placeholder.includes('••')`));+ await screenshot('api-failure');+ });+ const report = { evidence: 'Production React components and mock IPC; native effects are a separate acceptance gate', tests: results.length, passed: results.filter(item=>item.state==='green').length, results };+ await writeFile(path.join(output, 'report.json'), JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+ if (report.passed !== report.tests) process.exitCode = 1;+} finally { clearInterval(keepAlive); client.close(); }diff --git a/apps/desktop/tests/v3/visual/connection-flow.mjs b/apps/desktop/tests/v3/visual/connection-flow.mjsnew file mode 100644index 00000000..0dc0d9c5--- /dev/null+++ b/apps/desktop/tests/v3/visual/connection-flow.mjs@@ -0,0 +1,70 @@+import { spawn } from 'node:child_process';+import { mkdtemp, mkdir, rm } from 'node:fs/promises';+import net from 'node:net';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const here = path.dirname(fileURLToPath(import.meta.url));+const desktopRoot = path.resolve(here, '../../..');+const outputRoot = path.resolve(process.argv[2] ?? path.join(desktopRoot, 'test-results/v3-connection-flow'));++const availablePort = () => new Promise((resolve, reject) => {+ const server = net.createServer();+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ const address = server.address();+ const port = typeof address === 'object' && address ? address.port : 0;+ server.close(error => error ? reject(error) : resolve(port));+ });+});+const waitFor = async (url, timeout = 15_000) => {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ try { if ((await fetch(url)).ok) return; } catch {}+ await new Promise(resolve => setTimeout(resolve, 80));+ }+ throw new Error(`Timed out waiting for ${url}`);+};+const terminate = async child => {+ if (!child?.pid) return;+ try { process.kill(-child.pid, 'SIGTERM'); } catch {}+ await Promise.race([+ new Promise(resolve => child.once('exit', resolve)),+ new Promise(resolve => setTimeout(resolve, 1500)),+ ]);+};+const removeProfile = async directory => {+ for (let attempt = 0; attempt < 5; attempt += 1) {+ try { await rm(directory, { recursive: true, force: true }); return; } catch (error) {+ if (attempt === 4) throw error;+ await new Promise(resolve => setTimeout(resolve, 120));+ }+ }+};+const waitForExit = child => new Promise((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', (code, signal) => resolve({ code, signal }));+});++const httpPort = await availablePort();+let cdpPort = await availablePort();+while (cdpPort === httpPort) cdpPort = await availablePort();+const profile = await mkdtemp(path.join(os.tmpdir(), 'hiroute-v3-connection-flow-'));+await mkdir(outputRoot, { recursive: true });+let vite;+let chrome;+try {+ vite = spawn(path.join(desktopRoot, 'node_modules/.bin/vite'), ['tests/v3/browser', '--host', '127.0.0.1', '--port', String(httpPort), '--strictPort'], { cwd: desktopRoot, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ await waitFor(`http://127.0.0.1:${httpPort}/`);+ const chromeExecutable = process.env.CHROME_BIN || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : 'google-chrome');+ chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ await waitFor(`http://127.0.0.1:${cdpPort}/json/version`);+ const runner = spawn(process.execPath, [path.join(here, 'connection-flow-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot], { cwd: desktopRoot, stdio: 'inherit' });+ const outcome = await waitForExit(runner);+ if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;+} finally {+ await terminate(chrome);+ await terminate(vite);+ await removeProfile(profile);+}diff --git a/crates/application-api/src/model_connections.rs b/crates/application-api/src/model_connections.rsindex 0aa93177..3496b1b8 100644--- a/crates/application-api/src/model_connections.rs+++ b/crates/application-api/src/model_connections.rs@@ -136,6 +136,8 @@ pub struct RegisteredModelConnectionCheckRequestV1 {#[serde(default)]pub models: Vec<NativeUserModelDeclarationV1>,pub connection_option_id: String,+ /// User-visible label only; product identity and execution facts remain catalog-owned.+ pub display_name: String,pub expected_catalog: crate::ComputeCatalogProvenanceViewV1,#[serde(default, skip_serializing_if = "Option::is_none")]pub candidate_ref: Option<String>,@@ -180,6 +182,7 @@ impl RegisteredModelConnectionCheckRequestV1 {&& !value.contains('\0')};bounded(&self.connection_option_id)+ && bounded(&self.display_name)&& self.candidate_ref.as_ref().is_none_or(|candidate_ref| {bounded(candidate_ref) && candidate_ref == &self.input_candidate.candidate_ref})@@ -472,6 +475,7 @@ mod tests {inference_model_id: None,models: Vec::new(),connection_option_id: "bailian.payg.cn.v1".into(),+ display_name: "团队百炼".into(),expected_catalog: crate::ComputeCatalogProvenanceViewV1 {product_release: "release-v1".into(),catalog_binding_id: "client-bundled/current".into(),@@ -493,6 +497,19 @@ mod tests {};assert!(request.valid());let encoded = serde_json::to_value(&request).unwrap();+ let mut missing_name = encoded.clone();+ missing_name.as_object_mut().unwrap().remove("display_name");+ assert!(+ serde_json::from_value::<RegisteredModelConnectionCheckRequestV1>(missing_name)+ .is_err()+ );+ for name in ["", " ", " trailing ", "bad\0name"] {+ request.display_name = name.into();+ assert!(!request.valid());+ }+ request.display_name = "x".repeat(257);+ assert!(!request.valid());+ request.display_name = "团队百炼".into();for forbidden in ["base_url","billing_class",diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rsindex 6544bb7a..4601352c 100644--- a/crates/client-core/tests/transport.rs+++ b/crates/client-core/tests/transport.rs@@ -275,6 +275,7 @@ async fn registered_model_check_uses_the_protected_closed_operation() {inference_model_id: None,models: Vec::new(),connection_option_id: "bailian.payg.cn.v1".into(),+ display_name: "Team Bailian".into(),expected_catalog: ComputeCatalogProvenanceViewV1 {product_release: "mvp-current".into(),catalog_binding_id: "fixture-catalog".into(),diff --git a/crates/daemon/src/control/runtime/model_connections/registered.rs b/crates/daemon/src/control/runtime/model_connections/registered.rsindex 2799617b..d4adb28c 100644--- a/crates/daemon/src/control/runtime/model_connections/registered.rs+++ b/crates/daemon/src/control/runtime/model_connections/registered.rs@@ -161,7 +161,7 @@ impl LocalControlAdapter {candidate_ref: request.candidate_ref.clone(),lineage_ref: request.lineage_ref.clone(),trusted_lineage_digest: None,- display_name: resolved.option.display_name.clone(),+ display_name: request.display_name.clone(),existing_source_id: request.existing_source_id.clone(),edit_revision: request.edit_revision,check_id: request.check_id.clone(),@@ -390,6 +390,7 @@ mod tests {inference_model_id: None,models: Vec::new(),connection_option_id: connection_option_id.into(),+ display_name: "团队 API".into(),expected_catalog: ComputeCatalogProvenanceViewV1 {product_release: provenance.product_release,catalog_binding_id: provenance.catalog_binding_id,@@ -536,6 +537,7 @@ mod tests {.adapter.trusted_registered_draft(&request(&catalog, "deepseek.official.global.v1")).unwrap();+ assert_eq!(deepseek.display_name, "团队 API");assert_eq!(deepseek.base_url, "https://api.deepseek.com");assert_eq!(deepseek.inventory_path_override.as_deref(), Some("/models"));assert_eq!(deepseek.protocol, UpstreamProtocol::Responses);diff --git a/crates/daemon/src/control/runtime/model_connections/saved.rs b/crates/daemon/src/control/runtime/model_connections/saved.rsindex b26fdd42..27930bbe 100644--- a/crates/daemon/src/control/runtime/model_connections/saved.rs+++ b/crates/daemon/src/control/runtime/model_connections/saved.rs@@ -108,6 +108,7 @@ impl LocalControlAdapter {inference_model_id: None,models: Vec::new(),connection_option_id: connection_option_id.clone(),+ display_name: source.display_name.clone(),expected_catalog: ComputeCatalogProvenanceViewV1 {product_release: provenance.product_release,catalog_binding_id: provenance.catalog_binding_id,@@ -413,6 +414,7 @@ mod tests {inference_model_id: None,models: Vec::new(),connection_option_id: "bailian.payg.cn.v1".into(),+ display_name: "团队百炼 · 生产".into(),expected_catalog: ComputeCatalogProvenanceViewV1 {product_release: provenance.product_release,catalog_binding_id: provenance.catalog_binding_id,@@ -795,6 +797,7 @@ mod tests {.adapter.saved_registered_draft(&saved, &source, &candidate).unwrap();+ assert_eq!(before_restart.display_name, "团队百炼 · 生产");assert_eq!(before_restart.trusted_lineage_digest,Some(source.lineage_digest.clone())@@ -823,6 +826,7 @@ mod tests {.adapter.saved_registered_draft(&saved, &source, &candidate).unwrap();+ assert_eq!(after_restart.display_name, before_restart.display_name);assert_eq!(after_restart.base_url, before_restart.base_url);assert_eq!(after_restart.models, before_restart.models);assert_eq!(@@ -856,6 +860,7 @@ mod tests {.adapter.saved_registered_draft(&saved, &catalog_a_source, &candidate).unwrap();+ assert_eq!(upgraded.display_name, before_restart.display_name);assert_eq!(upgraded.base_url, before_restart.base_url);assert!(matches!(upgraded.provenance,diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex 75907400..1c09bbff 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -34,6 +34,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi| User step | Owners to follow | Representative guard || --- | --- | --- |+| Add an API connection and choose its models | [Connection directory](../../apps/desktop/src/features/model-connections/ConnectionDirectory.tsx), [form and draft ownership](../../apps/desktop/src/features/model-connections/README.md), [registered check](../../crates/daemon/src/control/runtime/model_connections/registered.rs) | The executable catalog supplies the complete directory. A source name survives check/save; per-product credentials stay in the dialog and protected input. || Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs) | Static declarations and supported credential references only; OAuth/helpers are not executed by discovery || Display, prepare and save the selected source | [Safe Desktop projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Provider/model identity remains visible; privileged scan material stays private; source changes invalidate the prepared candidate || Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. |