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
fix: preserve Unicode model IDs in routing options (#78)
澄潭4b7b98785193
diff --git a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsxindex f47350db..d9aef10c 100644--- a/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx+++ b/apps/desktop/src/features/model-connections/ModelConnectionForm.tsx@@ -42,6 +42,7 @@ import {connectionErrorMessage,ManualModelEditor,manualModelError,+ manualModelIdError,registeredConnectionLabel,safeConnectionErrorCode,validEndpoint,@@ -78,6 +79,10 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const password = useRef<HTMLInputElement>(null);const errorFeedback = useRef<HTMLDivElement>(null);const draftRef = useRef(draft);+ // Only saved, catalog-prefilled or backend-observed IDs bypass the temporary+ // manual ASCII policy. Editing a draft never adds its input to this set.+ const preservedModelIds = useRef(new Set(props.initialDraft.existing_source_id+ ? props.initialDraft.models.map(model => model.upstream_model_id) : []));const protectedInputRef = useRef<ComputeCandidateRef | null>(null);const activeCheckRef = useRef<string | null>(null);const applyDispatchedRef = useRef(false);@@ -146,6 +151,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const protocol = endpoint?.protocol ?? (provider.protocol_candidates.includes(draftRef.current.protocol)? draftRef.current.protocol : provider.protocol_candidates[0]);const candidates = catalog ? metadataProviderCandidates(provider, catalog, registeredOptions) : [];+ for (const candidate of candidates) preservedModelIds.current.add(candidate.upstream_model_id);const records = new Map(catalog?.model_records.filter(model =>model.provider_record_key === provider.provider_record_key&& model.usable_for.includes('custom-api-model-prefill')@@ -189,6 +195,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {const endpoint = [...(option.endpoints ?? [])].sort((a, b) => a.stable_preference - b.stable_preference)[0];if (!endpoint) return;const candidates = registeredModelCandidates(option, connectionOptions?.metadata_catalog);+ for (const candidate of candidates) preservedModelIds.current.add(candidate.upstream_model_id);const otherProtocols = new Set<UpstreamProtocol>();const additional_endpoints = [...(option.endpoints ?? [])].sort((a, b) => a.stable_preference - b.stable_preference)@@ -374,6 +381,13 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {? [...base.models, blankModel(inferenceModelId)] : base.models;const current = { ...base, inference_model_id: inferenceModelId,models: selectedModels.map(withCapabilityFallback) };+ const allowedIds = new Set([...preservedModelIds.current,+ ...(!custom ? registeredCandidates.map(model => model.upstream_model_id) : [])]);+ // Check every route to the backend, including returning to connection check+ // from the manual editor, before registering credentials or sending inference.+ const idError = current.models.filter(model => model.upstream_model_id !== '')+ .map(model => manualModelIdError(model.upstream_model_id, allowedIds)).find(Boolean);+ if (idError) { setError(idError); return; }const passwordElement = password.current;const enteredSecret = passwordElement?.value ?? '';const connectionReady = custom@@ -388,7 +402,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {return;}if (saveAfterCheck) {- const validation = (new Set(current.models.map(model => model.upstream_model_id.trim())).size !== current.models.length ? 'MODEL_ID_DUPLICATE' : '') || current.models.map(manualModelError).find(Boolean) || (!current.models.length ? 'MODEL_ID_REQUIRED' : '');+ const validation = (new Set(current.models.map(model => model.upstream_model_id)).size !== current.models.length ? 'MODEL_ID_DUPLICATE' : '') || current.models.map(model => manualModelError(model, allowedIds)).find(Boolean) || (!current.models.length ? 'MODEL_ID_REQUIRED' : '');if (validation) { setError(validation); return; }}const checkId = clientOperationId('check');@@ -420,7 +434,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {}): await backend.checkRegisteredModelConnection({inference_model_id: inferenceModelId,- models: checkingDraft.models.filter(model => model.upstream_model_id.trim()).map(({ client_id: _clientId, ...model }) => ({ ...model, display_name: model.display_name.trim() || model.upstream_model_id })),+ 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,expected_catalog: connectionOptions!.catalog,candidate_ref: checkingDraft.candidate_ref,@@ -450,6 +464,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {setPhase('editing');return;}+ for (const model of checked.candidate.models) preservedModelIds.current.add(model.upstream_model_id);const selectable = checked.candidate.models.filter(model => model.selectable);if (saveAfterCheck) {await saveChecked(checked, selectable.filter(model => checkingDraft.models.some(declared => declared.upstream_model_id === model.upstream_model_id)).map(model => model.model_ref));@@ -684,7 +699,7 @@ export function ModelConnectionForm(props: ModelConnectionFormProps) {</form>{screen === 'manual' && <form id="mc-manual-form" onSubmit={event => { event.preventDefault(); void runCheck(true); }}>- {draft.models.map(model => <div key={model.client_id}><ManualModelEditor model={model} language={language} disabled={!props.mutable} catalogManaged={!custom && Object.hasOwn(registeredOption?.known_models ?? {}, model.upstream_model_id.trim())} onChange={updateManualModel} /><button className="btn btn-quiet" type="button" onClick={() => invalidate(current => ({ ...current, models: current.models.filter(value => value.client_id !== model.client_id) }), false, 'manual')}>{zh ? '移除模型' : 'Remove model'}</button></div>)}+ {draft.models.map(model => <div key={model.client_id}><ManualModelEditor model={model} language={language} disabled={!props.mutable} catalogManaged={!custom && Object.hasOwn(registeredOption?.known_models ?? {}, model.upstream_model_id)} onChange={updateManualModel} /><button className="btn btn-quiet" type="button" onClick={() => invalidate(current => ({ ...current, models: current.models.filter(value => value.client_id !== model.client_id) }), false, 'manual')}>{zh ? '移除模型' : 'Remove model'}</button></div>)}<button className="btn" type="button" onClick={() => invalidate(current => ({ ...current, models: [...current.models, blankModel()] }), false, 'manual')}>{zh ? '添加模型 ID' : 'Add model ID'}</button></form>}diff --git a/apps/desktop/src/features/model-connections/form-support.tsx b/apps/desktop/src/features/model-connections/form-support.tsxindex 56ac0fd4..68232d35 100644--- a/apps/desktop/src/features/model-connections/form-support.tsx+++ b/apps/desktop/src/features/model-connections/form-support.tsx@@ -33,6 +33,8 @@ export function connectionErrorMessage(code: string, zh: boolean): string {? '请完整填写模型能力;不支持的能力也需要明确选择。': 'Complete every model capability, including capabilities that are not supported.';if (code === 'MODEL_ID_DUPLICATE') return zh ? '同一接入中的模型 ID 不能重复。' : 'Model IDs must be unique within this connection.';+ if (code === 'MODEL_ID_ASCII_REQUIRED') return zh ? '手工填写的模型 ID 只能使用 ASCII 字符(英文字母、数字和符号)。中文名称请填写在“模型名称”中;已有或目录提供的模型 ID 可原样保留。' : 'Manually entered model IDs must use ASCII letters, numbers and symbols. Put a localized name in Model name; existing or catalog-provided IDs can be kept unchanged.';+ if (code === 'MODEL_ID_INVALID') return zh ? '模型 ID 不能包含控制字符或首尾空白,且不能超过 512 字节。' : 'Model IDs cannot contain control characters or surrounding whitespace and must fit within 512 UTF-8 bytes.';if (code === 'MODEL_ID_REQUIRED') return zh ? '请填写服务使用的模型 ID。' : 'Enter the model ID used by the service.';if (code === 'MODEL_LIMITS_INVALID') return zh? '上下文和输出上限需为正整数,且输出不能超过上下文。'@@ -109,8 +111,18 @@ export function reasoningValue(};}-export function manualModelError(model: ModelDeclaration | undefined): string {- if (!model?.upstream_model_id.trim()) return 'MODEL_ID_REQUIRED';+export function manualModelIdError(id: string, preservedIds: ReadonlySet<string> = new Set()): string {+ if (!id || /^\p{White_Space}+$/u.test(id)) return 'MODEL_ID_REQUIRED';+ // Keep the backend's byte/control bounds, even for preserved opaque IDs.+ if (/^\p{White_Space}|\p{White_Space}$/u.test(id) || new TextEncoder().encode(id).length > 512 || /[\p{Cc}\uD800-\uDFFF]/u.test(id)) return 'MODEL_ID_INVALID';+ // Temporary Desktop entry policy. This does not narrow the backend contract.+ if (/[^\x00-\x7f]/.test(id) && !preservedIds.has(id)) return 'MODEL_ID_ASCII_REQUIRED';+ return '';+}++export function manualModelError(model: ModelDeclaration | undefined, preservedIds: ReadonlySet<string> = new Set()): string {+ const idError = manualModelIdError(model?.upstream_model_id ?? '', preservedIds);+ if (idError || !model) return idError;const context = model.capabilities.context_tokens.value;const output = model.capabilities.max_output_tokens.value;if ((context !== null && (!Number.isSafeInteger(context) || context <= 0)) || (output !== null && (!Number.isSafeInteger(output) || output <= 0)) || (context !== null && output !== null && output > context)) return 'MODEL_LIMITS_INVALID';@@ -155,8 +167,8 @@ export function ManualModelEditor({ model, language, disabled, catalogManaged =return <fieldset className="connection-fields manual-capability-fields" disabled={disabled}><p className="v3-select-intro">{zh- ? '填写模型 ID 即可接入基础文字。缺少能力资料时采用表单中的可编辑兜底值。'- : 'A model ID is enough for basic text. Missing capability facts use the editable defaults shown below.'}</p>+ ? '手工填写的模型 ID 请使用 ASCII 字符;中文名称可填写在“模型名称”中。已有或目录提供的 ID 可原样保留。'+ : 'Use ASCII characters for manually entered model IDs and Model name for localized names. Existing or catalog-provided IDs can be kept unchanged.'}</p><label className="field"><span className="field-label">{zh ? '模型 ID' : 'Model ID'}</span><input className="input" data-autofocus value={model.upstream_model_id} placeholder="my-model" onChange={event => onChange({ ...model, upstream_model_id: event.target.value, display_name: model.display_name === model.upstream_model_id ? event.target.value : model.display_name })} /></label>{catalogManaged ? <p className="field-help">{zh? '此模型采用内置目录的名称和能力。如需修改,请返回连接信息,选择“自定义此模板的连接配置”。'diff --git a/apps/desktop/src/features/model-connections/state.ts b/apps/desktop/src/features/model-connections/state.tsindex 440047a8..2c3a8256 100644--- a/apps/desktop/src/features/model-connections/state.ts+++ b/apps/desktop/src/features/model-connections/state.ts@@ -54,7 +54,7 @@ export function buildCheckDraft(draft: ModelConnectionDraft): ModelConnectionDrareturn {...wireDraft,configuration_revision: provenance.configuration_revision,- models: models.filter(model => model.upstream_model_id.trim()).map(({ client_id: _clientId, ...model }) => ({ ...model, display_name: model.display_name.trim() || model.upstream_model_id })),+ models: models.filter(model => model.upstream_model_id).map(({ client_id: _clientId, ...model }) => ({ ...model, display_name: model.display_name.trim() || model.upstream_model_id })),};}@@ -216,7 +216,7 @@ export function withRegisteredModels(candidates: ReadonlyArray<Pick<ModelDeclaration, 'upstream_model_id' | 'display_name'> &{ capability_prefill?: ModelDeclaration['capabilities'] }>,): ModelDeclaration[] {- const ids = new Set(models.map(model => model.upstream_model_id.trim()));+ const ids = new Set(models.map(model => model.upstream_model_id));return [...models, ...candidates.filter(candidate => !ids.has(candidate.upstream_model_id)).map(candidate => candidate.capability_prefill? { ...blankModel(candidate.upstream_model_id, candidate.display_name), capabilities: candidate.capability_prefill }diff --git a/apps/desktop/src/plan-candidate-availability.ts b/apps/desktop/src/plan-candidate-availability.tsnew file mode 100644index 00000000..7c6422c0--- /dev/null+++ b/apps/desktop/src/plan-candidate-availability.ts@@ -0,0 +1,16 @@+export type UnavailableCandidate = { binding_id: string; display_name: string; reason: string };++/** Closed backend reasons only; never display a provider error or credential-bearing payload. */+export function candidateUnavailableMessage(reason: string, language: 'zh' | 'en'): string {+ const messages: Record<string, [string, string]> = {+ invalid_model_id: ['模型 ID 格式不受支持,请在模型页面核对上游实际 ID。', 'Unsupported model ID. Check the upstream model ID on the Models page.'],+ source_not_ready: ['接入已停用或尚未就绪,请在模型页面启用或完成接入。', 'The connection is disabled or not ready. Enable or complete it on the Models page.'],+ model_not_eligible: ['当前来源尚未授权此模型执行,请重新检查接入。', 'This source does not currently authorize this model. Recheck the connection.'],+ catalog_mismatch: ['已保存接入与当前供应商目录不兼容,请重新检查接入。', 'The saved connection is incompatible with the current provider catalog. Recheck it.'],+ credential_unavailable: ['接入缺少可用凭据或授权,请在模型页面处理。', 'The connection needs credentials or authorization. Update it on the Models page.'],+ runtime_unavailable: ['订阅执行服务暂不可用,请检查订阅接入后重试。', 'The subscription runtime is unavailable. Check the subscription connection and retry.'],+ capability_unavailable: ['缺少路由所需的能力资料,请检查模型配置。', 'Required routing capability data is missing. Check the model configuration.'],+ invalid_configuration: ['当前接入配置无法用于路由,请在模型页面检查模型和协议设置。', 'This connection cannot be prepared for routing. Check its model and protocol settings on the Models page.'],+ };+ return (messages[reason] ?? messages.invalid_configuration)[language === 'zh' ? 0 : 1];+}diff --git a/apps/desktop/src/plan-editor-errors.ts b/apps/desktop/src/plan-editor-errors.tsindex 37bd8ee4..3547ae0d 100644--- a/apps/desktop/src/plan-editor-errors.ts+++ b/apps/desktop/src/plan-editor-errors.ts@@ -14,6 +14,7 @@ export function planErrorMessage(error: unknown, language: 'zh' | 'en'): stringQODER_MODEL_BUDGET_CONFLICT: ['新预算低于 Qoder 当前已接入模型声明的容量。请先在 Agent 页面停用 Qoder 的模型路由,再发布此计划并重新配置模型路由;任务协作无需停用。当前输入已保留。', 'The new budget is below the capacity declared by the current Qoder model connection. Disable Qoder model routing on the Agent page, publish this plan, then configure model routing again. Task collaboration can stay enabled. Your input is retained.'],PLAN_HEAD_STALE: ['当前路由已在其他地方发布新版本。你的输入已保留,请读取当前生效配置后重新编辑。', 'A newer route version was published elsewhere. Your input is retained; reload the active route before editing again.'],DRAFT_REVISION_STALE: ['该草稿已在其他地方更新或移除。你的输入已保留,请读取最新草稿和生效配置后重试。', 'This draft was updated or removed elsewhere. Your input is retained; reload the latest draft and active route before retrying.'],+ RESIDENT_UNAVAILABLE: ['暂时无法连接本机服务,当前输入已保留。请稍后重试。', 'Cannot connect to the local service. Your input is retained. Try again.'],DAEMON_UNAVAILABLE: ['暂时无法连接本机服务,当前输入已保留。请稍后重试。', 'Cannot connect to the local service. Your input is retained. Try again.'],RESPONSE_DATA_INVALID: ['未能读取操作结果,当前输入已保留。请先核实路由状态再重试。', 'Could not read the operation result. Your input is retained. Check the route state before retrying.'],};diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsxindex 267d890a..f0b11146 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -1,3 +1,4 @@+import { candidateUnavailableMessage, type UnavailableCandidate } from './plan-candidate-availability';import type { OpenDecisionConnection } from './features/decision-services/presentation';import { BranchRoutingEditor, FollowUpPreference } from './features/decision-services/BranchRoutingEditor';import { branchRouting, branchSelections, classifierIssue, judgmentIssue, defaultJudgment, emptyService, routingIssue, type Judgment, type BranchRouting, type Classifier, type DecisionService } from './features/decision-services/types';@@ -37,7 +38,7 @@ type CodexCapabilityIssue = { kind: 'plan_compilation' | 'invalid_compiled_plan'type CodexCapabilities = { state: 'available'; context_window: number; input_modalities: ('text' | 'image')[]; reasoning: 'route_configuration'; limitations: CodexCapabilityLimit[]; fixed_limits: ('parallel_tool_calls_disabled')[] }| { state: 'unavailable'; issues: CodexCapabilityIssue[] };export type ClaudeCapabilities = { state: 'available'; context_window: number; plan_window: number } | { state: 'unavailable'; reason: string };-export type Options = { claude_capabilities?: ClaudeCapabilities | null; context_window: ContextWindowBounds | null; suggested_alias: string | null; candidates: Candidate[]; free_suggestions: { candidates: { selection: Selection }[]; unavailable: Record<string, string> } | null; codex_capabilities: CodexCapabilities | null };+export type Options = { unavailable_candidate_count?: number; unavailable_candidates?: UnavailableCandidate[]; claude_capabilities?: ClaudeCapabilities | null; context_window: ContextWindowBounds | null; suggested_alias: string | null; candidates: Candidate[]; free_suggestions: { candidates: { selection: Selection }[]; unavailable: Record<string, string> } | null; codex_capabilities: CodexCapabilities | null };type ValidationIssue = { selector?: string; message: string; group?: string; bindingId?: string; field?: 'alias' | 'context_window' | 'request_timeout' };export type PlanEditorHandle = {saveDraft(): Promise<boolean>;@@ -125,9 +126,12 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drconst memory = useRef(editingMemory ?? {}).current;const [moreSettingsOpen, setMoreSettingsOpen] = useState(editor.delegation_enabled);const [optionsError, setOptionsError] = useState('');+ const [optionsErrorCode, setOptionsErrorCode] = useState('');const [optionsRetry, setOptionsRetry] = useState(0);const [effort, setEffort] = useState<{ name: string; native: Native; value: Selection['reasoning']; apply: (value: Selection['reasoning']) => void } | null>(null);const [picker, setPicker] = useState<{ title: string; values: Selection[]; replace: (values: Selection[]) => void; free: boolean; preferred?: 'low' | 'high' } | null>(null);+ const unavailable = options?.unavailable_candidates ?? [];+ const candidateIssue = (id: string) => unavailable.find(item => item.binding_id === id);const [sources, setSources] = useState<Record<string, string>>({});const [sourceOptions, setSourceOptions] = useState<Record<string, string | null>>({});const dirty = JSON.stringify(editor) !== baseline;@@ -166,20 +170,13 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drlet current = true;const timer = setTimeout(async () => {try {- const value = await invoke<Options>('plan_editor_options', { input: { display_name: editor.display_name, requirements: editor.requirements, editor } });- if (current) { setOptions(value); setOptionsError(''); }- } catch {- try {- const management = await invoke<{ sources: { models: unknown[] }[] }>('compute_management_snapshot');- if (!current) return;- if (!management.sources.some(source => source.models.length > 0)) {- setOptions({ context_window: null, suggested_alias: null, candidates: [], free_suggestions: null, codex_capabilities: null });- setOptionsError('');- } else {- setOptionsError(text('暂时无法读取可用于路由的模型,当前编辑已保留。', 'Unable to read routable models. Your edits are preserved.'));- }- } catch {- if (current) setOptionsError(text('暂时无法读取可用于路由的模型,当前编辑已保留。', 'Unable to read routable models. Your edits are preserved.'));+ const value = await invoke<Options>('plan_editor_options', { input: { display_name: editor.display_name, requirements: editor.requirements, editor, include_unavailable: true } });+ if (current) { setOptions(value); setOptionsError(''); setOptionsErrorCode(''); }+ } catch (cause) {+ if (current) {+ setOptions(null);+ setOptionsError(planErrorMessage(cause, language));+ setOptionsErrorCode(planErrorCode(cause));}}}, 200);@@ -226,7 +223,7 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drif (!group.values.length) return { group: group.id, message: text('请为每个启用的模型组合添加模型。', 'Add a model to each enabled group.') };for (const selection of group.values) {const candidate = options.candidates.find(item => item.binding_id === selection.binding_id);- if (!candidate || !candidate.routable) return { group: group.id, bindingId: selection.binding_id, message: text('所选模型当前不可用于路由,请更换模型。', 'A selected model is not currently routable. Choose another model.') };+ if (!candidate || !candidate.routable) return { group: group.id, bindingId: selection.binding_id, message: candidateIssue(selection.binding_id) ? candidateUnavailableMessage(candidateIssue(selection.binding_id)!.reason, language) : text('所选模型当前不可用于路由,请更换模型。', 'A selected model is not currently routable. Choose another model.') };if (group.free && candidate.billing_class !== 'free') return { group: group.id, bindingId: selection.binding_id, message: text('免费组合只能使用明确免费的模型。', 'The free group accepts only verified free models.') };if (editor.delegation_enabled && editor.work && !candidate.ingress_protocols.includes(editor.work.protocol)) return { group: group.id, bindingId: selection.binding_id, message: text(`“${candidate.display_name}”不支持所选执行 Agent 的协议,请更换模型或执行 Agent。`, `“${candidate.display_name}” does not support the selected execution agent protocol. Choose another model or agent.`) };const native = candidate.reasoning;@@ -380,12 +377,13 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drreturn <section className={`route-lane${primary ? ' primary' : ''}${validationIssue?.group === groupId ? ' invalid' : ''}`} data-route-group={groupId}><div className="lane-head"><div><strong>{title}</strong><span>{subtitle}</span></div><span className="badge no-dot">{values.length}</span></div><div className="candidate-list">{values.map((s, index) => {const c = candidates.find(c => c.binding_id === s.binding_id);const put = (reasoning: Selection['reasoning']) => replace(values.map((v, i) => i === index ? { ...v, reasoning } : v));- const displayName = c?.display_name ?? (options ? text('不可用模型', 'Unavailable model') : text('正在读取模型…', 'Loading model…'));+ const issue = candidateIssue(s.binding_id);+ const displayName = c?.display_name ?? issue?.display_name ?? (options ? text('不可用模型', 'Unavailable model') : text('正在读取模型…', 'Loading model…'));return <div className={`candidate-row route-candidate${validationIssue?.bindingId === s.binding_id ? ' invalid' : ''}`} data-binding-id={s.binding_id} key={s.binding_id}><span className="drag-handle" aria-hidden="true"><UiIcon name="grip" /></span><span className="candidate-index">{index + 1}</span><ProviderIcon optionId={sourceOptions[s.binding_id]} language={language} />- <div className="candidate-main"><strong>{displayName}</strong><span>{billing(c?.billing_class)} · {sources[s.binding_id] ?? text('来源暂不可得', 'Source unavailable')}{c && !c.routable ? text(' · 当前不可用', ' · Unavailable') : ''}</span></div>+ <div className="candidate-main"><strong>{displayName}</strong><span>{billing(c?.billing_class)} · {sources[s.binding_id] ?? text('来源暂不可得', 'Source unavailable')}{c && !c.routable ? text(' · 当前不可用', ' · Unavailable') : ''}</span>{issue && <span className="oc-inline-error">{candidateUnavailableMessage(issue.reason, language)}</span>}</div>{reasoningControl(s, c, put)}<div className="candidate-controls"><button type="button" className="icon-btn" disabled={index === 0} aria-label={text('上移', 'Move up')} onClick={() => move(index, -1)}><UiIcon name="arrowUp" /></button><button type="button" className="icon-btn" disabled={index === values.length - 1} aria-label={text('下移', 'Move down')} onClick={() => move(index, 1)}><UiIcon name="arrowDown" /></button><button type="button" className="icon-btn" aria-label={text('删除', 'Remove')} onClick={() => replace(values.filter((_, i) => i !== index))}><UiIcon name="trash" /></button></div></div>;@@ -402,7 +400,7 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr</div>}<fieldset disabled={busy}><div hidden={!!plan && view !== 'configuration'}><section className="editor-section"><div className="editor-section-heading"><div><h3>{text('这份智能路由用来做什么', 'What this routing is for')}</h3><p>{text('Agent 根据用途选择适合任务的路由。', 'Your Agent uses this description to choose a route.')}</p></div></div><div className="plan-identity-fields"><label><span className="sr-only">{text('名称', 'Name')}</span><input className="input" autoFocus={creating} required placeholder={text('名称,例如:代码实现', 'Name, e.g. Code implementation')} aria-invalid={invalidFields && !editor.display_name.trim()} aria-describedby={invalidFields && !editor.display_name.trim() ? "route-name-error" : undefined} value={editor.display_name} maxLength={128} onChange={e => update({ display_name: e.target.value })} />{invalidFields && !editor.display_name.trim() && <span id="route-name-error" className="oc-inline-error">{text('请填写路由名称', 'Enter a route name')}</span>}</label><label><span className="sr-only">{text('使用场景', 'Purpose')}</span><input className="input" required placeholder={text('使用场景:适合做什么,期望交付什么', 'Purpose: tasks and expected results')} maxLength={512} aria-invalid={invalidFields && !editor.purpose.trim()} aria-describedby={invalidFields && !editor.purpose.trim() ? "route-purpose-error" : undefined} value={editor.purpose} onChange={e => update({ purpose: e.target.value })} />{invalidFields && !editor.purpose.trim() && <span id="route-purpose-error" className="oc-inline-error">{text('请填写使用场景', 'Enter a purpose')}</span>}</label></div><div className="field plan-alias"><label><span className="field-label">{text('接入模型名', 'Connection model name')}</span><input className="input plan-alias-field" readOnly={!!plan} value={editor.custom_alias ?? options?.suggested_alias ?? ''} placeholder="hiroute-…" maxLength={64} aria-invalid={validationIssue?.field === 'alias'} onChange={e => update({ custom_alias: e.target.value })} /></label><span className="field-help">{text('在 Agent 中使用此名称调用这条智能路由。创建后保持稳定。', 'Use this name in an Agent to call the smart route. It remains stable after creation.')}</span>{validationIssue?.field === 'alias' && <span className="oc-inline-error">{validationIssue.message}</span>}{!plan && editor.custom_alias !== undefined && <button className="btn" type="button" onClick={() => update({ custom_alias: undefined })}>{text('恢复自动名称', 'Use automatic name')}</button>}</div></section>- <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('怎样使用模型', 'How to use models')}</h3></div></div>{optionsError && <div className="callout warn route-local-error" role="alert"><UiIcon name="warning" /><span>{optionsError}</span><button className="btn" type="button" onClick={() => setOptionsRetry(value => value + 1)}>{text('重试', 'Retry')}</button></div>}<div className="mode-switcher plan-mode-switcher">{(['fixed_model', 'smart_saving', 'custom_branches', 'free_first'] as Mode[]).map((m, i) => <button className={`mode-card${editor.mode === m ? ' active' : ''}`} type="button" aria-pressed={editor.mode === m} key={m} onClick={() => changeMode(m)}><strong>{text(['固定模型', '智能省钱', '自定义分支', '免费优先'][i], ['Fixed model', 'Smart saving', 'Custom branches', 'Free first'][i])}</strong><span>{text(['按固定顺序依次尝试候选模型', '简单任务用省钱组合,复杂任务用主力组合', '按自己的任务条件选择分支和模型', '先用免费模型,可选择主力兜底'][i], ['Try candidate models in a fixed order', 'Economy for simple tasks; primary for complex work', 'Choose branches and models by your task conditions', 'Use free models first, with optional primary fallback'][i])}</span></button>)}</div></section>+ <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('怎样使用模型', 'How to use models')}</h3></div></div>{optionsError && <div className="callout warn route-local-error" role="alert" data-error-code={optionsErrorCode}><UiIcon name="warning" /><span>{optionsError}</span><button className="btn" type="button" onClick={() => setOptionsRetry(value => value + 1)}>{text('重试', 'Retry')}</button></div>}{!optionsError && options && !options.candidates.some(candidate => candidate.routable) && <p className="field-help" role="status">{unavailable.length ? text('已接入的模型当前不可用于路由,请查看下方原因并在模型页面处理。', 'Connected models are currently unavailable for routing. Review the reasons below and update them on the Models page.') : text('还没有可用于路由的模型,请先在模型页面接入模型。', 'No routable models yet. Connect a model on the Models page.')}</p>}{!optionsError && unavailable.length > 0 && <Disclosure className="route-unavailable-models" language={language} label={text(`不可用模型(${unavailable.length})`, `Unavailable models (${unavailable.length})`)}>{options?.unavailable_candidate_count && <p>{text(`共 ${options.unavailable_candidate_count} 个不可用模型,此处显示前 ${unavailable.length} 个。可在模型页面查看并处理全部接入。`, `${options.unavailable_candidate_count} models are unavailable; showing the first ${unavailable.length}. Review all connections on the Models page.`)}</p>}<ul>{unavailable.map(item => <li key={item.binding_id}><strong>{item.display_name}</strong> — {candidateUnavailableMessage(item.reason, language)}</li>)}</ul></Disclosure>}<div className="mode-switcher plan-mode-switcher">{(['fixed_model', 'smart_saving', 'custom_branches', 'free_first'] as Mode[]).map((m, i) => <button className={`mode-card${editor.mode === m ? ' active' : ''}`} type="button" aria-pressed={editor.mode === m} key={m} onClick={() => changeMode(m)}><strong>{text(['固定模型', '智能省钱', '自定义分支', '免费优先'][i], ['Fixed model', 'Smart saving', 'Custom branches', 'Free first'][i])}</strong><span>{text(['按固定顺序依次尝试候选模型', '简单任务用省钱组合,复杂任务用主力组合', '按自己的任务条件选择分支和模型', '先用免费模型,可选择主力兜底'][i], ['Try candidate models in a fixed order', 'Economy for simple tasks; primary for complex work', 'Choose branches and models by your task conditions', 'Use free models first, with optional primary fallback'][i])}</span></button>)}</div></section>{editor.mode === 'fixed_model' && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('固定模型顺序', 'Fixed model order')}</h3><p>{text('HiRoute 按此顺序尝试;不满足能力或暂时不可用的模型会被跳过。', 'HiRoute tries this order, skipping models that cannot satisfy the request or are temporarily unavailable.')}</p></div></div>{group(text('候选模型', 'Candidate models'), text('发布后保持此顺序', 'Keep this order after publication'), editor.candidates, candidates => update({ candidates }), { groupId: 'fixed' })}</section>}{editor.mode === 'smart_saving' && <><DecisionSelector classifier={editor.smart.classifier} smart services={services} language={language} onChange={classifier => update({ smart: { ...editor.smart, classifier } })} onOpenServices={onOpenServices} error={validationIssue?.group === 'classifier' ? validationIssue.message : undefined} />@@ -451,20 +449,26 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drdescription={editor.display_name}language={language}single={false}+ showUnavailablevalue={picker.values.map(value => value.binding_id)}- items={(options?.candidates ?? []).map(candidate => ({+ items={[...(options?.candidates ?? []).map(candidate => ({id: candidate.binding_id,optionId: sourceOptions[candidate.binding_id],name: candidate.display_name,source: `${billing(candidate.billing_class)} · ${sources[candidate.binding_id] ?? text('来源暂不可得', 'Source unavailable')}`,unavailable: !candidate.routable- ? text('当前模型不可用', 'Model unavailable')+ ? candidateUnavailableMessage(candidateIssue(candidate.binding_id)?.reason ?? 'invalid_configuration', language): picker.free && candidate.billing_class !== 'free'? text('不符合免费组条件', 'Not eligible for the free group'): editor.delegation_enabled && editor.work && !candidate.ingress_protocols.includes(editor.work.protocol)? text('不支持所选执行 Agent', 'Incompatible with selected execution agent'): undefined,- }))}+ })), ...unavailable.filter(item => !options?.candidates.some(candidate => candidate.binding_id === item.binding_id)).map(item => ({+ id: item.binding_id, name: item.display_name,+ optionId: sourceOptions[item.binding_id],+ source: sources[item.binding_id] ?? text('来源暂不可得', 'Source unavailable'),+ unavailable: candidateUnavailableMessage(item.reason, language),+ }))]}onClose={() => setPicker(null)}onApply={ids => {const selections = ids.map<Selection>(id => {diff --git a/apps/desktop/src/ui/ModelPicker.tsx b/apps/desktop/src/ui/ModelPicker.tsxindex 2a9d34e7..308aff2c 100644--- a/apps/desktop/src/ui/ModelPicker.tsx+++ b/apps/desktop/src/ui/ModelPicker.tsx@@ -6,13 +6,14 @@ import { UiIcon } from './UiIcon';export type ModelChoice = { id: string; name: string; source: string; optionId?: string | null; unavailable?: string };/** Selection belongs to the caller's draft, never to the filtered list. */-export function ModelPicker({ title, description, language, items, value, single = false, onApply, onClose }: {+export function ModelPicker({ title, description, language, items, value, single = false, showUnavailable = false, onApply, onClose }: {title: string;description?: string;language: 'zh' | 'en';items: ModelChoice[];value: string[];single?: boolean;+ showUnavailable?: boolean;onApply(ids: string[]): void;onClose(): void;}) {@@ -20,7 +21,7 @@ export function ModelPicker({ title, description, language, items, value, singleconst [query, setQuery] = useState('');const needle = query.trim().toLocaleLowerCase();const eligible = items.filter(item => !item.unavailable);- const remaining = eligible.filter(item => !value.includes(item.id));+ const remaining = (showUnavailable ? items : eligible).filter(item => !value.includes(item.id));const visible = remaining.filter(item => `${item.name} ${item.source}`.toLocaleLowerCase().includes(needle));return <Dialog open title={title} closeLabel={text('关闭候选模型', 'Close candidates')} onClose={onClose}description={description}@@ -29,8 +30,8 @@ export function ModelPicker({ title, description, language, items, value, single<div className="native-list v3-catalog catalog-picker">{visible.map(item => <div className="list-row" key={item.id}><ProviderIcon optionId={item.optionId} language={language} />- <span className="row-main"><span className="row-title">{item.name}</span><span className="row-meta">{item.source}</span></span>- <button className="btn btn-primary" type="button" onClick={() => onApply(single ? [item.id] : [...value, item.id])}>{text(single ? '选择' : '添加', single ? 'Select' : 'Add')}</button>+ <span className="row-main"><span className="row-title">{item.name}</span><span className="row-meta">{item.source}</span>{item.unavailable && <span className="row-meta">{item.unavailable}</span>}</span>+ <button className="btn btn-primary" type="button" disabled={Boolean(item.unavailable)} onClick={() => onApply(single ? [item.id] : [...value, item.id])}>{text(single ? '选择' : '添加', single ? 'Select' : 'Add')}</button></div>)}{!visible.length && <div className="empty-state" role="status"><div><span className="empty-icon"><UiIcon name="models" /></span><h3>{needle ? text('没有匹配项', 'No matches') : remaining.length === 0 && eligible.length ? text('可用模型已全部加入', 'All available models have been added') : text('还没有符合条件的模型', 'No eligible models yet')}</h3><p>{needle ? text('试试其他名称或来源。', 'Try another name or source.') : eligible.length ? text('关闭后可以调整候选顺序。', 'Close to adjust the candidate order.') : text('先连接一个满足要求的模型。', 'Connect a model that meets the requirements.')}</p></div></div>}</div>diff --git a/apps/desktop/tests/model-connections-state.test.mjs b/apps/desktop/tests/model-connections-state.test.mjsindex 82bffe1e..217294c6 100644--- a/apps/desktop/tests/model-connections-state.test.mjs+++ b/apps/desktop/tests/model-connections-state.test.mjs@@ -14,6 +14,7 @@ import {selectedModelRefsAfterRecheck,blankModel,withCapabilityFallback,+ withRegisteredModels,} from '../src/features/model-connections/state.ts';test('tool recheck keeps explicit model identities with fresh refs and drops unavailable choices', () => {@@ -95,6 +96,35 @@ test('native user check maps UI provenance to the exact public wire draft', () =assert.equal('qualification' in wire, false);});+test('native check keeps opaque provider IDs distinct from display text and normalization', () => {+ const ids = ['内网模型', '外网模型', 'Vendor/Model@2026?revision#1', 'Model A',+ 'é', 'e\u0301', '\ufeff模型\ufeff', '\ufeff', '模型🧠', '🧠'.repeat(128), '界'.repeat(170) + 'ab'];+ const draft = {+ entry_kind: 'custom_api', provenance: { kind: 'user_configured', configuration_revision: 1 },+ qualification: { free_access: null, evidence_ref: null },+ models: ids.map(id => blankModel(id, '中文显示名称')),+ };+ const wire = buildCheckDraft(draft);+ assert.deepEqual(wire.models.map(model => model.upstream_model_id), ids);+ assert.ok(wire.models.every(model => model.display_name === '中文显示名称'));+ assert.equal(new Set(wire.models.map(model => model.upstream_model_id)).size, ids.length);+ assert.equal(new TextEncoder().encode(wire.models.at(-1).upstream_model_id).length, 512);+});++test('registered model joins deduplicate only exact IDs and retain a distinct FEFF-prefixed model', () => {+ const prefixed = blankModel('\ufeff模型', '已编辑名称');+ const models = withRegisteredModels([prefixed], [+ { upstream_model_id: '\ufeff模型', display_name: '重复目录名称' },+ { upstream_model_id: '模型', display_name: '无前缀名称' },+ { upstream_model_id: '模型\ufeff', display_name: '有后缀名称' },+ ]);+ assert.deepEqual(models.map(model => model.upstream_model_id), ['\ufeff模型', '模型', '模型\ufeff']);+ assert.equal(models[0], prefixed);+ assert.deepEqual(models.map(model => model.display_name), ['已编辑名称', '无前缀名称', '有后缀名称']);+ const added = withRegisteredModels([], [{ upstream_model_id: '\ufeff', display_name: '仅有格式字符的 ID' }]);+ assert.equal(buildCheckDraft({ provenance: { kind: 'user_configured', configuration_revision: 1 }, models: added }).models[0].upstream_model_id, '\ufeff');+});+test('native check preserves every endpoint and the saved-source edit revision', () => {const draft = {entry_kind: 'custom_api', provenance: { kind: 'user_configured', configuration_revision: 2 },diff --git a/apps/desktop/tests/v3/browser/manual-model-ids.html b/apps/desktop/tests/v3/browser/manual-model-ids.htmlnew file mode 100644index 00000000..d8647299--- /dev/null+++ b/apps/desktop/tests/v3/browser/manual-model-ids.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="zh-CN">+<head><meta charset="UTF-8" /><title>Model ID entry — rendered form regression</title></head>+<body><div id="root"></div><div id="form-root"></div><script type="module" src="./manual-model-ids.tsx"></script></body>+</html>diff --git a/apps/desktop/tests/v3/browser/manual-model-ids.tsx b/apps/desktop/tests/v3/browser/manual-model-ids.tsxnew file mode 100644index 00000000..daaaf438--- /dev/null+++ b/apps/desktop/tests/v3/browser/manual-model-ids.tsx@@ -0,0 +1,128 @@+import { useState } from 'react';+import { createRoot } from 'react-dom/client';+import { ModelConnectionForm } from '../../../src/features/model-connections/ModelConnectionForm';+import { blankModel } from '../../../src/features/model-connections/state';+import { newModelConnectionDraft } from '../../../src/product/ModelManagementPage';+import { PresentationRoot } from '../../../src/ui';+import type { ModelConnectionBackend, ModelConnectionCheckRequest, ModelConnectionDraft, ModelConnectionCheckView } from '../../../src/features/model-connections/types';+import '../../../src/occami/styles.css';++const assert: (condition: unknown, message: string) => asserts condition = (condition, message) => {+ if (!condition) throw new Error(message);+};+const tick = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+async function until(predicate: () => boolean, label: string) {+ const deadline = Date.now() + 5000;+ while (!predicate()) {+ if (Date.now() > deadline) throw new Error(`Timed out: ${label}`);+ await new Promise(resolve => setTimeout(resolve, 20));+ }+ await tick();+}+function button(text: string) {+ const found = [...document.querySelectorAll<HTMLButtonElement>('button')].find(item => item.textContent?.trim() === text);+ assert(found, `Missing button ${text}`);+ return found;+}+function input(index: number, value: string) {+ const element = document.querySelectorAll<HTMLInputElement>('#mc-manual-form input')[index];+ assert(element, `Missing input ${index}`);+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(element, value);+ element.dispatchEvent(new Event('input', { bubbles: true }));+}+const digest: `sha256:${string}` = `sha256:${'a'.repeat(64)}`;+const operation = { operation_id: 'operation/test', state: 'succeeded' as const, sequence: 1, cancellable: false };++async function mounted(existingId: string | null, observedId: string | null, run: (trace: { checks: ModelConnectionCheckRequest[]; protectedInputs: number; saves: number }) => Promise<void>) {+ const trace = { checks: [] as ModelConnectionCheckRequest[], protectedInputs: 0, saves: 0 };+ const draft: ModelConnectionDraft = { ...newModelConnectionDraft(), display_name: '本地模型服务',+ base_url: 'https://example.invalid/v1', authentication: { kind: 'none' },+ ...(existingId ? { existing_source_id: 'source/existing', expected_source_revision: 1, models: [blankModel(existingId, '原有名称')] } : {}),+ };+ const backend: ModelConnectionBackend = {+ async listConnectionOptions() { return { schema: 'fixture', catalog: { product_release: 'fixture', catalog_binding_id: 'fixture', release_sequence: 1, connector_registry_digest: digest, model_data_digest: digest, cross_reference_digest: digest }, options: [] }; },+ async registerProtectedInput() { trace.protectedInputs++; return { input_candidate: { candidate_ref: 'input/test', candidate_revision: 1 } }; },+ async releaseProtectedInput() {},+ async cancelModelConnectionCheck() {},+ async checkRegisteredModelConnection() { throw new Error('Unexpected registered connection'); },+ async checkModelConnection(request) {+ trace.checks.push(structuredClone(request));+ const models = request.draft.models.length ? request.draft.models : observedId ? [blankModel(observedId, '目录模型')] : [];+ return {+ candidate: { candidate: { candidate_ref: 'candidate/test', candidate_revision: 1 },+ correlation: { candidate_ref: 'candidate/test', edit_revision: request.draft.edit_revision, check_id: request.draft.check_id, input_digest: digest },+ producer: 'native', provenance: 'user_configured', display_name: request.draft.display_name,+ fact_state: 'complete', input_state: 'not_required',+ models: models.map((model, index) => ({ model_ref: `model/${index}`, upstream_model_id: model.upstream_model_id,+ display_name: model.display_name, membership: observedId ? 'observed' : 'user_declared', fact_basis: 'user_declared', selectable: true })),+ },+ target: { scheme: 'https', authority: 'example.invalid', port: 443, request_path: '/v1/chat/completions', upstream_protocol: 'chat_completions', protocol_profile_id: 'profile/test', protocol_profile_revision: 1 },+ inventory_path: '/v1/models', reachability: 'reachable', authentication: 'not_required', directory: 'available', protocol: 'selected', inference: 'not_run',+ checked_model_count: models.length, invalid_model_count: 0, pages_read: 1, checked_at_unix_ms: 1, input_digest: digest,+ } satisfies ModelConnectionCheckView;+ },+ async previewComputeSave(change) { return { spec: { schema_version: { major: 1, minor: 0 }, command_id: 'fixture-save', desired_state: change }, accept_digest: digest, expected_revisions: change.expected_revisions, changes: [], affected_plan_refs: [] }; },+ async applyComputeSave() { trace.saves++; return { result: { operation_id: operation.operation_id, accepted_digest: digest, state: 'succeeded' }, operation }; },+ async getComputeSaveResult() { return { disposition: 'saved', bindings: [], source_id: 'source/test' }; },+ };+ const root = createRoot(document.getElementById('form-root')!);+ root.render(<PresentationRoot language="zh" theme="light" textScale={1}><ModelConnectionForm+ language="zh" mutable initialDraft={draft} expectedRevisions={{ target: 0, dependencies: {} }} backend={backend}+ onBack={() => {}} onCancel={() => {}} onSaveAccepted={() => {}} onSaveResult={() => {}} onSaveUncertain={() => {}} restoreFocus={() => {}}+ /></PresentationRoot>);+ try { await until(() => Boolean(document.querySelector('#mc-connection-form')), 'connection form'); await run(trace); }+ finally { root.unmount(); await tick(); }+}++const scenarios: [string, () => Promise<void>][] = [+ ['manual IDs reject new Unicode before check/save, preserve input and recover with ASCII', () => mounted(null, null, async trace => {+ button('手工维护模型').click(); await tick();+ input(0, '中文模型'); await tick(); input(1, '中文显示名称'); await tick();+ button('保存接入').click();+ await until(() => Boolean(document.querySelector('[data-error-code="MODEL_ID_ASCII_REQUIRED"]')), 'ASCII entry explanation');+ assert(document.querySelector('[role="alert"]')?.textContent?.includes('模型名称'), 'Error did not explain the name field');+ assert(trace.checks.length === 0 && trace.protectedInputs === 0 && trace.saves === 0, 'Rejected input reached the backend');+ assert(document.querySelector<HTMLInputElement>('#mc-manual-form input')?.value === '中文模型', 'Rejected input was discarded');+ button('返回').click(); await tick(); button('检查接入').click(); await tick();+ assert(trace.checks.length === 0, 'Returning to connection check bypassed manual validation');+ button('手工维护模型').click(); await tick(); input(0, 'vendor/model-v1'); await tick(); button('保存接入').click();+ await until(() => trace.saves === 1, 'corrected ASCII save');+ assert(trace.checks[0].draft.models[0].upstream_model_id === 'vendor/model-v1', 'ASCII correction changed');+ assert(trace.checks[0].draft.models[0].display_name === '中文显示名称', 'Localized display name changed');+ })],+ ['saved Unicode ID permits name edits but not a new non-ASCII replacement', () => mounted('旧模型\ufeff', null, async trace => {+ button('手工维护模型').click(); await tick(); input(0, '另一个模型'); await tick(); button('保存接入').click();+ await until(() => Boolean(document.querySelector('[data-error-code="MODEL_ID_ASCII_REQUIRED"]')), 'new replacement rejected');+ assert(trace.checks.length === 0 && trace.saves === 0, 'Changed Unicode ID inherited the saved exception');+ input(0, '旧模型\ufeff'); await tick(); input(1, '更新后的中文名称'); await tick(); button('保存接入').click();+ await until(() => trace.saves === 1, 'unchanged existing ID saved');+ assert(trace.checks[0].draft.models[0].upstream_model_id === '旧模型\ufeff', 'Existing ID normalized or changed');+ assert(trace.checks[0].draft.models[0].display_name === '更新后的中文名称', 'Name edit was blocked');+ })],+ ['directory-provided Unicode ID remains editable and saveable', () => mounted(null, '目录模型🧠', async trace => {+ button('检查接入').click();+ await until(() => Boolean(document.querySelector('.model-result-row')), 'observed catalog');+ document.querySelector<HTMLInputElement>('.model-result-row input[type="checkbox"]')!.click(); await tick();+ button('编辑所选模型 / 添加模型').click(); await tick(); input(1, '自定义目录名称'); await tick(); button('保存接入').click();+ await until(() => trace.saves === 1, 'observed Unicode save');+ assert(trace.checks[1].draft.models[0].upstream_model_id === '目录模型🧠', 'Observed ID rejected or rewritten');+ assert(trace.checks[1].draft.models[0].display_name === '自定义目录名称', 'Observed model name edit lost');+ })],+];++function Harness() {+ const [running, setRunning] = useState(false);+ const [results, setResults] = useState<{ name: string; state: string; error?: string }[]>([]);+ async function run() {+ setRunning(true); const next = [];+ for (const [name, scenario] of scenarios) {+ try { await scenario(); next.push({ name, state: 'green' }); }+ catch (error) { next.push({ name, state: 'red', error: error instanceof Error ? error.message : String(error) }); }+ }+ setResults(next); setRunning(false);+ }+ return <><p>Rendered production form with a recording backend fixture; not native/Tauri or live-provider acceptance.</p>+ <button data-run-tests disabled={running} onClick={() => void run()}>Run checks</button>+ <pre data-test-results>{JSON.stringify({ tests: results.length, passed: results.filter(row => row.state === 'green').length, failed: results.filter(row => row.state === 'red').length, results }, null, 2)}</pre></>;+}+createRoot(document.getElementById('root')!).render(<Harness />);diff --git a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx b/apps/desktop/tests/v3/browser/plan-editor-ux.tsxindex c9223d7b..14f33b92 100644--- a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx+++ b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx@@ -6,10 +6,16 @@ import { mockIPC } from '@tauri-apps/api/mocks';import type { Draft, Editor } from '../../../src/plan-editor';import { RoutingPage } from '../../../src/product/RoutingPage';import { PresentationRoot } from '../../../src/ui';+import { manualModelError } from '../../../src/features/model-connections/form-support';+import { blankModel } from '../../../src/features/model-connections/state';import { dailyPlan, fixtureTrace, mockProductInvoke, readyDesktop, resetFixtureTrace } from './product-fixtures';import '../../../src/occami/styles.css';const workerChecks = new URLSearchParams(location.search).get('checks') === 'workers';+const availabilityChecks = new URLSearchParams(location.search).get('checks') === 'availability';+let availabilityFailure = false;+let availabilityEmpty = false;+let unavailableRequested = false;const plan = structuredClone(dailyPlan);if (!workerChecks) { plan.desired.delegation_enabled = false; plan.desired.work = undefined; }const submitted: { action: string; editor: Editor }[] = [];@@ -23,6 +29,19 @@ mockIPC((command, payload) => {fixtureTrace.commands.push(command);return structuredClone(savedSnapshot);}+ if (command === 'plan_editor_options' && availabilityChecks) {+ unavailableRequested = (payload as { input?: { include_unavailable?: boolean } }).input?.include_unavailable === true;+ if (availabilityFailure) throw { source: 'backend', envelope: { error: { code: 'DAEMON_UNAVAILABLE', private: 'provider-secret-debug' } } };+ const current = mockProductInvoke(command, payload as Record<string, unknown>, 'ready') as Record<string, unknown>;+ return { ...current,+ ...(availabilityEmpty ? { candidates: [] } : {}),+ unavailable_candidates: availabilityEmpty ? [] : [+ { binding_id: 'binding/invalid-retained', display_name: '错误模型', reason: 'invalid_model_id' },+ { binding_id: 'binding/disabled-retained', display_name: '停用模型', reason: 'source_not_ready' },+ ],+ ...(availabilityEmpty ? {} : { unavailable_candidate_count: 257 }),+ };+ }if (command === 'preview_plan_editor') {fixtureTrace.commands.push(command);const request = input.input!;@@ -175,6 +194,63 @@ const checks: [string, () => Promise<void>][] = [}],];+const availabilityCases: [string, () => Promise<void>][] = [+ ['routing.options.id-safety: ASCII manual entry preserves exact existing and observed Unicode IDs', async () => {+ for (const id of ['gpt-6.1-sol', 'Vendor/Model@2026?revision#1', 'Model A', 'x'.repeat(512)]) {+ assert(manualModelError(blankModel(id, '中文名称')) === '', `ASCII ID was rejected: ${JSON.stringify(id)}`);+ }+ for (const id of ['内网模型', 'e\u0301', '\ufeff模型\ufeff', '\ufeff', '\u202emodel', '模型🧠', '🧠'.repeat(128), '界'.repeat(170) + 'ab']) {+ assert(manualModelError(blankModel(id, '中文名称')) === 'MODEL_ID_ASCII_REQUIRED', `New non-ASCII input was accepted: ${JSON.stringify(id)}`);+ const preserved = new Set([id]);+ assert(manualModelError(blankModel(id, '修改名称'), preserved) === '', `Existing ID was rejected: ${JSON.stringify(id)}`);+ assert(manualModelError(blankModel(`${id}改`, '名称'), preserved) !== '', 'A modified non-ASCII ID inherited the exception');+ }+ for (const id of [' bad', 'bad\u00a0', 'bad\u3000', 'bad\tmodel', 'bad\0model', 'bad\u0085model', '\u0085bad', 'bad\u0085', 'bad\ud800model', '\udfffbad', 'x'.repeat(513), '界'.repeat(171), '🧠'.repeat(129)]) {+ assert(manualModelError(blankModel(id, '中文名称'), new Set([id])) === 'MODEL_ID_INVALID', `Preservation bypassed safety bounds: ${JSON.stringify(id)}`);+ }+ }],+ ['routing.options.exclusions: rejected models remain visible with disabled selection and safe reasons', async () => {+ await until(() => Boolean(document.querySelector('.route-unavailable-models')), 'unavailable model explanations');+ assert(unavailableRequested, 'Route editor did not opt in to explanations');+ element<HTMLDetailsElement>('.route-unavailable-models').querySelector('summary')!.click();+ assert(element('.route-unavailable-models').textContent?.includes('共 257 个不可用模型'), 'Truncated explanations concealed their actual count');+ element<HTMLButtonElement>('.add-candidate').click();+ await until(() => Boolean(document.querySelector('.catalog-picker')), 'model picker');+ const rows = [...document.querySelectorAll<HTMLElement>('.catalog-picker .list-row')];+ const rejected = rows.filter(row => row.textContent?.includes('错误模型') || row.textContent?.includes('停用模型'));+ assert(rejected.length === 2, 'Unavailable candidate identities were silently omitted');+ const selected = document.querySelectorAll('.route-candidate').length;+ for (const row of rejected) {+ const add = row.querySelector<HTMLButtonElement>('button')!;+ assert(add.disabled, 'Unavailable candidate could be selected');+ assert(row.textContent?.includes('模型页面'), 'Unavailable candidate lost its actionable reason');+ add.click();+ }+ await tick();+ assert(document.querySelectorAll('.route-candidate').length === selected, 'Rejected selection changed the route');+ element<HTMLButtonElement>('button[aria-label="关闭候选模型"]').click();+ }],+ ['routing.options.service-error: visible retry preserves input and recovers after real error mapping', async () => {+ availabilityFailure = true;+ setInput('.plan-identity-fields input', '保留用户输入');+ await until(() => Boolean(document.querySelector('[data-error-code="DAEMON_UNAVAILABLE"]')), 'visible service failure');+ const alert = element('[data-error-code="DAEMON_UNAVAILABLE"]');+ assert(alert.textContent?.includes('本机服务'), 'Service error did not identify the unavailable service');+ assert(!alert.textContent?.includes('provider-secret-debug'), 'Backend error payload leaked into copy');+ assert(element<HTMLInputElement>('.plan-identity-fields input').value === '保留用户输入', 'Service error discarded user input');+ availabilityFailure = false;+ alert.querySelector<HTMLButtonElement>('button')!.click();+ await until(() => !document.querySelector('[data-error-code="DAEMON_UNAVAILABLE"]'), 'options retry recovery');+ }],+ ['routing.options.empty: no sources is readable and distinct from service failure', async () => {+ availabilityEmpty = true;+ setInput('.plan-identity-fields input', '无候选模型');+ await until(() => [...document.querySelectorAll('[role="status"]')].some(row => row.textContent?.includes('还没有可用于路由的模型')), 'empty source guidance');+ assert(!document.querySelector('.route-local-error'), 'Empty options were shown as a service error');+ assert(!document.querySelector('.route-unavailable-models'), 'Empty source list invented exclusions');+ }],+];+function Harness() {const [snapshot, setSnapshot] = useState(() => structuredClone(savedSnapshot));const [running, setRunning] = useState(false);@@ -190,7 +266,7 @@ function Harness() {return;}const next = [];- for (const [name, check] of checks) {+ for (const [name, check] of availabilityChecks ? availabilityCases : checks) {try { await check(); next.push({ name, state: 'green' }); }catch (error) { next.push({ name, state: 'red', error: error instanceof Error ? error.message : String(error) }); }}diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex a945d940..36af3f90 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -11,6 +11,7 @@ const shellOnly = process.argv[5] === '--shell-only';const routeSaveOnly = process.argv[5] === '--route-save-only';const workerReplacementOnly = process.argv[5] === '--worker-replacement-only';const claudeCollaborationOnly = process.argv[5] === '--claude-collaboration-only';+const routeOptionsOnly = process.argv[5] === '--route-options-only';if (!Number.isInteger(port) || !baseUrl || !process.argv[4]) {throw new Error('Usage: node agent-trust-active.mjs <cdp-port> <base-url> <output-directory>');}@@ -20,7 +21,7 @@ try {const client = await connectPage(port);try {const checks = [];- if (!shellOnly && !routeSaveOnly && !workerReplacementOnly) {+ if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !routeOptionsOnly) {await navigate(client, new URL('agent-trust.html', baseUrl).href, { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.agentTrust)', { timeout: 7000 });const catalog = await evaluate(client, "import('/agent-trust-scenarios.mjs').then(module => module.agentTrustScenarioCatalog)");@@ -39,7 +40,7 @@ try {assertScenarioResults(selected, results);checks.push(...results);}- if (!shellOnly && !claudeCollaborationOnly) {+ if (!shellOnly && !claudeCollaborationOnly && !routeOptionsOnly) {await navigate(client, new URL('?page=routing&scenario=ready', baseUrl).href, { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });const catalog = await evaluate(client, "import('/routing-worker-scenarios.mjs').then(module => module.routingWorkerScenarioCatalog)");@@ -53,7 +54,7 @@ try {process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);}}- if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly) {+ if (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly && !routeOptionsOnly) {await navigate(client, new URL('?page=models&scenario=ready', baseUrl).href, { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.__HIRouteFixtureTrace)', { timeout: 7000 });const fromModel = await evaluate(client, "import('/model-to-route-scenarios.mjs').then(module => module.runModelToRouteScenarios())");@@ -65,7 +66,23 @@ try {process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);}}- if (shellOnly || (!routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly)) {+ if (routeOptionsOnly || (!shellOnly && !routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly)) {+ await navigate(client, new URL('plan-editor-ux.html?checks=availability', baseUrl).href, { width: 1280, height: 900 });+ await waitFor(client, 'Boolean(document.querySelector("button")?.textContent?.includes("运行智能路由交互检查"))', { timeout: 7000 });+ await evaluate(client, 'document.querySelector("button").click()');+ await waitFor(client, 'Boolean(document.querySelector("[data-ux-results]")?.textContent)', { timeout: 20000 });+ const result = await evaluate(client, 'JSON.parse(document.querySelector("[data-ux-results]").textContent)');+ const required = ['routing.options.id-safety', 'routing.options.exclusions', 'routing.options.service-error', 'routing.options.empty'];+ if (result.tests !== required.length || result.results?.length !== required.length+ || result.results.some(item => !['green', 'red'].includes(item.state))+ || new Set(result.results.map(item => item.name.split(':')[0])).size !== required.length+ || required.some(id => !result.results.some(item => item.name.startsWith(`${id}:`)))) {+ throw new Error('Required route-options scenarios did not execute');+ }+ checks.push(...result.results);+ for (const item of result.results) process.stdout.write(`${item.state}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);+ }+ if (shellOnly || (!routeSaveOnly && !workerReplacementOnly && !claudeCollaborationOnly && !routeOptionsOnly)) {await navigate(client, new URL('product-shell.html', baseUrl).href, { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.productShell)', { timeout: 7000 });const catalog = await evaluate(client, "import('/product-shell-scenarios.mjs').then(module => module.productShellScenarioCatalog)");diff --git a/apps/desktop/tests/v3/visual/agent-trust.mjs b/apps/desktop/tests/v3/visual/agent-trust.mjsindex f06cf6dd..47311c41 100644--- a/apps/desktop/tests/v3/visual/agent-trust.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust.mjs@@ -9,10 +9,11 @@ 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-agent-trust'));const shellOnly = process.argv[3] === '--shell-only';-if (process.argv[3] && !['--shell-only', '--route-save-only', '--worker-replacement-only', '--claude-collaboration-only'].includes(process.argv[3])) throw new Error(`Unknown scenario selection: ${process.argv[3]}`);+if (process.argv[3] && !['--shell-only', '--route-save-only', '--worker-replacement-only', '--claude-collaboration-only', '--route-options-only'].includes(process.argv[3])) throw new Error(`Unknown scenario selection: ${process.argv[3]}`);const routeSaveOnly = process.argv[3] === '--route-save-only';const workerReplacementOnly = process.argv[3] === '--worker-replacement-only';const claudeCollaborationOnly = process.argv[3] === '--claude-collaboration-only';+const routeOptionsOnly = process.argv[3] === '--route-options-only';const availablePort = () => new Promise((resolve, reject) => {const server = net.createServer();@@ -72,7 +73,7 @@ try {chrome.stderr.on('data', data => { chromeErrors = (chromeErrors + data).slice(-8000); });try { await waitFor(`http://127.0.0.1:${cdpPort}/json/version`); }catch (error) { throw new Error(`${error.message}\n${chromeErrors}`); }- const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(shellOnly ? ['--shell-only'] : routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });+ const runner = spawn(process.execPath, [path.join(here, 'agent-trust-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot, ...(shellOnly ? ['--shell-only'] : routeSaveOnly ? ['--route-save-only'] : workerReplacementOnly ? ['--worker-replacement-only'] : claudeCollaborationOnly ? ['--claude-collaboration-only'] : routeOptionsOnly ? ['--route-options-only'] : [])], { cwd: desktopRoot, stdio: 'inherit' });const outcome = await waitForExit(runner);if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;} finally {diff --git a/crates/application-api/src/plan_authoring.rs b/crates/application-api/src/plan_authoring.rsindex 9eb4ea9d..81319678 100644--- a/crates/application-api/src/plan_authoring.rs+++ b/crates/application-api/src/plan_authoring.rs@@ -171,6 +171,28 @@ pub struct PlanCandidateOptionV1 {pub native_ingress_protocols: Vec<UpstreamProtocol>,}+/// Safe local reasons; never carry provider payloads, endpoints or credentials.+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum PlanCandidateUnavailableReasonV1 {+ InvalidModelId,+ SourceNotReady,+ ModelNotEligible,+ CatalogMismatch,+ CredentialUnavailable,+ RuntimeUnavailable,+ CapabilityUnavailable,+ InvalidConfiguration,+}++#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct PlanUnavailableCandidateV1 {+ pub binding_id: String,+ pub display_name: String,+ pub reason: PlanCandidateUnavailableReasonV1,+}+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(rename_all = "snake_case")]pub enum CodexInputModalityV1 {@@ -245,6 +267,9 @@ pub enum CodexClientCapabilityPreviewV1 {#[derive(Clone, Debug, Default, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct PlanEditorOptionsRequestV1 {+ /// Opt in so released strict response readers keep their original field set.+ #[serde(default)]+ pub include_unavailable: bool,#[serde(default)]pub published_plan: Option<PublishedPlanCapabilityRequestV1>,#[serde(default)]@@ -263,6 +288,11 @@ pub struct PlanEditorOptionsRequestV1 {#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct PlanEditorOptionsV1 {+ /// Present only when opted-in explanations are bounded to the first page.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub unavailable_candidate_count: Option<usize>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub unavailable_candidates: Vec<PlanUnavailableCandidateV1>,pub claude_capabilities: Option<ClaudeClientCapabilityPreviewV1>,pub context_window: Option<PlanContextWindowPreviewV1>,pub suggested_alias: Option<ModelAlias>,diff --git a/crates/application/src/client_access/editor_options.rs b/crates/application/src/client_access/editor_options.rsindex a321993b..bb1fb120 100644--- a/crates/application/src/client_access/editor_options.rs+++ b/crates/application/src/client_access/editor_options.rs@@ -124,7 +124,20 @@ pub(super) fn dispatch(.collect(),}).collect();+ let unavailable_candidate_count = (payload.include_unavailable+ && state.unavailable_candidates.len() > MAX_RATING_QUERY_ITEMS)+ .then_some(state.unavailable_candidates.len());Ok(PlanEditorOptionsV1 {+ unavailable_candidate_count,+ unavailable_candidates: if payload.include_unavailable {+ state+ .unavailable_candidates+ .into_iter()+ .take(MAX_RATING_QUERY_ITEMS)+ .collect()+ } else {+ Vec::new()+ },claude_capabilities,context_window,suggested_alias,@@ -420,4 +433,17 @@ mod tests {);assert_eq!(port.calls.load(Ordering::SeqCst), 0);}++ #[test]+ fn missing_routing_service_still_reports_daemon_unavailable() {+ let response = crate::ApplicationService::default().dispatch(LocalControlRequestV2 {+ schema_version: LOCAL_CONTROL_SCHEMA_V2,+ request_id: "options-missing-service".into(),+ principal: PrincipalV1::interactive_user(),+ operation_id: "GetPlanEditorOptions".into(),+ protected_grant: None,+ payload: serde_json::json!({"include_unavailable": true}),+ });+ assert_eq!(response.error.unwrap().code, ErrorCode::DaemonUnavailable);+ }}diff --git a/crates/application/src/compiler/facts.rs b/crates/application/src/compiler/facts.rsindex 8598b5f1..d9d0c11e 100644--- a/crates/application/src/compiler/facts.rs+++ b/crates/application/src/compiler/facts.rs@@ -137,7 +137,7 @@ impl CandidateCompilationFactV1 {self.protocol_endpoint.base_url, self.protocol_endpoint.request_path),)- || !valid_reference(&self.native_transport_model)+ || !hiroute_domain::valid_upstream_model_id(&self.native_transport_model)|| (self.connector_runtime == ConnectorRuntimeKind::BuiltinNative&& self.native_transport_model != self.binding.upstream_model_id)|| self.protocol_profiles.is_empty()@@ -269,7 +269,7 @@ impl CandidateCompilationFactV1 {self.protocol_endpoint.base_url, self.protocol_endpoint.request_path),)- || !valid_reference(&self.native_transport_model)+ || !hiroute_domain::valid_upstream_model_id(&self.native_transport_model)|| self.connector_runtime != ConnectorRuntimeKind::BuiltinNative|| self.native_transport_model != self.binding.upstream_model_id|| self.protocol_profiles.is_empty()@@ -326,6 +326,14 @@ pub enum CandidateFactScope {impl AgentPlanCompilationFactsV1 {pub fn validate(&self) -> Result<(), CompilerFactError> {+ if self.candidates.is_empty() {+ return Err(CompilerFactError::InvalidCandidateCount);+ }+ self.validate_snapshot()+ }++ /// Read-only options may describe no candidates; compilation must call `validate`.+ pub fn validate_snapshot(&self) -> Result<(), CompilerFactError> {if self.schema != AGENT_PLAN_FACTS_SCHEMA_V1 {return Err(CompilerFactError::UnsupportedSchema);}@@ -333,14 +341,16 @@ impl AgentPlanCompilationFactsV1 {return Err(CompilerFactError::UnsupportedCompilerRevision);}self.refs- .validate()+ .validate_snapshot().map_err(|_| CompilerFactError::InvalidFactReferences)?;if !valid_reference(&self.ordering_price_version)|| invalid_digest(&self.ordering_price_digest){return Err(CompilerFactError::InvalidFactReferences);}- if self.candidates.is_empty() || self.candidates.len() > 512 {+ if self.candidates.len() > 512+ || (!self.candidates.is_empty() && self.refs.inventory_revision == 0)+ {return Err(CompilerFactError::InvalidCandidateCount);}let mut binding_ids = BTreeSet::new();diff --git a/crates/application/src/compiler/tests.rs b/crates/application/src/compiler/tests.rsindex 10c2fa4a..ff7f0fff 100644--- a/crates/application/src/compiler/tests.rs+++ b/crates/application/src/compiler/tests.rs@@ -10,6 +10,99 @@ use hiroute_domain::{use super::test_fixtures::*;use super::*;+fn with_upstream_model_id(fact: &mut CandidateCompilationFactV1, id: &str) {+ fact.binding.upstream_model_id = id.to_owned();+ fact.capability.upstream_model_id = id.to_owned();+ fact.native_transport_model = id.to_owned();+ for profile in &mut fact.protocol_profiles {+ profile.capability.native_model = id.to_owned();+ }+}++#[test]+fn compiler_preserves_opaque_upstream_ids_in_every_materialized_protocol() {+ for id in [+ "内网模型".to_owned(),+ "vendor/模型:2026@alpha?revision#1".to_owned(),+ "Model A".to_owned(),+ "e\u{301}-模型".to_owned(),+ "\u{feff}模型\u{feff}".to_owned(),+ "\u{feff}".to_owned(),+ "模型🧠".to_owned(),+ "🧠".repeat(128),+ "x".repeat(512),+ "界".repeat(170) + "ab",+ ] {+ let mut facts = compilation_facts();+ let selected = facts+ .candidates+ .iter_mut()+ .find(|fact| fact.binding.binding_id == "binding/primary-b")+ .unwrap();+ with_upstream_model_id(selected, &id);+ selected.model.display_name = "中文显示名称".into();+ selected.binding.validate_shape().unwrap();+ facts.validate().unwrap();+ let materialized = materialize_agent_plan(&custom_desired(), &facts).unwrap();+ let candidate = &materialized.materialized.attempt_owned.groups[0].candidates[0];+ assert_eq!(candidate.binding_id, "binding/primary-b");+ assert_eq!(candidate.upstream_model_id, id);+ assert_eq!(candidate.native_transport_model, id);+ assert!(!candidate.protocol_profiles.is_empty());+ for profile in &candidate.protocol_profiles {+ assert_eq!(profile.capability.native_model, id);+ }+ materialized.materialized.validate().unwrap();+ }+}++#[test]+fn compiler_rejects_unsafe_upstream_ids_without_loosening_binding_identifiers() {+ for id in [+ String::new(),+ " 模型".into(),+ "模型\u{a0}".into(),+ "a\tb".into(),+ "a\0b".into(),+ "a\u{85}b".into(),+ "\u{85}模型".into(),+ "模型\u{85}".into(),+ "x".repeat(513),+ "界".repeat(171),+ "🧠".repeat(129),+ ] {+ let mut facts = compilation_facts();+ with_upstream_model_id(&mut facts.candidates[0], &id);+ assert!(facts.validate().is_err(), "accepted unsafe ID {id:?}");+ }+ let mut facts = compilation_facts();+ with_upstream_model_id(&mut facts.candidates[0], "内网模型");+ facts.candidates[0].binding.binding_id = "binding/内网模型".into();+ assert!(facts.validate().is_err());+}++#[test]+fn empty_options_snapshot_cannot_become_a_published_or_digested_plan() {+ let mut facts = compilation_facts();+ facts.candidates.clear();+ facts.refs.inventory_revision = 0;+ facts.validate_snapshot().unwrap();+ assert!(facts.refs.validate().is_err());+ assert_eq!(+ facts.validate(),+ Err(CompilerFactError::InvalidCandidateCount)+ );+ assert!(facts.digest().is_err());+ assert!(materialize_agent_plan(&custom_desired(), &facts).is_err());++ let mut nonempty = compilation_facts();+ nonempty.refs.inventory_revision = 0;+ assert_eq!(+ nonempty.validate_snapshot(),+ Err(CompilerFactError::InvalidCandidateCount)+ );+}+#[test]fn compiler_smart_saving_materializes_two_deterministic_branches() {let desired = smart_desired();diff --git a/crates/application/src/compute_management/mutation_support.rs b/crates/application/src/compute_management/mutation_support.rsindex c5d7fdea..2c7424c0 100644--- a/crates/application/src/compute_management/mutation_support.rs+++ b/crates/application/src/compute_management/mutation_support.rs@@ -237,6 +237,9 @@ fn candidate_model_can_be_saved(candidate: &super::ComputeCandidateModelFactsV2,intent: ComputeManagementIntentV2,) -> bool {+ if !hiroute_domain::valid_upstream_model_id(&candidate.upstream_model_id) {+ return false;+ }candidate.selectable// A failed or credential-blocked connection cannot become Ready, but its trusted Native// declaration remains valid disabled management state.diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rsindex 0c474ed8..11353019 100644--- a/crates/application/src/control/mod.rs+++ b/crates/application/src/control/mod.rs@@ -384,6 +384,8 @@ pub trait AgentConnectionControlPort: Send + Sync {#[derive(Clone)]pub struct RoutingCompilationSnapshotV1 {+ /// Read-only diagnostics, excluded from executable facts and their canonical digest.+ pub unavailable_candidates: Vec<hiroute_application_api::PlanUnavailableCandidateV1>,pub facts: crate::compiler::AgentPlanCompilationFactsV1,pub expected_revisions: RevisionSetV1,/// Exact active aggregate used only by Apply to preserve immutable aliases, existing Plans,diff --git a/crates/application/src/routing/suggestions.rs b/crates/application/src/routing/suggestions.rsindex e45344de..61d5200c 100644--- a/crates/application/src/routing/suggestions.rs+++ b/crates/application/src/routing/suggestions.rs@@ -22,7 +22,7 @@ pub fn suggest_free(ratings: &ModelRatings,snapshot: RatingSnapshotSelectionV1,) -> Result<FreeSuggestionsV1, AgentPlanCompilerError> {- facts.validate()?;+ facts.validate_snapshot()?;requirements.validate().map_err(|_| AgentPlanCompilerError::InvalidDesiredPlan)?;diff --git a/crates/daemon/src/control/runtime/compute_routing/tests.rs b/crates/daemon/src/control/runtime/compute_routing/tests.rsindex b7c66aff..2d175793 100644--- a/crates/daemon/src/control/runtime/compute_routing/tests.rs+++ b/crates/daemon/src/control/runtime/compute_routing/tests.rs@@ -7,7 +7,8 @@ use hiroute_domain::{CanonicalDigest, ComputeProjectionExpectationV1, CredentialRefV1, PortErrorCode, WorkspaceId,};use hiroute_integrations::{- CpaRegisteredSourceV1, RegisteredComputeDiscoveryFactV1, TrustedReleaseCatalog,+ CpaAccountMaterializationV1, CpaRegisteredSourceV1, RegisteredComputeDiscoveryFactV1,+ TrustedReleaseCatalog, register_cpa_account,};use hiroute_local_storage::LocalStorageSet;@@ -297,7 +298,145 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()&previous_model_data,).unwrap();- assert_eq!(stores.control().compute_projection_rows().unwrap().len(), 3);+ let cpa_source_id = "cpa/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";+ let cpa_kind = hiroute_cpa_bridge::CpaAccountKind::Codex;+ let registered = register_cpa_account(+ &catalog,+ &CpaAccountMaterializationV1 {+ connector_id: cpa_kind.connector_id().into(),+ connection_option_id: cpa_kind.connection_option_id().into(),+ endpoint_profile_id: cpa_kind.endpoint_profile_id().into(),+ source_id: cpa_source_id.into(),+ account_subject:+ "account/cpa/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ .into(),+ credential_ref: CredentialRefV1::new(+ "credential/cpa/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ format!("source/{cpa_source_id}"),+ format!("connector/{}", cpa_kind.connector_id()),+ "provider-auth",+ [format!(+ "connection-option/{}",+ cpa_kind.connection_option_id()+ )],+ 1,+ )+ .unwrap(),+ observed_model_ids: ["gpt-6.1-sol".into()].into_iter().collect(),+ },+ )+ .unwrap();+ let mut cpa = catalog+ .prepare_cpa_compute_projection(+ ®istered,+ "model.openai.gpt-6.1-sol",+ ComputeProjectionExpectationV1 {+ source_revision: 0,+ source_digest: None,+ binding_revision: 0,+ binding_digest: None,+ inventory_revision: 0,+ inventory_digest: None,+ },+ true,+ )+ .unwrap()+ .desired;+ // Admit the binding before its pool, then provide the exact retained credential reference.+ // A Ready binding without a pool is correctly rejected by the current store writer.+ cpa.source.state = hiroute_domain::MaterializationState::NeedsCredential;+ stores+ .control()+ .put_compute_source(0, &cpa.source, catalog.registry(), true)+ .unwrap();+ stores+ .control()+ .put_source_binding(0, &cpa.binding, catalog.registry(), catalog.model_data())+ .unwrap();+ stores+ .control()+ .put_inventory_snapshot(&cpa.inventory)+ .unwrap();+ let cpa_pool = cpa+ .credential_pool_identity+ .as_ref()+ .unwrap()+ .materialize_first(+ registered.credential_ref,+ CanonicalDigest::of_bytes(b"retained-cpa-reference"),+ )+ .unwrap();+ stores+ .control()+ .put_credential_pool(0, &cpa_pool, catalog.registry(), catalog.model_data())+ .unwrap();++ // Inject a structurally valid retained join fault after proving that current writers reject+ // it. This unit fixture exercises the read-only adapter; product smoke uses public saves.+ let mut credential_stale_binding = current.binding.clone();+ credential_stale_binding.binding_id = "binding/credential-stale".into();+ credential_stale_binding.credential_pool_id = Some("pool/credential-stale".into());+ stores+ .control()+ .put_source_binding(+ 0,+ &credential_stale_binding,+ catalog.registry(),+ catalog.model_data(),+ )+ .unwrap();+ let mut credential_stale_pool = pool.clone();+ credential_stale_pool.pool_id = "pool/credential-stale".into();+ credential_stale_pool.binding_id = credential_stale_binding.binding_id.clone();+ credential_stale_pool.binding_digest = CanonicalDigest::of(&credential_stale_binding).unwrap();+ stores+ .control()+ .put_credential_pool(+ 0,+ &credential_stale_pool,+ catalog.registry(),+ catalog.model_data(),+ )+ .unwrap();+ credential_stale_binding.revision = 2;+ assert_eq!(+ stores+ .control()+ .put_source_binding(+ 1,+ &credential_stale_binding,+ catalog.registry(),+ catalog.model_data(),+ )+ .unwrap_err()+ .code,+ PortErrorCode::InvalidData+ );+ credential_stale_binding+ .validate(¤t.source, catalog.model_data())+ .unwrap();+ credential_stale_pool.validate().unwrap();+ assert!(+ credential_stale_pool+ .validate_against_binding(&credential_stale_binding)+ .is_err()+ );+ let fixture = rusqlite::Connection::open(storage_root.join("live/control.db")).unwrap();+ assert_eq!(+ fixture+ .execute(+ "UPDATE source_bindings SET revision=2, binding_json=?1+ WHERE binding_id=?2 AND revision=1 AND active=1",+ rusqlite::params![+ serde_json::to_string(&credential_stale_binding).unwrap(),+ credential_stale_binding.binding_id+ ],+ )+ .unwrap(),+ 1+ );+ drop(fixture);+ assert_eq!(stores.control().compute_projection_rows().unwrap().len(), 5);let home = directory.path().join("home");let project = directory.path().join("project");@@ -421,6 +560,26 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot().unwrap();assert_eq!(snapshot.facts.candidates.len(), 1);+ let reasons = snapshot+ .unavailable_candidates+ .iter()+ .map(|candidate| (candidate.binding_id.as_str(), candidate.reason))+ .collect::<BTreeMap<_, _>>();+ use hiroute_application_api::PlanCandidateUnavailableReasonV1 as Reason;+ assert_eq!(reasons.len(), 4);+ assert_eq!(reasons["binding/stale"], Reason::CatalogMismatch);+ assert_eq!(+ reasons["binding/stale-model-revision"],+ Reason::CatalogMismatch+ );+ assert_eq!(+ reasons[cpa.binding.binding_id.as_str()],+ Reason::RuntimeUnavailable+ );+ assert_eq!(+ reasons["binding/credential-stale"],+ Reason::CredentialUnavailable+ );assert_eq!(snapshot.facts.candidates[0].binding.binding_id,current.binding.binding_iddiff --git a/crates/daemon/src/control/runtime/routing.rs b/crates/daemon/src/control/runtime/routing.rsindex 693bb955..8ea2b2cb 100644--- a/crates/daemon/src/control/runtime/routing.rs+++ b/crates/daemon/src/control/runtime/routing.rs@@ -2,7 +2,6 @@ use hiroute_application::compiler::{AgentPlanCompilationFactsV1, CandidateCompilationFactV1, CandidateFactScope,FreeCandidateEvidenceV1, OrderingPriceFactV1,};-use hiroute_application::compute_management::compile_compute_management_source;use hiroute_application::control::{ControlReadError, RoutingCompilationSnapshotV1, RoutingFactsPort,};@@ -13,6 +12,11 @@ use hiroute_domain::{};use super::LocalControlAdapter;+use hiroute_application_api::PlanCandidateUnavailableReasonV1 as UnavailableReason;++#[path = "routing_candidates.rs"]+mod candidates;+use candidates::CandidateDiagnostics;impl RoutingFactsPort for LocalControlAdapter {fn plan_lifecycle_snapshot(@@ -194,7 +198,8 @@ impl RoutingFactsPort for LocalControlAdapter {let first = self.routing_snapshot(workspace_id)?;let second = self.routing_snapshot(workspace_id)?;// Both reads are independent. Compare the complete inputs without temporary encoding.- if first.facts != second.facts+ if first.unavailable_candidates != second.unavailable_candidates+ || first.facts != second.facts|| first.expected_revisions != second.expected_revisions|| first.active_publication != second.active_publication{@@ -256,6 +261,8 @@ impl LocalControlAdapter {control.compute_projection_rows().map_err(super::map_port)?,)};+ let mut diagnostics =+ CandidateDiagnostics::new(&management.sources, &rows, catalog);let needs_cpa = rows.iter().any(|(source, _, _)| source.origin == SourceOrigin::Cpa)@@ -287,6 +294,11 @@ impl LocalControlAdapter {source.validate_shape().map_err(|_| ControlReadError::Corrupt)?;+ if !hiroute_domain::valid_upstream_model_id(&binding.upstream_model_id) {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::InvalidModelId);+ continue;+ }binding.validate_shape().map_err(|_| ControlReadError::Corrupt)?;@@ -296,6 +308,8 @@ impl LocalControlAdapter {// A structurally valid durable projection can legitimately become stale when a// newer client-bundled catalog removes or revises its exact connector/model/Offer facts.// Exclude only that candidate; persisted corruption was already rejected above.+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;}let Some(model) = catalog@@ -303,6 +317,8 @@ impl LocalControlAdapter {.model(&binding.model_configuration_id).cloned()else {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;};let Some(capability) = catalog@@ -312,11 +328,15 @@ impl LocalControlAdapter {.find(|capability| capability.capability_id == binding.capability_id).cloned()else {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;};let Ok(resolved) =catalog.resolve_connection_option(&source.connection_option_id)else {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;};let Some(protocol_endpoint) = resolved@@ -328,9 +348,13 @@ impl LocalControlAdapter {}).cloned()else {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;};let Some(offer) = catalog.model_data().offer(&binding.offer_ref) else {+ diagnostics+ .legacy_reason(&binding.binding_id, UnavailableReason::CatalogMismatch);continue;};let mut pool = binding@@ -357,6 +381,10 @@ impl LocalControlAdapter {&& (catalog.validate_pool(pool, &source).is_err()|| pool.validate_against_binding(&binding).is_err()){+ diagnostics.legacy_reason(+ &binding.binding_id,+ UnavailableReason::CredentialUnavailable,+ );continue;}let Some(reasoning) = catalog@@ -367,12 +395,22 @@ impl LocalControlAdapter {}).cloned()else {+ diagnostics.legacy_reason(+ &binding.binding_id,+ UnavailableReason::CapabilityUnavailable,+ );continue;};let source_state = match resolved.connector.authentication {AuthenticationKind::None => source.state,- _ if pool.is_some() => MaterializationState::Ready,- _ => source.state,+ _ if source.state == MaterializationState::Disabled => source.state,+ _ if pool.as_ref().is_some_and(|pool| {+ pool.credentials.iter().any(|entry| entry.enabled)+ }) =>+ {+ MaterializationState::Ready+ }+ _ => MaterializationState::NeedsCredential,};let Some(execution) =super::candidate_execution::materialize_candidate_execution(@@ -385,6 +423,15 @@ impl LocalControlAdapter {cpa_targets,)else {+ let reason = if source.origin == SourceOrigin::Cpa && cpa_targets.is_none()+ {+ UnavailableReason::RuntimeUnavailable+ } else if source_state == MaterializationState::NeedsCredential {+ UnavailableReason::CredentialUnavailable+ } else {+ UnavailableReason::InvalidConfiguration+ };+ diagnostics.legacy_reason(&binding.binding_id, reason);continue;};// The current catalog keeps configuration-scoped ratings separate. Explicit@@ -484,17 +531,17 @@ impl LocalControlAdapter {{let Ok(resolved) = catalog.resolve_connection_option(connection_option_id)else {+ diagnostics.catalog_mismatch(&source);continue;};if !super::model_connections::registered_source_matches_current_option(&source, &resolved,) {+ diagnostics.catalog_mismatch(&source);continue;}}- let Ok(compilation) = compile_compute_management_source(&source) else {- continue;- };+ let compilation = diagnostics.compile_models(&source);for fact in &compilation {let candidate = match &fact.provenance {hiroute_domain::ComputeManagementProvenanceV2::ConnectorOwned {@@ -535,6 +582,23 @@ impl LocalControlAdapter {};if let Some(candidate) = candidate {candidates.push(candidate);+ } else {+ let runtime_unavailable = match &fact.provenance {+ hiroute_domain::ComputeManagementProvenanceV2::ConnectorOwned {+ connector_id,+ account_ref,+ } => cpa_targets+ .and_then(|batch| {+ unique_live_cpa_source(+ batch.sources(),+ connector_id,+ account_ref,+ )+ })+ .is_none(),+ _ => false,+ };+ diagnostics.materialization_failed(fact, runtime_unavailable);}}}@@ -545,7 +609,7 @@ impl LocalControlAdapter {.iter().map(|value| value.2).max()- .ok_or(ControlReadError::NotFound)?;+ .unwrap_or(0);let rating_snapshot = catalog.rating_snapshot().clone();let facts = AgentPlanCompilationFactsV1 {schema: AGENT_PLAN_FACTS_SCHEMA_V1.into(),@@ -584,7 +648,7 @@ impl LocalControlAdapter {.map_err(|_| ControlReadError::Corrupt)?,candidates,};- facts.validate().map_err(|error| {+ facts.validate_snapshot().map_err(|error| {eprintln!("routing compilation facts are invalid: {error}");ControlReadError::Corrupt})?;@@ -612,6 +676,7 @@ impl LocalControlAdapter {return Err(ControlReadError::SnapshotChanged);}Ok(RoutingCompilationSnapshotV1 {+ unavailable_candidates: diagnostics.finish(&facts.candidates),facts,expected_revisions,active_publication,diff --git a/crates/daemon/src/control/runtime/routing_candidates.rs b/crates/daemon/src/control/runtime/routing_candidates.rsnew file mode 100644index 00000000..efe6fd10--- /dev/null+++ b/crates/daemon/src/control/runtime/routing_candidates.rs@@ -0,0 +1,270 @@+//! Read-only explanations accompany saved model identities; they never become execution facts.+use std::collections::BTreeMap;++use hiroute_application::compiler::CandidateCompilationFactV1;+use hiroute_application::compute_management::{+ ComputeManagementCompilationErrorV2, ComputeManagementCompilationFactV2,+ compile_compute_management_source,+};+use hiroute_application_api::{+ PlanCandidateUnavailableReasonV1 as Reason, PlanUnavailableCandidateV1,+};+use hiroute_domain::{+ ComputeInventorySnapshotV1, ComputeManagedModelV2, ComputeManagementSourceV2, ComputeSourceV1,+ MaterializationState, SourceBindingV1, valid_upstream_model_id,+};+use hiroute_integrations::TrustedReleaseCatalog;++pub(super) struct CandidateDiagnostics(BTreeMap<String, PlanUnavailableCandidateV1>);++impl CandidateDiagnostics {+ pub(super) fn new(+ sources: &[ComputeManagementSourceV2],+ rows: &[(ComputeSourceV1, SourceBindingV1, ComputeInventorySnapshotV1)],+ catalog: &TrustedReleaseCatalog,+ ) -> Self {+ let mut result = Self(BTreeMap::new());+ for (source, binding, _) in rows {+ let name = catalog+ .model_data()+ .model(&binding.model_configuration_id)+ .map_or(binding.upstream_model_id.as_str(), |model| {+ model.display_name.as_str()+ });+ result.insert(+ &binding.binding_id,+ name,+ source_reason(source.state).unwrap_or(Reason::InvalidConfiguration),+ );+ }+ for source in sources {+ for model in &source.models {+ result.model(+ model,+ model_reason(source, model).unwrap_or(Reason::InvalidConfiguration),+ );+ }+ }+ result+ }++ fn insert(&mut self, id: &str, name: &str, reason: Reason) {+ self.0.insert(+ id.to_owned(),+ PlanUnavailableCandidateV1 {+ binding_id: id.to_owned(),+ display_name: name.chars().filter(|c| !c.is_control()).take(128).collect(),+ reason,+ },+ );+ }++ fn model(&mut self, model: &ComputeManagedModelV2, reason: Reason) {+ self.insert(&model.binding_id, &model.display_name, reason);+ }++ pub(super) fn legacy_reason(&mut self, binding_id: &str, reason: Reason) {+ if let Some(candidate) = self.0.get_mut(binding_id) {+ candidate.reason = reason;+ }+ }++ pub(super) fn catalog_mismatch(&mut self, source: &ComputeManagementSourceV2) {+ for model in &source.models {+ self.model(+ model,+ model_reason(source, model).unwrap_or(Reason::CatalogMismatch),+ );+ }+ }++ pub(super) fn compile_models(+ &mut self,+ source: &ComputeManagementSourceV2,+ ) -> Vec<ComputeManagementCompilationFactV2> {+ let mut facts = Vec::new();+ // Validate each model independently: a retained invalid/unsupported row cannot poison+ // another model's eligibility. Source authorization and credential checks still run.+ let mut selected = source.clone();+ for model in &source.models {+ if let Some(reason) = model_reason(source, model) {+ self.model(model, reason);+ continue;+ }+ selected.models = vec![model.clone()];+ match compile_compute_management_source(&selected) {+ Ok(models) => facts.extend(models),+ Err(error) => self.model(+ model,+ match error {+ ComputeManagementCompilationErrorV2::InvalidSource => {+ Reason::InvalidConfiguration+ }+ ComputeManagementCompilationErrorV2::NotReady => Reason::SourceNotReady,+ ComputeManagementCompilationErrorV2::UnknownCapability => {+ Reason::CapabilityUnavailable+ }+ ComputeManagementCompilationErrorV2::EligibilityMismatch => {+ Reason::ModelNotEligible+ }+ ComputeManagementCompilationErrorV2::CredentialMissing+ | ComputeManagementCompilationErrorV2::AuthorizationMissing => {+ Reason::CredentialUnavailable+ }+ },+ ),+ }+ }+ facts+ }++ pub(super) fn materialization_failed(+ &mut self,+ fact: &ComputeManagementCompilationFactV2,+ runtime_unavailable: bool,+ ) {+ // Only the live-source join proves runtime absence. Other preparation failures do not+ // establish a provider/network/credential failure.+ let reason = if runtime_unavailable {+ Reason::RuntimeUnavailable+ } else {+ Reason::InvalidConfiguration+ };+ self.insert(&fact.binding_id, &fact.display_name, reason);+ }++ pub(super) fn finish(+ mut self,+ candidates: &[CandidateCompilationFactV1],+ ) -> Vec<PlanUnavailableCandidateV1> {+ for fact in candidates {+ if fact.is_routable() {+ self.0.remove(&fact.binding.binding_id);+ } else {+ self.insert(+ &fact.binding.binding_id,+ &fact.model.display_name,+ source_reason(fact.source_state).unwrap_or(Reason::ModelNotEligible),+ );+ }+ }+ self.0.into_values().collect()+ }+}++fn source_reason(state: MaterializationState) -> Option<Reason> {+ match state {+ MaterializationState::Ready => None,+ MaterializationState::Disabled => Some(Reason::SourceNotReady),+ MaterializationState::NeedsCredential | MaterializationState::NeedsAuthorization => {+ Some(Reason::CredentialUnavailable)+ }+ }+}++fn model_reason(+ source: &ComputeManagementSourceV2,+ model: &ComputeManagedModelV2,+) -> Option<Reason> {+ if !valid_upstream_model_id(&model.upstream_model_id) {+ Some(Reason::InvalidModelId)+ } else if let Some(reason) = source_reason(source.state) {+ Some(reason)+ } else if !model.execution_eligible {+ Some(Reason::ModelNotEligible)+ } else {+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use hiroute_domain::{COMPUTE_MANAGEMENT_SOURCE_SCHEMA_V2, CanonicalDigest};+ use serde_json::json;++ fn source(ids: &[&str]) -> ComputeManagementSourceV2 {+ let evidence = CanonicalDigest::of_bytes(b"retained-source-evidence");+ serde_json::from_value(json!({+ "schema": COMPUTE_MANAGEMENT_SOURCE_SCHEMA_V2,+ "source_id": "source/retained",+ "revision": 1,+ "lineage_digest": evidence,+ "display_name": "Retained user source",+ "provenance": {"kind": "user_configured", "configuration_revision": 1, "evidence_digest": evidence},+ "target": {"scheme":"http", "authority":"127.0.0.1", "port":8123,+ "request_path":"/v1/responses", "upstream_protocol":"responses",+ "protocol_profile_id":"profile/custom/responses", "protocol_profile_revision":1},+ "authentication": {"kind":"none"},+ "state": "ready",+ "models": ids.iter().enumerate().map(|(i, id)| json!({+ "model_ref":format!("model/retained-{i}"), "binding_id":format!("binding/retained-{i}"),+ "revision":1, "upstream_model_id":id, "display_name":format!("Retained model {i}"),+ "membership":"user_declared", "execution_eligible":true,+ "capabilities":{+ "tool":{"value":true,"basis":"user_declared"},+ "vision":{"value":false,"basis":"user_declared"},+ "streaming":{"value":true,"basis":"user_declared"},+ "context_tokens":{"value":32768,"basis":"user_declared"},+ "max_output_tokens":{"value":4096,"basis":"user_declared"},+ "native_reasoning":{"value":{"kind":"fixed","profile":"provider-default"},"basis":"user_declared"}+ },+ "capability_evidence_digest": evidence+ })).collect::<Vec<_>>(),+ "last_candidate_ref":"candidate/retained", "last_candidate_revision":1+ })).unwrap()+ }++ #[test]+ fn retained_invalid_model_is_explained_without_poisoning_a_valid_sibling() {+ let catalog = crate::release_catalog::current_fixture_catalog();+ let source = source(&["bad\tmodel", "内网模型"]);+ // The historical management reader must preserve old bytes for repair.+ source.validate().unwrap();+ let mut diagnostics =+ CandidateDiagnostics::new(std::slice::from_ref(&source), &[], &catalog);+ let facts = diagnostics.compile_models(&source);+ assert_eq!(facts.len(), 1);+ assert_eq!(facts[0].upstream_model_id, "内网模型");+ let candidate =+ crate::control::runtime::candidate_execution::materialize_management_candidate(+ &facts[0], None,+ )+ .unwrap();+ let unavailable = diagnostics.finish(&[candidate]);+ assert_eq!(unavailable.len(), 1);+ assert_eq!(unavailable[0].binding_id, "binding/retained-0");+ assert_eq!(unavailable[0].reason, Reason::InvalidModelId);+ }++ #[test]+ fn unavailable_model_count_does_not_limit_the_execution_snapshot() {+ let catalog = crate::release_catalog::current_fixture_catalog();+ let ids = (0..257)+ .map(|i| format!("unavailable-{i}"))+ .collect::<Vec<_>>();+ let mut disabled = source(&ids.iter().map(String::as_str).collect::<Vec<_>>());+ disabled.state = MaterializationState::Disabled;+ disabled.validate().unwrap();+ let mut valid = source(&["内网模型"]);+ valid.source_id = "source/live".into();+ valid.models[0].binding_id = "binding/live".into();+ valid.models[0].model_ref = "model/live".into();+ let mut diagnostics =+ CandidateDiagnostics::new(&[disabled.clone(), valid.clone()], &[], &catalog);+ assert!(diagnostics.compile_models(&disabled).is_empty());+ let facts = diagnostics.compile_models(&valid);+ let candidate =+ crate::control::runtime::candidate_execution::materialize_management_candidate(+ &facts[0], None,+ )+ .unwrap();+ let unavailable = diagnostics.finish(&[candidate]);+ assert_eq!(unavailable.len(), 257);+ assert!(+ unavailable+ .iter()+ .all(|row| row.reason == Reason::SourceNotReady)+ );+ }+}diff --git a/crates/daemon/src/gateway_ports/credential.rs b/crates/daemon/src/gateway_ports/credential.rsindex 2da25d32..4b1ee040 100644--- a/crates/daemon/src/gateway_ports/credential.rs+++ b/crates/daemon/src/gateway_ports/credential.rs@@ -269,8 +269,8 @@ fn validate_request(|| !valid_reference(request.credential_ref)|| destination.is_none()|| !valid_reference(request.connector_id)- || !valid_reference(request.upstream_model_id)- || !valid_reference(request.native_transport_model)+ || !hiroute_domain::valid_upstream_model_id(request.upstream_model_id)+ || !hiroute_domain::valid_upstream_model_id(request.native_transport_model)|| !request.request_path.starts_with('/')|| request.request_path.len() < 2|| request.request_path.contains(['?', '#'])diff --git a/crates/daemon/tests/publication_process.rs b/crates/daemon/tests/publication_process.rsindex 16f42520..c79fb4a7 100644--- a/crates/daemon/tests/publication_process.rs+++ b/crates/daemon/tests/publication_process.rs@@ -60,6 +60,11 @@ fn real_process_native_model_save_publishes_and_reaches_gateway() {run_script("model_connections_product.py");}+#[test]+fn real_process_route_options_preserve_opaque_ids_and_isolate_unavailable_models() {+ run_script("route_options_product.py");+}+/// A blank Linux HOME installs the candidate package, starts the installed daemon, and drives/// the released CLI through compute, routing, Agent, observation, and Worker entry points.#[test]diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.pyindex f285a2b4..11e3135f 100644--- a/crates/daemon/tests/support/model_connections_product.py+++ b/crates/daemon/tests/support/model_connections_product.py@@ -155,7 +155,9 @@ def declared(value):def save_native_source(product, upstream, token=None, unknown=False,protocol='responses', upstream_model_id=MODEL, variant='',- context_tokens=32768, cli_input=False):+ context_tokens=32768, cli_input=False,+ source_display_name='Product Native API',+ model_display_name='Manual Native Model'):status = control(product, 'GetClientServiceStatus', {})['data']suffix = ('-unknown' if unknown else '') + ('-' + variant if variant else '')candidate_ref = 'candidate/native/product' + suffix@@ -178,7 +180,7 @@ def save_native_source(product, upstream, token=None, unknown=False,'inference_model_id': None,'candidate_ref': candidate_ref if token is not None else None,'lineage_ref': 'lineage/native/product' + suffix,- 'display_name': 'Product Native API',+ 'display_name': source_display_name,'existing_source_id': None,'expected_source_revision': None,'edit_revision': 1,@@ -195,7 +197,7 @@ def save_native_source(product, upstream, token=None, unknown=False,'configuration_revision': 1,'models': [{'upstream_model_id': upstream_model_id,- 'display_name': 'Manual Native Model',+ 'display_name': model_display_name,'catalog_configuration_id': None,'membership': 'user_declared','capabilities': {@@ -412,7 +414,8 @@ def assert_saved_recheck_fences_before_network(product, upstream, saved):assert len(upstream.requests) == before, upstream.requests-def publish_plan_and_agent(product, binding_id):+def publish_plan_and_agent(product, binding_id, native_model_mode='preserve_available'):+ assert native_model_mode in ('preserve_available', 'hiroute_only')product.editor = {'schema': 'hiroute.plan-editor/v2','display_name': 'Native API Product Plan',@@ -449,9 +452,9 @@ def publish_plan_and_agent(product, binding_id):product.model_alias = preview['plan_head']['model_alias']configure_model_settings_v2(product, [product.plan_id], 'native-product-agent',- agent_id='agent_codex_default', native_model_mode='preserve_available')+ agent_id='agent_codex_default', native_model_mode=native_model_mode)catalog, _ = product.catalog()- expected_models = [MODEL, product.model_alias]+ expected_models = ([MODEL] if native_model_mode == 'preserve_available' else []) + [product.model_alias]assert [model['id'] for model in catalog['data']] == expected_models, catalogdiff --git a/crates/daemon/tests/support/route_options_product.py b/crates/daemon/tests/support/route_options_product.pynew file mode 100644index 00000000..baac52e1--- /dev/null+++ b/crates/daemon/tests/support/route_options_product.py@@ -0,0 +1,312 @@+"""Saved model IDs, empty/excluded options and authenticated egress through real hirouted."""+import hashlib+import json+import subprocess+import sys+import time+from pathlib import Path++import model_connections_product as native+import publication_product+from publication_product import Product+++MODEL = '内网模型'+FEFF_MODEL = '\ufeff模型🧠\ufeff'+LEGACY_OPTION_FIELDS = {+ 'claude_capabilities', 'context_window', 'suggested_alias', 'candidates',+ 'free_suggestions', 'ratings', 'codex_capabilities', 'revisions',+}+++def encoded(value):+ # Protected action digests use the production canonical UTF-8 JSON representation.+ return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()+++native.encoded = encoded+publication_product.encoded = encoded+native.MODEL = MODEL+++def options(product, include_unavailable=None):+ payload = {'display_name': '日常开发', 'requirements': {}}+ if include_unavailable is not None:+ payload['include_unavailable'] = include_unavailable+ return native.control(product, 'GetPlanEditorOptions', payload)['data']+++def assert_legacy_options(value):+ # Exact released response field set, including its explicit null optional fields.+ assert set(value) == LEGACY_OPTION_FIELDS, sorted(value)+++def stable_compute_fields(value):+ # ListCompute evaluates presentation on each read; its timestamp is not durable state.+ stable = json.loads(json.dumps(value))+ for source in stable['sources']:+ for model in source['models']:+ del model['presentation']['evaluated_at_ms']+ return stable+++def prepare_many(product, upstream, ids, suffix):+ candidate_ref = 'candidate/native/options-' + suffix+ product.secrets.add(native.NATIVE_TOKEN)+ product.register_protected_frame({+ 'schema': 'hiroute.protected-input/v1',+ 'registration_id': hashlib.sha256(candidate_ref.encode()).hexdigest(),+ 'candidate_ref': candidate_ref,+ 'candidate_revision': 1,+ 'secret': native.NATIVE_TOKEN,+ })+ draft = {+ 'inference_model_id': None,+ 'candidate_ref': candidate_ref,+ 'lineage_ref': 'lineage/native/options-' + suffix,+ 'display_name': '不可用候选来源',+ 'existing_source_id': None,+ 'expected_source_revision': None,+ 'edit_revision': 1,+ 'check_id': 'check/native/options-' + suffix,+ 'base_url': upstream.base_url,+ 'base_kind': 'api_root',+ 'request_path_override': None,+ 'inventory_path_override': None,+ 'protocol': 'responses',+ 'protocol_profile_id': 'profile/custom/responses',+ 'protocol_profile_revision': 1,+ 'authentication': {'kind': 'bearer'},+ 'additional_endpoints': [],+ 'configuration_revision': 1,+ 'models': [{+ 'upstream_model_id': model_id,+ 'display_name': '保留模型 ' + str(i),+ 'catalog_configuration_id': None,+ 'membership': 'user_declared',+ 'capabilities': {+ 'tool': native.declared(True), 'vision': native.declared(False),+ 'streaming': native.declared(True),+ 'context_tokens': native.declared(32768),+ 'max_output_tokens': native.declared(4096),+ 'native_reasoning': native.declared({'kind': 'fixed', 'profile': 'provider-default'}),+ },+ } for i, model_id in enumerate(ids)],+ }+ request = {'draft': draft, 'input_candidate': {+ 'candidate_ref': candidate_ref, 'candidate_revision': 1,+ }}+ revisions = native.control(product, 'GetClientServiceStatus', {})['data']['revisions']+ grant = native.desktop_grant(product, 'CheckNativeModelConnection',+ 'sha256:' + hashlib.sha256(encoded(request)).hexdigest(), revisions, suffix)+ return request, grant+++def save_many(product, candidate, suffix):+ snapshot = native.control(product, 'ListCompute', {})['data']+ change = {+ 'schema': 'hiroute.compute-management-change/v2',+ 'subject': {'kind': 'candidate', 'candidate': candidate['candidate']},+ 'expected_revisions': snapshot['revisions'],+ 'selected_model_refs': [model['model_ref'] for model in candidate['models']],+ 'intent': 'save_ready', 'key_edits': [],+ }+ preview = native.control(product, 'PreviewComputeSave', {'change': change})['data']+ applied = native.control(product, 'ApplyComputeSave', {+ 'spec': preview['spec'], 'accept_digest': preview['accept_digest'],+ 'expected_revisions': preview['expected_revisions'], 'idempotency_key': suffix,+ })+ assert applied['data']['state'] == 'succeeded', applied+ saved = native.control(product, 'GetComputeSaveResult', {'operation': applied['operation']})['data']+ assert saved['disposition'] == 'saved', saved+ return saved+++def disable(product, source_id):+ snapshot = native.control(product, 'ListCompute', {})['data']+ source = next(value for value in snapshot['sources'] if value['source_id'] == source_id)+ change = {+ 'schema': 'hiroute.compute-management-change/v2',+ 'subject': {'kind': 'saved_source', 'source_id': source_id},+ 'expected_revisions': snapshot['revisions'],+ 'selected_model_refs': [model['model_ref'] for model in source['models']],+ 'intent': 'save_disabled', 'key_edits': [],+ }+ preview = native.control(product, 'PreviewComputeSave', {'change': change})['data']+ applied = native.control(product, 'ApplyComputeSave', {+ 'spec': preview['spec'], 'accept_digest': preview['accept_digest'],+ 'expected_revisions': preview['expected_revisions'], 'idempotency_key': 'options-disable',+ })+ assert applied['data']['state'] == 'succeeded', applied+++def ascii_case(product, upstream):+ saved = native.save_native_source(product, upstream, native.NATIVE_TOKEN,+ upstream_model_id='internal-model', variant='ascii-control',+ source_display_name='中文接入', model_display_name='内网模型')+ legacy = options(product)+ assert_legacy_options(legacy)+ assert len(legacy['candidates']) == 1, legacy+ assert legacy['candidates'][0]['binding_id'] == saved['binding_id']+ assert legacy['candidates'][0]['display_name'] == '内网模型'+ assert legacy['candidates'][0]['routable']+ return {'state': 'green', 'candidate_count': 1, 'chinese_display_with_ascii_id': True}+++def unicode_case(product, upstream):+ saved = []+ for i, (model_id, display) in enumerate([(MODEL, '中文显示名'), ('外网模型', 'External'),+ ('internal-model', '内网模型'), (FEFF_MODEL, '格式字符与 Emoji'), ('\ufeff', '格式字符 ID'), ('模型🧠', 'Emoji ID')]):+ saved.append(native.save_native_source(product, upstream, native.NATIVE_TOKEN,+ upstream_model_id=model_id, variant='opaque-' + str(i),+ source_display_name='测试接入 ' + str(i), model_display_name=display))+ snapshot = native.control(product, 'ListCompute', {})['data']+ persisted = next(source for source in snapshot['sources'] if source['source_id'] == saved[-1]['source_id'])+ assert persisted['models'][0]['upstream_model_id'] == model_id+ if i == 1:+ only_unicode = options(product)+ assert {row['binding_id'] for row in only_unicode['candidates']} == {row['binding_id'] for row in saved}+ assert all(row['routable'] for row in only_unicode['candidates'])+ legacy = options(product)+ assert_legacy_options(legacy)+ by_binding = {row['binding_id']: row for row in legacy['candidates']}+ assert set(by_binding) == {row['binding_id'] for row in saved}, legacy+ assert by_binding[saved[0]['binding_id']]['display_name'] == '中文显示名'+ assert by_binding[saved[2]['binding_id']]['display_name'] == MODEL+ assert all(row['routable'] for row in by_binding.values())+ assert options(product, True)['candidates'] == legacy['candidates']+ before = native.control(product, 'ListCompute', {})['data']+ with upstream.lock:+ network_before = len(upstream.requests)+ invalid_ids = [' bad', 'bad\tmodel', 'bad\u0085model', 'bad\u0085', '界' * 171, '🧠' * 129]+ for i, invalid in enumerate(invalid_ids):+ request, grant = prepare_many(product, upstream, [invalid], 'invalid-' + str(i))+ native.control(product, 'CheckNativeModelConnection', request, grant, expected_error='INVALID_ARGUMENTS')+ after = native.control(product, 'ListCompute', {})['data']+ assert stable_compute_fields(after) == stable_compute_fields(before), 'Rejected checks changed durable compute state'+ with upstream.lock:+ assert len(upstream.requests) == network_before, 'Invalid ID was sent to the provider'+ native.publish_plan_and_agent(product, saved[0]['binding_id'], native_model_mode='hiroute_only')+ assert product.model_alias != MODEL, 'Route alias replaced the actual upstream ID'+ native.gateway_request(product)+ with upstream.lock:+ posts = [row for row in upstream.requests if row['method'] == 'POST']+ assert len(posts) == 1, posts+ assert posts[0]['body']['model'] == MODEL, posts+ assert posts[0]['authorization'] == 'Bearer ' + native.NATIVE_TOKEN+ assert posts[0]['api_key'] is None+ product.stop()+ product.start()+ assert {row['binding_id'] for row in options(product)['candidates']} == set(by_binding)+ return {'state': 'green', 'candidate_count': len(by_binding), 'authenticated_gateway_posts': 1,+ 'invalid_ids_rejected_before_network': len(invalid_ids), 'reopened': True}+++def feff_egress_case(product, upstream):+ saved = native.save_native_source(product, upstream, native.NATIVE_TOKEN,+ upstream_model_id=FEFF_MODEL, variant='feff-egress', model_display_name='格式字符与 Emoji 模型')+ legacy = options(product)+ assert_legacy_options(legacy)+ assert [row['binding_id'] for row in legacy['candidates']] == [saved['binding_id']]+ native.publish_plan_and_agent(product, saved['binding_id'], native_model_mode='hiroute_only')+ native.gateway_request(product)+ with upstream.lock:+ posts = [row for row in upstream.requests if row['method'] == 'POST']+ assert len(posts) == 1, posts+ assert posts[0]['body']['model'] == FEFF_MODEL+ assert posts[0]['authorization'] == 'Bearer ' + native.NATIVE_TOKEN+ return {'state': 'green', 'authenticated_gateway_posts': 1,+ 'exact_feff_and_non_bmp_id_preserved': True}+++def empty_case(product, upstream):+ legacy = options(product)+ assert_legacy_options(legacy)+ assert legacy['candidates'] == []+ assert options(product, True)['candidates'] == []+ request, grant = prepare_many(product, upstream, ['disabled-model'], 'empty-disabled')+ candidate = native.control(product, 'CheckNativeModelConnection', request, grant)['data']['candidate']+ saved = save_many(product, candidate, 'empty-disabled-save')+ disable(product, saved['source_id'])+ unavailable = options(product, True)+ assert unavailable['candidates'] == []+ assert [row['reason'] for row in unavailable['unavailable_candidates']] == ['source_not_ready']+ assert_legacy_options(options(product, False))+ try:+ native.publish_plan_and_agent(product, saved['bindings'][0]['binding_id'], native_model_mode='hiroute_only')+ except AssertionError:+ error = json.loads(product.outputs[-1]).get('error')+ assert error and error['code'] not in ('DAEMON_UNAVAILABLE', 'INTERNAL'), error+ else:+ raise AssertionError('Published an unavailable candidate')+ with upstream.lock:+ assert not upstream.requests, 'Disabled publication reached upstream'+ return {'state': 'green', 'zero_sources': True, 'all_unavailable': True, 'publication_rejected': True}+++def many_unavailable_case(product, upstream):+ request, grant = prepare_many(product, upstream, ['disabled-' + str(i) for i in range(257)], 'many-disabled')+ candidate = native.control(product, 'CheckNativeModelConnection', request, grant)['data']['candidate']+ saved = save_many(product, candidate, 'many-disabled-save')+ assert len(saved['bindings']) == 257, saved+ disable(product, saved['source_id'])+ valid = native.save_native_source(product, upstream, native.NATIVE_TOKEN,+ upstream_model_id=MODEL, variant='many-live', model_display_name='仍可用模型')+ legacy = options(product)+ assert_legacy_options(legacy)+ assert [row['binding_id'] for row in legacy['candidates']] == [valid['binding_id']]+ explicit_old = options(product, False)+ assert_legacy_options(explicit_old)+ explained = options(product, True)+ assert len(explained['unavailable_candidates']) == 256, explained+ assert explained['unavailable_candidate_count'] == 257, explained+ assert all(row['reason'] == 'source_not_ready' for row in explained['unavailable_candidates'])+ native.publish_plan_and_agent(product, valid['binding_id'], native_model_mode='hiroute_only')+ native.gateway_request(product)+ return {'state': 'green', 'unavailable_total': 257, 'explanations_returned': 256,+ 'valid_candidates': 1, 'publication_and_gateway_succeeded': True}+++CASES = {'ascii-control': ascii_case, 'unicode': unicode_case, 'feff-egress': feff_egress_case,+ 'empty': empty_case, 'many-unavailable': many_unavailable_case}+++def run(repository, selected=None):+ repository = Path(repository).resolve()+ sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repository, text=True).strip()+ cases = CASES if selected is None else {selected: CASES[selected]}+ for name, scenario in cases.items():+ product = Product(repository)+ native.MODEL = FEFF_MODEL if name == 'feff-egress' else MODEL+ upstream = native.NativeUpstream()+ product.enable_debug_diagnostics()+ # Codex's native metadata remains its actual bundled catalog. The new HiRoute route+ # exposes the opaque upstream ID through its alias without inventing native rights.+ product.install_codex_fixture()+ start = time.monotonic()+ try:+ product.start()+ result = scenario(product, upstream)+ product.stop()+ diagnostics = product.diagnostics_snapshot()+ assert diagnostics['state'] == 'complete', diagnostics+ assert diagnostics['level_applied']['level'] == 'debug', diagnostics+ assert diagnostics['level_applied']['source'] == 'smoke_override', diagnostics+ print(json.dumps({'scenario': 'route-options-' + name, 'candidate': sha,+ 'seconds': round(time.monotonic() - start, 3), **result,+ 'diagnostics': {key: diagnostics[key] for key in (+ 'state', 'current_boot', 'level_applied', 'record_count', 'invalid_record_count')},+ }, ensure_ascii=False), flush=True)+ except BaseException:+ evidence = repository / 'target/product-e2e-evidence' / ('route-options-' + name + '-' + str(int(time.time_ns())))+ print(json.dumps({'scenario': 'route-options-' + name, 'state': 'red', 'candidate': sha,+ 'diagnostics': product.preserve_diagnostics(evidence)}, ensure_ascii=False), flush=True)+ raise+ finally:+ upstream.close()+ product.close()+ native.MODEL = MODEL+++if __name__ == '__main__':+ run(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)diff --git a/crates/domain/src/compute/common.rs b/crates/domain/src/compute/common.rsindex c478ec8e..c158fb32 100644--- a/crates/domain/src/compute/common.rs+++ b/crates/domain/src/compute/common.rs@@ -4,6 +4,21 @@ use thiserror::Error;use crate::CanonicalDigest;+/// Provider model values are opaque UTF-8, not HiRoute's internal reference identifiers.+/// Keep the original bytes for saved intent, authorization and protocol serialization.+pub fn valid_upstream_model_id(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 512+ && value.trim() == value+ && !value.chars().any(char::is_control)+}++pub(super) fn validate_upstream_model_id(value: &str) -> Result<(), ComputeContractError> {+ valid_upstream_model_id(value)+ .then_some(())+ .ok_or(ComputeContractError::InvalidIdentifier)+}+pub(super) fn validate_identifier(value: &str) -> Result<(), ComputeContractError> {let valid = !value.is_empty()&& value.len() <= 256diff --git a/crates/domain/src/compute/inventory.rs b/crates/domain/src/compute/inventory.rsindex bea00af2..0665148d 100644--- a/crates/domain/src/compute/inventory.rs+++ b/crates/domain/src/compute/inventory.rs@@ -15,7 +15,7 @@ pub struct ObservedModelV1 {impl ObservedModelV1 {pub fn validate(&self) -> Result<(), ComputeContractError> {- validate_identifier(&self.upstream_model_id)?;+ super::common::validate_upstream_model_id(&self.upstream_model_id)?;validate_inventory_metadata(&self.metadata)}}diff --git a/crates/domain/src/compute/model_data.rs b/crates/domain/src/compute/model_data.rsindex 015ef503..6d1ecb75 100644--- a/crates/domain/src/compute/model_data.rs+++ b/crates/domain/src/compute/model_data.rs@@ -204,7 +204,7 @@ impl ModelDataBundleV1 {{return Err(ComputeContractError::CrossReference);}- validate_identifier(&capability.upstream_model_id)?;+ super::common::validate_upstream_model_id(&capability.upstream_model_id)?;validate_identifier(&capability.required_adapter_ref)?;validate_nonempty_digest(&capability.evidence_digest)?;}diff --git a/crates/domain/src/compute/source.rs b/crates/domain/src/compute/source.rsindex 18cb746c..288c1d42 100644--- a/crates/domain/src/compute/source.rs+++ b/crates/domain/src/compute/source.rs@@ -198,6 +198,7 @@ pub struct SourceBindingV1 {impl SourceBindingV1 {pub fn validate_shape(&self) -> Result<(), ComputeContractError> {+ super::common::validate_upstream_model_id(&self.upstream_model_id)?;for id in [&self.binding_id,&self.source_id,@@ -205,7 +206,6 @@ impl SourceBindingV1 {&self.capability_slice_version,&self.offer_ref,&self.model_configuration_id,- &self.upstream_model_id,&self.capability_id,] {validate_identifier(id)?;diff --git a/crates/domain/src/routing/materialized.rs b/crates/domain/src/routing/materialized.rsindex b9d69b23..53ec57da 100644--- a/crates/domain/src/routing/materialized.rs+++ b/crates/domain/src/routing/materialized.rs@@ -199,8 +199,6 @@ impl AttemptOwnedCandidateV1 {&self.connection_option_id,&self.offer_ref,&self.model_configuration_id,- &self.upstream_model_id,- &self.native_transport_model,&self.capability_id,&self.connector_id,&self.endpoint_profile_id,@@ -211,7 +209,9 @@ impl AttemptOwnedCandidateV1 {return Err(CompiledPlanError::InvalidCandidate);}}- if self.binding_revision == 0+ if !crate::valid_upstream_model_id(&self.upstream_model_id)+ || !crate::valid_upstream_model_id(&self.native_transport_model)+ || self.binding_revision == 0|| self.source_revision == 0|| self.offer_revision == 0|| self.model_configuration_revision == 0@@ -335,6 +335,14 @@ pub struct AgentPlanFactRefsV1 {impl AgentPlanFactRefsV1 {pub fn validate(&self) -> Result<(), CompiledPlanError> {+ if self.inventory_revision == 0 {+ return Err(CompiledPlanError::InvalidFactReference);+ }+ self.validate_snapshot()+ }++ /// An empty read-only inventory has revision zero; published facts still require a revision.+ pub fn validate_snapshot(&self) -> Result<(), CompiledPlanError> {for value in [&self.connector_registry_version,&self.model_data_bundle_version,@@ -346,17 +354,16 @@ impl AgentPlanFactRefsV1 {return Err(CompiledPlanError::InvalidFactReference);}}- if self.inventory_revision == 0- || [- &self.connector_registry_digest,- &self.model_data_digest,- &self.capability_slice_digest,- &self.ratings_slice_digest,- &self.free_offers_slice_digest,- &self.inventory_digest,- ]- .into_iter()- .any(invalid_digest)+ if [+ &self.connector_registry_digest,+ &self.model_data_digest,+ &self.capability_slice_digest,+ &self.ratings_slice_digest,+ &self.free_offers_slice_digest,+ &self.inventory_digest,+ ]+ .into_iter()+ .any(invalid_digest){Err(CompiledPlanError::InvalidFactReference)} else {diff --git a/crates/gateway/src/core_runtime/response_diagnostics_tests.rs b/crates/gateway/src/core_runtime/response_diagnostics_tests.rsindex 68161f05..d255db96 100644--- a/crates/gateway/src/core_runtime/response_diagnostics_tests.rs+++ b/crates/gateway/src/core_runtime/response_diagnostics_tests.rs@@ -722,17 +722,14 @@ fn wait_finished(facts: &Facts, failed: bool) {let finished = records.iter().any(|r| r.pointer("/fact/kind").and_then(Value::as_str) == Some("request_finished"));- // The native completion producer can deliver its usage after the- // request's terminal fact. Successful fixtures require both known- // usage sources; assert_business still checks the exact count/content.+ // Canonical usage can arrive after the terminal fact. Provider usage+ // is omitted when canonical usage was already recorded, so it is not+ // a completion barrier. The business oracle checks each source below.let usage_complete = failed- || records- .iter()- .filter(|r| {- r.pointer("/fact/kind").and_then(Value::as_str) == Some("usage_and_cache")- })- .count()- >= 2;+ || records.iter().any(|r| {+ r.pointer("/fact/kind").and_then(Value::as_str) == Some("usage_and_cache")+ && r["fact"]["source"] == "accepted_canonical_model_event"+ });if finished && usage_complete {return;}@@ -772,13 +769,7 @@ fn assert_prebody_relay_business(facts: &[Value]) {assert_eq!(requests[0]["fact"]["attempts_started"], 2);assert_eq!(requests[0]["fact"]["attempts_finished"], 2);assert_eq!(named("semantic_commit").len(), 1);- let usage = named("usage_and_cache");- assert_eq!(usage.len(), 2);- for record in usage {- assert_eq!(record["fact"]["ordinal"], 2);- assert_eq!(record["fact"]["input_tokens"], 11);- assert_eq!(record["fact"]["output_tokens"], 7);- }+ assert_success_usage(facts, 2);}fn assert_business(facts: &[Value], failed: bool, after_body: bool) {@@ -866,21 +857,38 @@ fn assert_business(facts: &[Value], failed: bool, after_body: bool) {assert_eq!(requests[0]["fact"]["attempts_finished"], 1);let semantic_commits = named("semantic_commit").len();assert_eq!(semantic_commits, if failed && !after_body { 0 } else { 1 });- let usage = named("usage_and_cache");- // These failed entities report no usage: preserve absence rather than- // synthesizing zero tokens from an incomplete response.- assert_eq!(usage.len(), if failed { 0 } else { 2 });- if !failed {- assert_eq!(- usage- .iter()- .filter(|r| r["fact"]["source"] == "provider_completion")- .count(),- 1- );+ if failed {+ // Failed entities report no usage; never synthesize zero tokens.+ assert!(named("usage_and_cache").is_empty());+ } else {+ assert_success_usage(facts, 1);}+}++pub(super) fn assert_success_usage(facts: &[Value], ordinal: u64) {+ let usage: Vec<_> = facts+ .iter()+ .filter(|r| r["fact"]["kind"] == "usage_and_cache")+ .collect();+ let count = |source: &str| {+ usage+ .iter()+ .filter(|r| r["fact"]["source"] == source)+ .count()+ };+ assert_eq!(count("accepted_canonical_model_event"), 1);+ // completed_attempt suppresses provider usage if canonical usage arrived+ // first. Both callback orders must retain exactly one canonical record.+ assert!(count("provider_completion") <= 1);+ let attempt = facts+ .iter()+ .find(|r| r["fact"]["kind"] == "attempt_started" && r["fact"]["ordinal"] == ordinal)+ .unwrap();+ assert!(attempt["attempt_id"].is_string());for record in usage {- assert_eq!(record["fact"]["ordinal"], 1);+ assert_eq!(record["fact"]["ordinal"], ordinal);+ assert_eq!(record["attempt_id"], attempt["attempt_id"]);+ assert_eq!(record["correlation"], attempt["correlation"]);assert!(matches!(record["fact"]["source"].as_str(),Some("provider_completion" | "accepted_canonical_model_event")@@ -889,6 +897,7 @@ fn assert_business(facts: &[Value], failed: bool, after_body: bool) {assert_eq!(record["fact"]["output_tokens"], 7);}}+fn wait_replay_clean(root: &Path) {let deadline = Instant::now() + Duration::from_secs(5);loop {diff --git a/crates/gateway/src/observation/tests.rs b/crates/gateway/src/observation/tests.rsindex cdfa2771..8eb1e7ac 100644--- a/crates/gateway/src/observation/tests.rs+++ b/crates/gateway/src/observation/tests.rs@@ -1,3 +1,7 @@+#[cfg(all(unix, debug_assertions, feature = "e2e-test-control"))]+#[path = "tests/usage_order.rs"]+mod usage_order;+use serde_json::{Value, json};use hiroute_diagnostics::runtime::DiagnosticsPort;@@ -143,12 +147,21 @@ fn request_with_capture(diagnostics: DiagnosticsPort,enabled: bool,) -> RequestObservation {- let gateway = GatewayObservation::with_sinks_and_policy(- true,- 64 * 1024,- GatewayObservationSinks::discard(),+ request_with_sinks(policy,- );+ diagnostics,+ enabled,+ GatewayObservationSinks::discard(),+ )+}++fn request_with_sinks(+ policy: OtelContentPolicy,+ diagnostics: DiagnosticsPort,+ enabled: bool,+ sinks: GatewayObservationSinks,+) -> RequestObservation {+ let gateway = GatewayObservation::with_sinks_and_policy(true, 64 * 1024, sinks, policy);RequestObservation::new(super::request::RequestObservationCapture {enabled,diff --git a/crates/gateway/src/observation/tests/usage_order.rs b/crates/gateway/src/observation/tests/usage_order.rsnew file mode 100644index 00000000..2b238450--- /dev/null+++ b/crates/gateway/src/observation/tests/usage_order.rs@@ -0,0 +1,195 @@+//! Exercise the real observation callbacks in both legal orders. The listener+//! fixtures use the same oracle, so canonical-first deterministically covers+//! the scheduling order that failed on CI without sleeps or callback retries.+use super::*;+use std::sync::mpsc::{self, Receiver, Sender};+use std::time::{Duration, Instant};++use crate::server::core_runtime::model_ir::ModelUsage;+use crate::server::core_runtime::response_diagnostics_tests::assert_success_usage;+use hiroute_gateway_core::core::execution_plan::{+ CredentialRef, PlanRevision, ResolvedTargetBindingId,+};+use hiroute_gateway_core::runtime::attempt::{AttemptTransportFacts, CommitFence};+use hiroute_gateway_core::runtime::driver::{+ AttemptBudgetGrant, AttemptCleanupOutcome, AttemptCommitFacts, AttemptDownstreamOutcome,+ AttemptStreamOutcome, AttemptTerminationReason, CompletedAttemptObservation,+ ProviderClassificationFacts, RealtimeRoutingFacts, RouteDecisionId, UsageDimension, UsageFact,+};++struct RecordSink(Sender<Value>);+impl ObservationRecordSink for RecordSink {+ fn deliver(&self, record: &ObservationRecord) -> Result<ObservationAck, ObservationNack> {+ self.0+ .send(serde_json::from_slice(record.payload()).unwrap())+ .unwrap();+ Ok(accounted_acknowledgement(record))+ }+}++fn recorded_usage(canonical_first: bool) -> Vec<Value> {+ let (sender, receiver): (_, Receiver<Value>) = mpsc::channel();+ let mut sinks = GatewayObservationSinks::discard();+ sinks.execution_fact = Arc::new(RecordSink(sender));+ let request = request_with_sinks(+ OtelContentPolicy::Disabled,+ DiagnosticsPort::default(),+ true,+ sinks,+ );+ let credential = "credential/none/usage-order";+ request.no_credential_materialized("binding:test", credential);+ request.disposition_published(&PublishedDisposition {+ request_id: RequestId(9),+ attempt_id: AttemptId(4),+ generation: AttemptGeneration(2),+ disposition: Disposition::Accept,+ });+ assert!(request.accept_current("frame:test", 128).is_some());+ let now = Instant::now();+ let completion = CompletedAttemptObservation {+ route_decision_id: RouteDecisionId(1),+ attempt_id: AttemptId(4),+ generation: AttemptGeneration(2),+ binding: ResolvedTargetBindingId::new(PlanRevision(1), 1),+ credential_ref: CredentialRef::new(credential).unwrap(),+ budget: AttemptBudgetGrant {+ issued_at: now,+ allocated: Duration::from_secs(1),+ deadline: now + Duration::from_secs(1),+ },+ routing_facts: RealtimeRoutingFacts::default(),+ provider: Some(ProviderClassificationFacts {+ usage: Some(UsageFact {+ input: UsageDimension::reported(11),+ output: UsageDimension::reported(7),+ ..UsageFact::default()+ }),+ ..ProviderClassificationFacts::default()+ }),+ failure: None,+ transport: AttemptTransportFacts {+ started_at: now,+ upstream_protocol: None,+ connect_elapsed: None,+ request_write_elapsed: None,+ upstream_ttfb: None,+ last_upstream_progress_at: None,+ local_read_suppressed: Duration::ZERO,+ upstream_body_bytes: 128,+ timeout: None,+ },+ disposition: Disposition::Accept,+ commits: AttemptCommitFacts {+ upstream_request: CommitFence::WriteConfirmed,+ downstream_headers: CommitFence::WriteConfirmed,+ downstream_semantic: CommitFence::WriteConfirmed,+ },+ stream: AttemptStreamOutcome::CompletedEos,+ downstream: AttemptDownstreamOutcome::Completed,+ cleanup: AttemptCleanupOutcome::Completed,+ ended_at: now,+ termination_reason: AttemptTerminationReason::AcceptedEos,+ };+ let usage = ModelUsage {+ input_tokens: Some(11),+ output_tokens: Some(7),+ ..ModelUsage::default()+ };+ if canonical_first {+ request.usage_model(&usage);+ request.completed_attempt(&completion, None);+ } else {+ request.completed_attempt(&completion, None);+ request.usage_model(&usage);+ }+ request.finish("accepted");+ let deadline = Instant::now() + Duration::from_secs(5);+ let mut records = Vec::new();+ // All callbacks above have returned; this final record is a barrier for+ // their already-enqueued facts, not a scheduling assumption about workers.+ loop {+ let record = receiver+ .recv_timeout(deadline.saturating_duration_since(Instant::now()))+ .unwrap();+ let finished = record["fact"]["kind"] == "request_finished";+ records.push(record);+ if finished {+ break;+ }+ }+ let terminal = records.last().unwrap();+ assert_eq!(terminal["fact"]["outcome"], "accepted");+ assert_eq!(terminal["fact"]["facts_completeness"], "complete");+ assert_eq!(terminal["fact"]["attempts_started"], 1);+ assert_eq!(terminal["fact"]["attempts_finished"], 1);+ records+}++#[test]+fn canonical_usage_before_completion_satisfies_listener_oracle() {+ let records = recorded_usage(true);+ assert_success_usage(&records, 1);+ assert_eq!(+ records+ .iter()+ .filter(|r| r["fact"]["kind"] == "usage_and_cache")+ .count(),+ 1+ );+}++#[test]+fn provider_completion_before_canonical_usage_satisfies_listener_oracle() {+ let records = recorded_usage(false);+ assert_success_usage(&records, 1);+ assert_eq!(+ records+ .iter()+ .filter(|r| r["fact"]["kind"] == "usage_and_cache")+ .count(),+ 2+ );+}++#[test]+fn listener_usage_oracle_rejects_missing_duplicate_wrong_or_uncorrelated_usage() {+ let records = recorded_usage(false);+ for mutation in [+ "missing",+ "duplicate",+ "wrong_tokens",+ "wrong_attempt",+ "wrong_ordinal",+ "wrong_request",+ "unknown_source",+ ] {+ let mut invalid = records.clone();+ let position = invalid+ .iter()+ .position(|r| r["fact"]["source"] == "accepted_canonical_model_event")+ .unwrap();+ match mutation {+ "missing" => {+ invalid.remove(position);+ }+ "duplicate" => invalid.push(invalid[position].clone()),+ "wrong_tokens" => invalid[position]["fact"]["input_tokens"] = json!(12),+ "wrong_attempt" => invalid[position]["attempt_id"] = json!("another-attempt"),+ "wrong_ordinal" => invalid[position]["fact"]["ordinal"] = json!(2),+ "wrong_request" => {+ invalid[position]["correlation"]["request_id"] = json!("another-request")+ }+ "unknown_source" => {+ let mut unexpected = invalid[position].clone();+ unexpected["fact"]["source"] = json!("unknown");+ invalid.push(unexpected);+ }+ _ => unreachable!(),+ }+ assert!(+ std::panic::catch_unwind(|| assert_success_usage(&invalid, 1)).is_err(),+ "oracle accepted {mutation}"+ );+ }+}diff --git a/crates/integrations/src/model_connections/probe.rs b/crates/integrations/src/model_connections/probe.rsindex fa9f0a21..a8c3f9ff 100644--- a/crates/integrations/src/model_connections/probe.rs+++ b/crates/integrations/src/model_connections/probe.rs@@ -596,10 +596,7 @@ fn parse_page(bytes: &[u8]) -> Result<ParsedPage, ()> {}fn valid_model_id(value: &str) -> bool {- !value.is_empty()- && value.len() <= 512- && !value.chars().any(char::is_control)- && value.trim() == value+ hiroute_domain::valid_upstream_model_id(value)}fn percent_encode_query(value: &str) -> String {diff --git a/crates/integrations/src/model_connections/tests.rs b/crates/integrations/src/model_connections/tests.rsindex 0e410651..228651d1 100644--- a/crates/integrations/src/model_connections/tests.rs+++ b/crates/integrations/src/model_connections/tests.rs@@ -1,5 +1,94 @@use super::*;+fn id_validation_draft(id: &str) -> NativeModelConnectionDraftV1 {+ NativeModelConnectionDraftV1 {+ display_template_id: None,+ inference_model_id: None,+ candidate_ref: None,+ lineage_ref: "lineage/native/id-validation".into(),+ trusted_lineage_digest: None,+ display_name: "中文接入名称".into(),+ existing_source_id: None,+ edit_revision: 1,+ check_id: "check/id-validation".into(),+ base_url: "http://127.0.0.1:8123/v1".into(),+ base_kind: ModelConnectionBaseKindV1::ApiRoot,+ request_path_override: None,+ inventory_path_override: None,+ protocol: UpstreamProtocol::Responses,+ protocol_profile_id: "profile/custom/responses".into(),+ protocol_profile_revision: 1,+ protocol_header_semantics: GatewayHeaderSemanticsV1 {+ content_type: "application/json".into(),+ required_headers: Vec::new(),+ forbidden_forward_headers: Vec::new(),+ },+ authentication: GatewayAuthenticationSemanticsV1::None,+ additional_native_endpoints: Vec::new(),+ provenance: NativeConnectionProvenanceInputV1::UserConfigured {+ configuration_revision: 1,+ },+ qualification: NativeConnectionQualificationV1 {+ free_access: None,+ evidence_ref: None,+ },+ runtime_fallback_denied_model_ids: Default::default(),+ models: vec![NativeModelDeclarationV1 {+ upstream_model_id: id.into(),+ display_name: "中文模型名称".into(),+ catalog_configuration_id: None,+ membership: ComputeModelMembershipV2::UserDeclared,+ capabilities: NativeModelCapabilityDeclarationV1::default(),+ }],+ }+}++#[test]+fn native_draft_uses_the_same_opaque_id_contract_for_models_inference_and_denials() {+ for id in [+ "内网模型".to_owned(),+ "Model A/@revision?实验#1".into(),+ "\u{feff}模型\u{feff}".into(),+ "\u{feff}".into(),+ "模型🧠".into(),+ "🧠".repeat(128),+ "x".repeat(512),+ "界".repeat(170) + "ab",+ ] {+ let mut draft = id_validation_draft(&id);+ validate_draft(&draft, &NativeModelConnectionCredentialV1::NotRequired).unwrap();+ draft.inference_model_id = Some(id.clone());+ validate_draft(&draft, &NativeModelConnectionCredentialV1::NotRequired).unwrap();+ draft.inference_model_id = None;+ draft.runtime_fallback_denied_model_ids.insert(id);+ validate_draft(&draft, &NativeModelConnectionCredentialV1::NotRequired).unwrap();+ }+}++#[test]+fn native_draft_rejects_invalid_provider_ids_before_any_probe() {+ for id in [+ " bad".to_owned(),+ "bad\u{a0}".into(),+ "bad\tmodel".into(),+ "bad\0model".into(),+ "bad\u{85}model".into(),+ "\u{85}bad".into(),+ "bad\u{85}".into(),+ "界".repeat(171),+ "🧠".repeat(129),+ ] {+ let invalid = id_validation_draft(&id);+ assert!(matches!(+ validate_draft(&invalid, &NativeModelConnectionCredentialV1::NotRequired),+ Err(NativeModelConnectionErrorV1::InvalidDraft)+ ));+ let mut denied = id_validation_draft("内网模型");+ denied.runtime_fallback_denied_model_ids.insert(id);+ assert!(validate_draft(&denied, &NativeModelConnectionCredentialV1::NotRequired).is_err());+ }+}+fn known<T>(value: T) -> NativeCandidateFactValueV1<T> {NativeCandidateFactValueV1 {value: Some(value),diff --git a/crates/integrations/src/model_connections/validation.rs b/crates/integrations/src/model_connections/validation.rsindex 9cec9121..e6cbc943 100644--- a/crates/integrations/src/model_connections/validation.rs+++ b/crates/integrations/src/model_connections/validation.rs@@ -5,7 +5,7 @@ pub(super) fn validate_draft(credential: &NativeModelConnectionCredentialV1<'_>,) -> Result<(), NativeModelConnectionErrorV1> {if draft.inference_model_id.as_ref().is_some_and(|id| {- !bounded_text(id, 512)+ !hiroute_domain::valid_upstream_model_id(id)|| draft.runtime_fallback_denied_model_ids.contains(id)|| !draft.models@@ -38,7 +38,7 @@ pub(super) fn validate_draft(|| draft.runtime_fallback_denied_model_ids.iter()- .any(|value| !bounded_text(value, 512) || value.trim() != value)+ .any(|value| !hiroute_domain::valid_upstream_model_id(value))|| draft.existing_source_id.as_ref()@@ -107,8 +107,7 @@ pub(super) fn validate_draft(};let mut model_ids = std::collections::BTreeSet::new();let models_valid = draft.models.iter().all(|model| {- bounded_text(&model.upstream_model_id, 512)- && model.upstream_model_id.trim() == model.upstream_model_id+ hiroute_domain::valid_upstream_model_id(&model.upstream_model_id)&& bounded_text(&model.display_name, 256)&& model.catalog_configuration_iddiff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex 3a492722..721e295f 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -39,7 +39,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi| Connect a native Codex or Claude subscription | [Source discovery](../../crates/integrations/src/agents/subscription_sources.rs), [credential adapters](../../crates/cpa-bridge/src), [shared lifecycle](../../crates/daemon/src/control/runtime/subscriptions.rs), [provider runtimes](../../crates/cpa-bridge/src/runtime_set.rs) | Native clients retain refresh authority; only access leases enter isolated CPA instances. Keychain interaction is limited to an explicit check; discovery reads metadata only. || Sign in independently to a Codex or Claude subscription | [Shared login control](../../crates/application/src/control_plane/subscription_login.rs), [protected lifecycle](../../crates/daemon/src/control/runtime/subscriptions/login.rs), [private sessions](../../crates/cpa-bridge/src/managed_sessions.rs), [Desktop sign-in](../../apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx) | CPA owns the new authorization and refresh; login is separate from Check/Save and routing. Daemon maintenance owns pending completion/expiry, and saved revisions own runtime selection. [The pinned CPA adapter](../../vendor/cpa/README.md) explains refresh ownership and request recovery. || Lease a subscription credential without blocking Gateway workers | [Async adapter](../../crates/daemon/src/gateway_ports/credential/cpa.rs), [request budget](../../crates/cpa-bridge/src/request_context.rs), [admission and observations](../../crates/cpa-bridge/src/runtime/admission.rs), [Claude identity resolution](../../crates/cpa-bridge/src/claude_profile.rs) | Bounded provider executors own compatibility I/O. Short admission updates revoke before lifecycle work; identity lookup runs outside the lifecycle owner. Cancellation and saved revisions guard later publication. Follow [concurrency regressions](../../crates/cpa-bridge/src/runtime/tests/request_io.rs) for races with disable, replacement and delayed I/O. |-| Make a saved source usable by a plan | [Capability qualification](../../crates/application/src/compute_management/compilation.rs), [candidate materialization](../../crates/daemon/src/control/runtime/candidate_execution.rs), [compiler](../../crates/application/src/compiler) | Native-observed facts retain source-local authority and budgets; display/save alone does not prove route eligibility |+| Make a saved source usable by a plan | [Capability qualification](../../crates/application/src/compute_management/compilation.rs), [candidate materialization](../../crates/daemon/src/control/runtime/candidate_execution.rs), [compiler](../../crates/application/src/compiler) | Native-observed facts retain source-local authority and budgets; [unavailable candidate reasons](../../crates/daemon/src/control/runtime/routing_candidates.rs) are read-only and never execution facts. Upstream model values use the shared opaque-ID rule; internal references remain strict || Distinguish a missing subscription candidate from a runtime outage | [Exact candidate projection](../../crates/daemon/src/control/runtime/compute_routing.rs), [source authorization](../../crates/daemon/src/control/runtime/source_authorization.rs), [provider discovery](../../crates/cpa-bridge/src/runtime_set.rs) | Resolve the requested provider from the trusted connection option. Its discovery error remains Unavailable; a best-effort aggregate list cannot establish that a selected source is absent. || Configure models and collaboration independently | [Shared settings transaction](../../crates/application/src/agent_connection/settings), [typed native facts](../../crates/daemon/src/control/runtime/settings_facts), [native provider guide](../../crates/integrations/src/agents/additional_native/README.md) | Native defaults, model grants, installed Skills and conditional restore have distinct owners || Project native reasoning settings | [Wire types](../../crates/domain/src/routing/gateway_execution.rs), [daemon renderer](../../crates/daemon/src/control/runtime/candidate_protocol_profiles.rs), [Gateway reader](../../crates/gateway/src/profiles/reasoning.rs) and [wire normalization](../../crates/gateway/src/adapters/request/reasoning.rs) | Keep one field/path/toggle definition; [materializer → compiler → Gateway tests](../../crates/daemon/src/control/runtime/candidate_execution_tests.rs) cover accepted aliases |