Skip to content

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.

fix(desktop): improve smart routing layout and context controls (#41)

澄潭5596167ba66e
diff --git a/apps/desktop/src/features/PlanRuntimeSettings.tsx b/apps/desktop/src/features/PlanRuntimeSettings.tsx
new file mode 100644
index 00000000..ccb0dd40
--- /dev/null
+++ b/apps/desktop/src/features/PlanRuntimeSettings.tsx
@@ -0,0 +1,132 @@
+import { useState } from 'react';
+import type { Editor, Options, PlanEditorMemory } from '../plan-editor';
+import { contextWindowError } from '../plan-context-window';
+import { requestTimeoutError } from '../plan-request-timeout';
+import { Disclosure, UiIcon } from '../ui';
+
+type CapabilityIssue = Extract<NonNullable<Options['codex_capabilities']>, { state: 'unavailable' }>['issues'][number];
+
+export function PlanRuntimeSettings({ limits, options, language, editingMemory, onChange }: {
+ limits: Editor['limits'];
+ options: Options | null;
+ language: 'zh' | 'en';
+ editingMemory: PlanEditorMemory;
+ onChange(limits: Editor['limits']): void;
+}) {
+ const en = language === 'en';
+ const text = (zh: string, eng: string) => en ? eng : zh;
+ const [previewAgent, setPreviewAgent] = useState<'codex' | 'claude'>('codex');
+ const bounds = options?.context_window;
+ const custom = limits.context_window_tokens !== undefined;
+ const windowError = contextWindowError(limits.context_window_tokens, bounds, language);
+ const timeoutError = requestTimeoutError(limits.request_timeout_ms, limits.attempt_timeout_ms, language);
+ const codex = options?.codex_capabilities;
+ const claude = options?.claude_capabilities;
+ const format = (tokens: number) => tokens.toLocaleString(en ? 'en-US' : 'zh-CN');
+ const compact = (tokens: number) => tokens >= 1000 && tokens % 1000 === 0 ? `${tokens / 1000}K` : format(tokens);
+ const bindings = (ids: string[]) => ids.map(id => options?.candidates.find(candidate => candidate.binding_id === id)?.display_name ?? id).join(text('、', ', '));
+ function changeWindowMode(mode: string) {
+ if (mode === 'auto') {
+ editingMemory.customWindowTokens = limits.context_window_tokens;
+ onChange({ ...limits, context_window_tokens: undefined });
+ } else {
+ onChange({ ...limits, context_window_tokens: editingMemory.customWindowTokens ?? bounds?.default_tokens ?? 272000 });
+ }
+ }
+ function capabilityIssue(issue: CapabilityIssue) {
+ const candidate = issue.binding_id ? bindings([issue.binding_id]) : text('当前路由', 'This route');
+ const reason = issue.kind === 'responses_protocol' ? text('缺少 Codex Responses 协议', 'is missing the Codex Responses protocol')
+ : issue.kind === 'request_capabilities' ? text('Codex Responses 请求路径的协议能力无法证明(不一定是模型元信息缺失)', 'cannot prove the required Codex Responses protocol semantics (not necessarily missing model metadata)')
+ : issue.kind === 'instruction_roles' ? text('当前接口无法保留 Codex 常规请求中的独立 developer 指令或中途指令位置;若是 Messages 来源,请改用原生 Responses', 'cannot preserve Codex developer instructions or mid-conversation instruction positions; use native Responses for a Messages source')
+ : issue.kind === 'context_input' ? text('缺少输入上下文上限', 'is missing its input context limit')
+ : issue.kind === 'context_output' ? text('缺少输出上限', 'is missing its output limit')
+ : issue.kind === 'context_total' ? text('缺少总上下文上限', 'is missing its total context limit')
+ : issue.kind === 'reasoning_profile' ? text('缺少所选推理配置事实', 'is missing facts for the selected reasoning configuration')
+ : issue.kind === 'context_window' ? text('无法得到有效上下文窗口', 'does not yield a valid context window')
+ : issue.kind === 'plan_compilation' ? text('当前候选无法按发布规则编译', 'cannot be compiled under the publication rules')
+ : text('编译后的路由事实无效', 'has invalid compiled routing facts');
+ return en ? `${candidate} ${reason}.` : `${candidate}:${reason}。`;
+ }
+
+ return <section className="editor-section plan-runtime-settings">
+ <div className="editor-section-heading"><h3>{text('上下文与等待时间', 'Context and wait time')}</h3></div>
+ <div className="plan-runtime-grid">
+ <div data-plan-context-window>
+ <label className="field">
+ <span className="field-label">{text('上下文窗口', 'Context window')}</span>
+ <select className="select plan-context-mode" value={custom ? 'custom' : 'auto'} onChange={event => changeWindowMode(event.target.value)}>
+ <option value="auto">{text('自动(默认)', 'Automatic (default)')}</option>
+ <option value="custom">{text('自定义', 'Custom')}</option>
+ </select>
+ </label>
+ {custom && <label className="field">
+ <span className="field-label">{text('窗口大小(tokens)', 'Window size (tokens)')}</span>
+ <input className="input plan-context-window-field" type="number" required min="1" step="1" max={bounds?.maximum_tokens}
+ value={limits.context_window_tokens === 0 ? '' : limits.context_window_tokens}
+ aria-invalid={Boolean(windowError)}
+ onChange={event => onChange({ ...limits, context_window_tokens: event.target.value === '' ? 0 : Number(event.target.value) })} />
+ </label>}
+ <p className="field-help plan-current-window" data-plan-window-current>
+ {bounds && !windowError
+ ? text(`当前窗口 ${format(limits.context_window_tokens ?? bounds.default_tokens)} tokens`, `Current window ${format(limits.context_window_tokens ?? bounds.default_tokens)} tokens`)
+ : windowError ? text('请修正自定义窗口。', 'Correct the custom window.')
+ : text('完成模型组合配置后显示可用窗口。', 'Complete the model groups to see the available window.')}
+ </p>
+ {bounds && <p className="field-help">{text(`默认 ${format(bounds.default_tokens)} · 候选共同上界 ${format(bounds.maximum_tokens)} tokens`, `Default ${format(bounds.default_tokens)} · Shared candidate limit ${format(bounds.maximum_tokens)} tokens`)}</p>}
+ {windowError && <p className="oc-inline-error" role="alert">{windowError}</p>}
+ </div>
+ <div data-plan-request-timeout>
+ <label className="field">
+ <span className="field-label">{text('单次请求最长等待(秒)', 'Maximum wait per request (seconds)')}</span>
+ <input className="input plan-request-timeout-field" type="number" min={Math.ceil(limits.attempt_timeout_ms / 1000)} max={3600} step={1}
+ value={limits.request_timeout_ms / 1000} aria-invalid={Boolean(timeoutError)}
+ onChange={event => onChange({ ...limits, request_timeout_ms: event.target.value === '' ? 0 : Number(event.target.value) * 1000 })} />
+ </label>
+ <p className="field-help">{text('包含重试和流式输出;超过时限会中断回复。新计划默认 1 小时。', 'Includes retries and streaming. A response is interrupted at the limit. New plans default to 1 hour.')}</p>
+ {timeoutError && <p className="oc-inline-error" role="alert">{timeoutError}</p>}
+ </div>
+ </div>
+ <div className="plan-capability-preview">
+ <label className="plan-preview-target"><span className="field-label">{text('目标 Agent 能力预览', 'Target Agent capability preview')}</span>
+ <select className="select" value={previewAgent} onChange={event => setPreviewAgent(event.target.value as 'codex' | 'claude')}>
+ <option value="codex">Codex</option><option value="claude">Claude Code</option>
+ </select>
+ </label>
+ {previewAgent === 'codex' && codex && <div className="codex-capability-summary" data-codex-capability-state={codex.state}>
+ {codex.state === 'available' ? <>
+ <div className="plan-capability-value" data-codex-capability-summary>
+ <strong>{text(`上下文 ${compact(codex.context_window)} · 输入 ${codex.input_modalities.includes('image') ? '文本/图片' : '文本'}`, `Context ${compact(codex.context_window)} · Input ${codex.input_modalities.includes('image') ? 'text/images' : 'text'}`)}</strong>
+ <span>{text('推理强度由路由配置决定', 'Reasoning effort is determined by the route configuration')}</span>
+ </div>
+ {codex.limitations.map(limit => <div className="callout warn" role="status" data-codex-capability-limit={limit.kind} key={limit.kind}>
+ <UiIcon name="warning" /><div>
+ <strong>{limit.kind === 'context_window' ? text('候选收窄了共同上下文', 'A candidate narrows the shared context') : text('候选收窄了图片输入', 'A candidate narrows image input')}</strong>
+ <p>{limit.kind === 'context_window'
+ ? text(`${bindings(limit.binding_ids)} 将共同上下文限制为 ${compact(bounds?.maximum_tokens ?? codex.context_window)}。`, `${bindings(limit.binding_ids)} limits the shared context to ${compact(bounds?.maximum_tokens ?? codex.context_window)}.`)
+ : text(`${bindings(limit.binding_ids)} 不支持完整的 Codex 图片输入;最终目录只声明文本。`, `${bindings(limit.binding_ids)} does not support complete Codex image input, so the final catalog declares text only.`)}</p>
+ </div>
+ </div>)}
+ </> : <div className="callout bad" role="alert" data-codex-capability-unavailable><UiIcon name="warning" /><div>
+ <strong>{text('无法生成可靠的 Codex 客户端能力', 'Reliable Codex client capabilities are unavailable')}</strong>
+ {codex.issues.map((issue, index) => <p key={`${issue.kind}:${issue.binding_id ?? index}`}>{capabilityIssue(issue)}</p>)}
+ </div></div>}
+ </div>}
+ {previewAgent === 'claude' && (claude?.state === 'available'
+ ? <p className="plan-capability-value">{text(`自动压缩窗口最多 ${compact(claude.context_window)} tokens`, `Auto-compact window up to ${compact(claude.context_window)} tokens`)}</p>
+ : <p className="field-help">{claude?.state === 'unavailable' && claude.reason === 'context_window_below_minimum'
+ ? text('Claude Code 自动压缩窗口最低为 100K;请调整计划窗口或使用 Codex。', 'Claude Code requires an auto-compact window of at least 100K. Adjust the plan window or use Codex.')
+ : text('当前候选或窗口尚不能用于 Claude Code;需要可用的 Messages 入口和有效窗口。', 'The current candidates or window are unavailable for Claude Code. A usable Messages ingress and valid window are required.')}</p>)}
+ <Disclosure className="native-details plan-capability-details" label={text('能力依据与生效方式', 'Capability details and applying changes')} language={language}>
+ <p className="field-help">{text('默认最多使用 272,000 tokens,受候选共同上界约束。较大的窗口可能增加上下文与缓存费用。', 'The default is at most 272,000 tokens, bounded by the shared candidate limit. Larger windows may increase context and cache costs.')}</p>
+ <p className="field-help">{text('已接入的 Agent 需重新保存模型设置并重新启动,才能加载更新后的窗口;进行中的会话不会立即改变。', 'Save the Agent model settings again and restart the client to load the updated window. Running sessions do not change immediately.')}</p>
+ {previewAgent === 'codex' ? <>
+ <p className="field-help">{text('依据当前编辑内容及候选的 Codex Responses 入口能力计算。上游使用其他协议时仍可能通过 HiRoute 适配;发布和接入时会重新核对,预览不代表真实客户端验证。', 'Calculated from the current edit and candidate Codex Responses ingress capabilities. HiRoute may adapt another upstream protocol; publication and connection recheck compatibility, and this preview is not a live client verification.')}</p>
+ {codex?.state === 'available' && codex.fixed_limits.includes('parallel_tool_calls_disabled') && <div className="callout" data-codex-fixed-limit="parallel_tool_calls_disabled"><UiIcon name="info" /><div>
+ <strong>{text('HiRoute 当前固定使用串行工具调用', 'HiRoute currently uses serial tool calls')}</strong>
+ <p>{text('这是当前实现限制,不由任何候选模型造成。', 'This is a fixed implementation limit, not a candidate-model limitation.')}</p>
+ </div></div>}
+ </> : <p className="field-help">{text('作用于整个 Claude Code 进程;接入多个计划时取最小窗口,原生模型可能更早压缩。接入时会核对窗口、配置冲突和请求能力。', 'Applies to the whole Claude Code process. Multiple plans share the smallest window; native models may compact earlier. Connection checks window constraints, configuration conflicts and request capabilities.')}</p>}
+ </Disclosure>
+ </div>
+ </section>;
+}
diff --git a/apps/desktop/src/occami/styles/pages.css b/apps/desktop/src/occami/styles/pages.css
index b3a82b46..63ffd12a 100644
--- a/apps/desktop/src/occami/styles/pages.css
+++ b/apps/desktop/src/occami/styles/pages.css
@@ -398,6 +398,39 @@ button.list-row { width: 100%; border-top: 0; border-right: 0; border-left: 0; c
button.option-row { width: 100%; text-align: left; }
button.option-row[aria-pressed='true'] { border-color: var(--accent); background: var(--accent-soft); }
.classifier-choice > .badge { flex: none; margin-top: 0; }
+.plan-editor .editor-section { padding: 28px 0; }
+.plan-editor .editor-section-heading { margin-bottom: 18px; }
+.plan-fallback { margin-top: 16px; }
+.plan-editor button.route-toggle-row,
+.plan-editor button.route-toggle-row[aria-pressed='true'] { padding: 12px 0; border: 0; border-radius: 0; background: transparent; }
+.plan-classification .classifier-choices { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
+.classifier-choice > .icon { flex: none; color: var(--accent); }
+.plan-classifier-config { margin-top: 22px; }
+.plan-classifier-config > label { display: grid; gap: 7px; }
+.plan-classifier-config > .editor-section-heading { margin-bottom: 0; }
+.plan-runtime-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; }
+.plan-runtime-grid > div { min-width: 0; }
+.plan-editor .plan-runtime-grid .field { margin: 0; }
+.plan-editor .plan-runtime-grid .field + .field { margin-top: 12px; }
+.plan-runtime-grid .select { width: 100%; }
+.plan-runtime-grid .field-help { margin: 8px 0 0; }
+.plan-runtime-grid .plan-current-window { color: var(--text-soft); }
+.plan-capability-preview { margin-top: 24px; }
+.plan-preview-target { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; }
+.plan-preview-target .field-label { margin: 0; }
+.plan-editor .plan-preview-target .select { width: auto; min-width: 120px; }
+.plan-capability-value { display: grid; gap: 4px; margin: 12px 0; font-size: calc(12px * var(--hr-text-scale)); }
+.plan-capability-value > span { color: var(--text-muted); font-size: calc(11px * var(--hr-text-scale)); }
+.plan-capability-preview .callout { margin-top: 10px; }
+.plan-capability-details { margin-top: 16px; }
+.plan-more-settings .editor-subsection { padding: 18px 0; border-bottom: 1px solid var(--divider); }
+.plan-more-settings .editor-subsection:last-child { padding-bottom: 0; border-bottom: 0; }
+.plan-more-settings .editor-subsection > h3 { margin: 0 0 10px; font-size: calc(14px * var(--hr-text-scale)); }
+.plan-more-settings button.option-row,
+.plan-more-settings button.option-row[aria-pressed='true'] { border: 0; border-radius: 0; padding: 12px 0; background: transparent; }
+@media(max-width:760px) {
+ .plan-classification .classifier-choices, .plan-runtime-grid { grid-template-columns: minmax(0, 1fr); }
+}
.classifier-protocol { display: grid; gap: 22px; }
.classifier-protocol section { min-width: 0; }
.classifier-protocol h3 { margin: 0; font-size: calc(14px * var(--hr-text-scale)); }
diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsx
index a9e75a8e..0138068c 100644
--- a/apps/desktop/src/plan-editor.tsx
+++ b/apps/desktop/src/plan-editor.tsx
@@ -8,6 +8,7 @@ import { ModelPicker } from './ui/ModelPicker';
import { BrandIcon, Disclosure, UiIcon } from './ui';
import { WorkerDependencies } from './features/WorkerDependencies';
import { PlanQuality, type PlanQualityModel } from './features/PlanQuality';
+import { PlanRuntimeSettings } from './features/PlanRuntimeSettings';
import { ClassifierProtocolDialog } from './features/ClassifierProtocolDialog';
import { confirmSaveDraftOrDiscard, useDiscardGuard } from './ui/discard-guard';
import { resolvePersistedEditor, type PersistedEditor, type PersistenceIdentity, type PlanOperation } from './plan-editor-persistence';
@@ -23,6 +24,8 @@ type SmartClassifier = { kind: 'local_rules' } | {
timeout_ms: number;
auth_header?: ClassifierAuthHeader | null;
};
+// Inactive inputs belong to this editing session, never to the persisted plan.
+export type PlanEditorMemory = { restClassifier?: Extract<SmartClassifier, { kind: 'rest' }>; customWindowTokens?: number };
type Smart = { economy: Selection[]; primary: Selection[]; primary_fallback: boolean; reselect_on_user_message: boolean; classifier: SmartClassifier; complex_keywords: string[] };
type Free = { candidates: Selection[]; primary: Selection[]; primary_fallback: boolean };
export type Editor = { schema: string; display_name: string; purpose: string; custom_alias?: string; mode: Mode; candidates: Selection[]; smart: Smart; free: Free; delegation_enabled: boolean; work?: Work; requirements: Record<string, unknown>; limits: { context_window_tokens?: number; maximum_attempts: number; request_timeout_ms: number; attempt_timeout_ms: number } };
@@ -106,14 +109,13 @@ function activePlanQualityModels(plan: Plan, candidates: Candidate[]): PlanQuali
}
return models;
}
-export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; language: 'zh' | 'en'; active?: boolean; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, language, active = true, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {
+export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Draft; creating?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory; language: 'zh' | 'en'; active?: boolean; usedBy?: { id: string; name: string; brand: 'codex' | 'claude-code' | 'agent'; isDefault: boolean }[]; onOpenAgent?: (agentId: string) => void; onOpenSession?: (sessionId: string, requestId: string) => void; onDone: () => Promise<void>; onClose: () => void; onDirty?: (dirty: boolean) => void; onEdit?: () => void; onBusyChange?: (busy: boolean) => void; onOperation?: (operation: PlanOperation | null) => void; onPersisted?: (editor: PersistedEditor<Plan, Draft> | null, action: 'save_draft' | 'publish', identity: PersistenceIdentity, operation: PlanOperation | null) => void }>(function PlanEditor({ plan, draft, creating = false, initialBindingId, editingMemory, language, active = true, usedBy = [], onOpenAgent, onOpenSession, onDone, onClose, onDirty, onEdit, onBusyChange, onOperation, onPersisted }, ref) {
const en = language === 'en', text = (zh: string, eng: string) => en ? eng : zh;
const [editor, setEditor] = useState<Editor>(() => structuredClone(draft?.editor ?? (plan ? reopen(plan) : emptyEditor())));
const [draftId] = useState(() => draft?.draft_id ?? 'draft/' + crypto.randomUUID());
const [base, setBase] = useState(() => ({ expected_head_revision: draft ? draft.base_head_revision ?? null : plan?.head.head_revision ?? null, expected_draft_revision: draft?.revision ?? null }));
const [options, setOptions] = useState<Options | null>(null), [busy, setBusy] = useState(false), [error, setError] = useState('');
const [baseline, setBaseline] = useState(() => JSON.stringify(editor));
- const [previewAgent, setPreviewAgent] = useState<'codex' | 'claude'>('codex');
const [notice, setNotice] = useState('');
const [keywordInput, setKeywordInput] = useState('');
const [invalidFields, setInvalidFields] = useState(false);
@@ -122,6 +124,8 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
const classifierSecretInput = useRef<HTMLInputElement>(null);
const [classifierTest, setClassifierTest] = useState<ClassifierDecisionTestResult | null>(null);
const [classifierProtocolOpen, setClassifierProtocolOpen] = useState(false);
+ const memory = useRef(editingMemory ?? {}).current;
+ const [moreSettingsOpen, setMoreSettingsOpen] = useState(editor.delegation_enabled || (editor.mode === 'smart_saving' && editor.smart.reselect_on_user_message));
const [optionsError, setOptionsError] = useState('');
const [optionsRetry, setOptionsRetry] = useState(0);
const [effort, setEffort] = useState<{ name: string; native: Native; value: Selection['reasoning']; apply: (value: Selection['reasoning']) => void } | null>(null);
@@ -189,6 +193,12 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
if (!first) return;
update({ candidates: [{ binding_id: first.binding_id, reasoning: defaultReasoning(first.reasoning) }] });
}, [creating, options, editor.mode, editor.candidates.length, initialBindingId]);
+ function focusField(selector: string) {
+ const element = document.querySelector<HTMLElement>(selector);
+ let details = element?.closest('details');
+ while (details) { details.open = true; details = details.parentElement?.closest('details'); }
+ element?.focus();
+ }
function reportError(cause: unknown) { setError(planErrorMessage(cause, language)); setDiagnostic(planErrorCode(cause)); }
function update(patch: Partial<Editor>) { onEdit?.(); setEditor(e => ({ ...e, ...patch })); setError(''); setNotice(''); setDiagnostic(''); setValidationIssue(null); setClassifierTest(null); }
function validateRoute(): ValidationIssue | null {
@@ -249,27 +259,20 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
setValidationIssue(issue);
setError(issue.message);
requestAnimationFrame(() => {
- if (issue.field === 'alias') {
- const input = document.querySelector<HTMLInputElement>('.plan-alias-field');
- const details = input?.closest('details');
- if (details) details.open = true;
- input?.focus();
- } else if (issue.field === 'context_window') {
- document.querySelector<HTMLInputElement>('.plan-context-window-field')?.focus();
- } else if (issue.field === 'request_timeout') {
- document.querySelector<HTMLInputElement>('.plan-request-timeout-field')?.focus();
- } else if (issue.group === 'executor') {
- document.querySelector<HTMLElement>('.v3-executors button')?.focus();
- } else if (issue.group === 'classifier') {
+ if (issue.field === 'alias') focusField('.plan-alias-field');
+ else if (issue.field === 'context_window') focusField('.plan-context-window-field');
+ else if (issue.field === 'request_timeout') focusField('.plan-request-timeout-field');
+ else if (issue.group === 'executor') focusField('.v3-executors button');
+ else if (issue.group === 'classifier') {
const classifier = editor.smart.classifier;
- const selector = classifier.kind === 'rest'
- && validClassifierEndpoint(classifier.endpoint)
- && !validClassifierTimeout(classifier.timeout_ms)
- ? '.classifier-timeout-field'
- : '.classifier-endpoint-field';
- document.querySelector<HTMLInputElement>(selector)?.focus();
+ const selector = classifier.kind !== 'rest' || !validClassifierEndpoint(classifier.endpoint)
+ ? '.classifier-endpoint-field'
+ : !validClassifierTimeout(classifier.timeout_ms) ? '.classifier-timeout-field'
+ : classifier.auth_header && !/^[a-zA-Z0-9._\-/:]{1,256}$/.test(classifier.auth_header.value_secret_ref)
+ ? '.classifier-secret-ref-field' : '.classifier-header-field';
+ focusField(selector);
} else {
- document.querySelector<HTMLElement>(issue.bindingId ? `[data-binding-id="${CSS.escape(issue.bindingId)}"] .effort-select` : `[data-route-group="${issue.group}"] .add-candidate`)?.focus();
+ focusField(issue.bindingId ? `[data-binding-id="${CSS.escape(issue.bindingId)}"] .effort-select` : `[data-route-group="${issue.group}"] .add-candidate`);
}
});
return false;
@@ -419,25 +422,32 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
}
function classifierEditor() {
const classifier = editor.smart.classifier;
- const replace = (next: SmartClassifier) => update({ smart: { ...editor.smart, classifier: next } });
+ const replace = (next: SmartClassifier) => {
+ if (classifier.kind === 'rest') memory.restClassifier = classifier;
+ if (next.kind === 'rest') memory.restClassifier = next;
+ update({ smart: { ...editor.smart, classifier: next } });
+ };
const patchRest = (patch: Partial<Extract<SmartClassifier, { kind: 'rest' }>>) => {
if (classifier.kind === 'rest') replace({ ...classifier, ...patch });
};
return <>
- <div className="editor-section-heading"><div><h3>{text('如何判断任务复杂度', 'How should task complexity be determined?')}</h3><p>{text('自定义服务会增加一次有界外部调用;失败时固定回退内置规则。', 'A custom service adds one bounded external call; failures fall back to built-in rules.')}</p></div><button className="btn" type="button" onClick={() => setClassifierProtocolOpen(true)}>{text('查看接入协议', 'View protocol')}</button></div>
+ <div className="editor-section-heading"><h3>{text('任务判断', 'Task classification')}</h3></div>
<div className="option-panel classifier-choices">
- <button type="button" className="option-row classifier-choice" aria-pressed={classifier.kind === 'local_rules'} onClick={() => { if (classifier.kind !== 'local_rules') replace({ kind: 'local_rules' }); }}><div><strong>{text('内置规则', 'Built-in rules')}</strong><span>{text('默认,不访问外部分类服务', 'Default; no external classifier call')}</span></div><span className={`badge ${classifier.kind === 'local_rules' ? 'info' : ''} no-dot`}>{classifier.kind === 'local_rules' ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button>
- <button type="button" className="option-row classifier-choice" aria-pressed={classifier.kind === 'rest'} onClick={() => { if (classifier.kind !== 'rest') replace(defaultRestClassifier()); }}><div><strong>{text('自定义分类服务', 'Custom classifier service')}</strong><span>{text('连接你部署的分类服务,可基于 Jev、LLM 或其他自定义策略实现', 'Connect a classifier you deploy, powered by Jev, an LLM, or another custom strategy')}</span></div><span className={`badge ${classifier.kind === 'rest' ? 'info' : ''} no-dot`}>{classifier.kind === 'rest' ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button>
+ <button type="button" className="option-row classifier-choice" aria-pressed={classifier.kind === 'local_rules'} onClick={() => { if (classifier.kind !== 'local_rules') replace({ kind: 'local_rules' }); }}><div><strong>{text('内置规则', 'Built-in rules')}</strong><span>{text('根据任务特征判断,不访问外部服务', 'Uses task characteristics; no external service call')}</span></div>{classifier.kind === 'local_rules' && <UiIcon name="check" />}</button>
+ <button type="button" className="option-row classifier-choice" aria-pressed={classifier.kind === 'rest'} onClick={() => { if (classifier.kind !== 'rest') replace(memory.restClassifier ?? defaultRestClassifier()); }}><div><strong>{text('自定义分类服务', 'Custom classifier service')}</strong><span>{text('连接你部署的分类服务', 'Connect a classifier you deploy')}</span></div>{classifier.kind === 'rest' && <UiIcon name="check" />}</button>
</div>
- {classifier.kind === 'rest' && <div className="field" data-route-group="classifier">
+ {classifier.kind === 'rest' && <div className="field plan-classifier-config" data-route-group="classifier">
+ <div className="editor-section-heading"><div><h3>{text('自定义分类服务', 'Custom classifier service')}</h3><p>{text('可基于 Jev、LLM 或其他自定义策略实现;调用失败时回退内置规则。', 'Use Jev, an LLM, or another custom strategy; failed calls fall back to built-in rules.')}</p></div><button className="btn" type="button" onClick={() => setClassifierProtocolOpen(true)}>{text('查看接入协议', 'View protocol')}</button></div>
<div className="callout"><UiIcon name="info" /><span>{text('这是你信任的服务。HiRoute 会发送完整 latest_user 和简化的 Agent turn 历史;服务自行决定是否使用或按模型上下文裁剪。', 'This must be a service you trust. HiRoute sends the complete latest_user and simplified Agent-turn history; the service decides what to use and how to trim it.')}</span></div>
<label><span className="field-label">{text('分类服务地址', 'Classifier endpoint')}</span><input className="input classifier-endpoint-field" required maxLength={2048} aria-invalid={validationIssue?.group === 'classifier'} value={classifier.endpoint} placeholder="https://classifier.example/v1/decisions" onChange={event => patchRest({ endpoint: event.target.value })} /></label>
<label><span className="field-label">{text('分类超时(毫秒)', 'Classifier timeout (ms)')}</span><input className="input classifier-timeout-field" type="number" required min={1} max={MAX_CLASSIFIER_TIMEOUT_MS} step={1} aria-invalid={validationIssue?.group === 'classifier'} value={classifier.timeout_ms} onChange={event => patchRest({ timeout_ms: Number(event.target.value) })} /><span className="field-help">{text('覆盖历史准备、认证、连接和响应读取。外置服务自身的总超时应略小于此值;官方 Jev 默认 2800 ms。', 'Covers history preparation, authentication, connection, and response reading. Set the external service timeout slightly lower; the official Jev decider defaults to 2800 ms.')}</span></label>
+ <Disclosure className="native-details classifier-auth" label={text('认证设置', 'Authentication settings')} language={language} defaultOpen={Boolean(classifier.auth_header)}>
<div className="option-panel">
<button type="button" className="option-row" aria-pressed={!classifier.auth_header} onClick={() => patchRest({ auth_header: null })}><div><strong>{text('无认证', 'No authentication')}</strong><span>{text('适合本机或可信内网服务', 'For local or trusted-network services')}</span></div></button>
<button type="button" className="option-row" aria-pressed={Boolean(classifier.auth_header)} onClick={() => patchRest({ auth_header: classifier.auth_header ?? { name: 'Authorization', value_secret_ref: '' } })}><div><strong>{text('自定义认证头', 'Custom authentication header')}</strong><span>{text('值从 Secret 读取,不保存在计划中', 'The value comes from a Secret and is never stored in the plan')}</span></div></button>
</div>
- {classifier.auth_header && <><div className="oc-field-grid"><label><span className="field-label">{text('请求头名称', 'Header name')}</span><input className="input" required maxLength={128} value={classifier.auth_header.name} placeholder="Authorization" onChange={event => patchRest({ auth_header: { ...classifier.auth_header!, name: event.target.value } })} /></label><label><span className="field-label">{text('Secret 引用', 'Secret reference')}</span><input className="input" required maxLength={256} value={classifier.auth_header.value_secret_ref} placeholder="classifier/main" onChange={event => patchRest({ auth_header: { ...classifier.auth_header!, value_secret_ref: event.target.value } })} /></label></div><div className="oc-field-grid classifier-secret-create"><label><span className="field-label">{text('新建 Secret 的认证值', 'Authentication value for a new Secret')}</span><input ref={classifierSecretInput} className="input" type="password" autoComplete="new-password" maxLength={32768} placeholder="Bearer …" /></label><div className="field-actions"><button className="btn" type="button" onClick={() => void saveClassifierSecret(classifier)}>{text('安全保存 Secret', 'Save Secret securely')}</button><span className="field-help">{text('只创建新引用;替换时请使用新的引用。认证值不会写入计划。', 'Creates a new reference only; use a new reference to replace it. The value is not stored in the plan.')}</span></div></div></>}
+ {classifier.auth_header && <><div className="oc-field-grid"><label><span className="field-label">{text('请求头名称', 'Header name')}</span><input className="input classifier-header-field" required maxLength={128} value={classifier.auth_header.name} placeholder="Authorization" onChange={event => patchRest({ auth_header: { ...classifier.auth_header!, name: event.target.value } })} /></label><label><span className="field-label">{text('Secret 引用', 'Secret reference')}</span><input className="input classifier-secret-ref-field" required maxLength={256} value={classifier.auth_header.value_secret_ref} placeholder="classifier/main" onChange={event => patchRest({ auth_header: { ...classifier.auth_header!, value_secret_ref: event.target.value } })} /></label></div><div className="oc-field-grid classifier-secret-create"><label><span className="field-label">{text('新建 Secret 的认证值', 'Authentication value for a new Secret')}</span><input ref={classifierSecretInput} className="input" type="password" autoComplete="new-password" maxLength={32768} placeholder="Bearer …" /></label><div className="field-actions"><button className="btn" type="button" onClick={() => void saveClassifierSecret(classifier)}>{text('安全保存 Secret', 'Save Secret securely')}</button><span className="field-help">{text('只创建新引用;替换时请使用新的引用。认证值不会写入计划。', 'Creates a new reference only; use a new reference to replace it. The value is not stored in the plan.')}</span></div></div></>}
+ </Disclosure>
<div className="field-help">{text('请求仅包含允许分支、完整当前用户输入、简化历史、历史完整性和可评分范围。认证、上下文裁剪和策略部署由服务管理。', 'The request contains only allowed branches, the complete current user input, simplified history, history completeness, and the assessable range. The service owns authentication, context trimming, and strategy deployment.')}</div>
<div className="callout warn"><UiIcon name="warning" /><span>{text('测试会向上述服务发送一个要求选择省钱分支的固定合成问题,并可能产生服务费用;不会读取真实会话,保存和发布也不会自动测试。', 'Testing sends a fixed synthetic prompt that asks for the economy branch and may incur service charges. It does not read a real conversation, and saving or publishing never tests automatically.')}</span></div>
<div className="field-actions"><button className="btn" type="button" onClick={() => void testRestClassifier(classifier)}>{text('测试决策', 'Test decision')}</button>{classifierTest && <span className={`badge ${classifierTest.outcome === 'passed' ? 'good' : 'bad'} no-dot`}>{classifierTest.outcome === 'passed' ? text(`已选择 ${classifierTest.branch_id} · ${classifierTest.duration_millis} ms`, `Selected ${classifierTest.branch_id} · ${classifierTest.duration_millis} ms`) : text(`测试失败:${classifierTest.failure_code ?? 'unknown'}`, `Test failed: ${classifierTest.failure_code ?? 'unknown'}`)}</span>}</div>
@@ -447,65 +457,36 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr
}
const editorState = dirty ? text('有未发布更改', 'Unpublished changes') : base.expected_draft_revision !== null ? text('草稿已保存', 'Draft saved') : plan ? text('已启用', 'Active') : text('未发布', 'Unpublished');
const editorTone = dirty ? 'warn' : plan && base.expected_draft_revision === null ? 'good' : 'info';
- const codexCapabilities = options?.codex_capabilities;
- const formatContext = (tokens: number) => tokens >= 1000 && tokens % 1000 === 0 ? `${tokens / 1000}K` : tokens.toLocaleString(en ? 'en' : 'zh-CN');
- const capabilityBindings = (ids: string[]) => ids.map(id => options?.candidates.find(candidate => candidate.binding_id === id)?.display_name ?? id).join(text('、', ', '));
- const capabilityIssue = (issue: CodexCapabilityIssue) => {
- const candidate = issue.binding_id ? capabilityBindings([issue.binding_id]) : text('当前路由', 'This route');
- const reason = issue.kind === 'responses_protocol' ? text('缺少 Codex Responses 协议', 'is missing the Codex Responses protocol')
- : issue.kind === 'request_capabilities' ? text('Codex Responses 请求路径的协议能力无法证明(不一定是模型元信息缺失)', 'cannot prove the required Codex Responses protocol semantics (not necessarily missing model metadata)')
- : issue.kind === 'instruction_roles' ? text('当前接口无法保留 Codex 常规请求中的独立 developer 指令或中途指令位置;若是 Messages 来源,请改用原生 Responses', 'cannot preserve Codex developer instructions or mid-conversation instruction positions; use native Responses for a Messages source')
- : issue.kind === 'context_input' ? text('缺少输入上下文上限', 'is missing its input context limit')
- : issue.kind === 'context_output' ? text('缺少输出上限', 'is missing its output limit')
- : issue.kind === 'context_total' ? text('缺少总上下文上限', 'is missing its total context limit')
- : issue.kind === 'reasoning_profile' ? text('缺少所选推理配置事实', 'is missing facts for the selected reasoning configuration')
- : issue.kind === 'context_window' ? text('无法得到有效上下文窗口', 'does not yield a valid context window')
- : issue.kind === 'plan_compilation' ? text('当前候选无法按发布规则编译', 'cannot be compiled under the publication rules')
- : text('编译后的路由事实无效', 'has invalid compiled routing facts');
- return en ? `${candidate} ${reason}.` : `${candidate}:${reason}。`;
- };
return <section className="plan-editor" aria-label={text('路由编辑器', 'Plan editor')}>{!creating && <header className="editor-header"><div className="editor-title"><div className="title-with-status"><h2>{editor.display_name || text('新建智能路由', 'New smart routing')}</h2><span className={`badge ${editorTone} no-dot`}>{editorState}</span></div></div><div className="editor-actions"><button className="btn" type="button" disabled={busy || (!dirty && Boolean(plan || draft))} onClick={() => void act('save_draft')}>{text('保存草稿', 'Save draft')}</button><button type="button" className="btn btn-primary" disabled={busy || (!dirty && !!plan && base.expected_draft_revision === null)} onClick={() => void act('publish')}><UiIcon name="upload" />{plan ? text('发布更改', 'Publish changes') : text('启用', 'Enable')}</button></div></header>}
{notice && <div className="callout" role="status"><UiIcon name="info" /><span>{notice}</span></div>}{error && <div role="alert" className="callout bad" data-error-code={diagnostic}><UiIcon name="warning" /><span>{error}</span></div>}
<fieldset disabled={busy}><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', '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', 'Free first'][i])}</strong><span>{text(['按固定顺序依次尝试候选模型', '简单任务用省钱组合,复杂任务用主力组合', '先用免费模型,可选择主力兜底'][i], ['Try candidate models in a fixed order', 'Economy for simple tasks; primary for complex work', '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' && <section className="editor-section">
+ {editor.mode === 'smart_saving' && <><section className="editor-section plan-model-groups">
<div className="editor-section-heading"><div><h3>{text('简单任务与复杂任务', 'Simple and complex tasks')}</h3><p>{text('简单任务先用省钱组合;复杂任务直接使用主力组合。', 'Simple tasks use the economy group; complex tasks use the primary group.')}</p></div></div>
<div className="mini-route">{group(text('简单任务', 'Simple tasks'), text('省钱组合', 'Economy group'), editor.smart.economy, economy => update({ smart: { ...editor.smart, economy } }), { preferred: 'low', groupId: 'economy' })}<span className="lane-connector"><UiIcon name="route" /></span>{group(text('复杂任务', 'Complex tasks'), text('主力组合', 'Primary group'), editor.smart.primary, primary => update({ smart: { ...editor.smart, primary } }), { preferred: 'high', primary: true, groupId: 'primary' })}</div>
- <div className="option-panel"><button type="button" className="option-row" aria-pressed={editor.smart.primary_fallback} onClick={() => update({ smart: { ...editor.smart, primary_fallback: !editor.smart.primary_fallback } })}><div><strong>{text('省钱组合不可用时继续主力组合', 'Use primary when economy is unavailable')}</strong><span>{text('复杂任务不会降级到省钱组合', 'Complex tasks never downgrade to economy')}</span></div><span className={`switch${editor.smart.primary_fallback ? ' on' : ''}`} aria-hidden="true" /></button></div>
+ <div className="option-panel plan-fallback"><button type="button" className="option-row route-toggle-row" aria-pressed={editor.smart.primary_fallback} onClick={() => update({ smart: { ...editor.smart, primary_fallback: !editor.smart.primary_fallback } })}><div><strong>{text('省钱组合不可用时继续主力组合', 'Use primary when economy is unavailable')}</strong><span>{text('复杂任务不会降级到省钱组合', 'Complex tasks never downgrade to economy')}</span></div><span className={`switch${editor.smart.primary_fallback ? ' on' : ''}`} aria-hidden="true" /></button></div>
+ </section><section className="editor-section plan-classification">
{classifierEditor()}
- <div className="option-panel"><button type="button" className="option-row" aria-pressed={editor.smart.reselect_on_user_message} onClick={() => update({ smart: { ...editor.smart, reselect_on_user_message: !editor.smart.reselect_on_user_message } })}><div><strong>{text('追问时重新选择模型', 'Reselect model for each follow-up')}</strong><span>{editor.smart.reselect_on_user_message ? text('每次追问可重新选择模型。切换可能影响对话连贯性、缓存命中率,并因模型间推理状态不兼容导致请求失败。', 'Each follow-up may reselect a model. Switching can affect continuity and cache hits, and incompatible reasoning state can cause a request to fail.') : text('连续对话中的追问优先沿用当前模型。上下文重建或模型不可用时仍可能切换。', 'Follow-ups prefer the current model. A rebuilt context or an unavailable model can still cause a switch.')}</span></div><span className={`switch${editor.smart.reselect_on_user_message ? ' on' : ''}`} aria-hidden="true" /></button></div>
<Disclosure className="native-details keywords" label={text('关键词规则', 'Keyword rules')} language={language}><div className="editor-section-heading"><div><h3>{text('强制使用主力组合的关键词', 'Keywords that force the primary group')}</h3><p>{text('默认规则会识别多目标、架构、调试、跨文件和较长任务;REST 服务失败时也使用这些规则。', 'Default rules recognize multi-goal, architecture, debugging, cross-file and longer tasks; these rules are also used when the REST service fails.')}</p></div></div><div className="keyword-box">{editor.smart.complex_keywords.filter(Boolean).map(word => <span className="keyword-chip" key={word}>{word}<button type="button" aria-label={`${text('移除关键词', 'Remove keyword')} ${word}`} onClick={() => update({ smart: { ...editor.smart, complex_keywords: editor.smart.complex_keywords.filter(value => value !== word) } })}><UiIcon name="close" /></button></span>)}</div><div className="keyword-add"><input className="input" value={keywordInput} maxLength={64} placeholder={text('输入一个关键词或短语', 'Enter a keyword or phrase')} onChange={event => setKeywordInput(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); const word = keywordInput.trim(); if (word && !editor.smart.complex_keywords.includes(word)) update({ smart: { ...editor.smart, complex_keywords: [...editor.smart.complex_keywords, word] } }); setKeywordInput(''); } }} /><button className="btn" type="button" onClick={() => { const word = keywordInput.trim(); if (word && !editor.smart.complex_keywords.includes(word)) update({ smart: { ...editor.smart, complex_keywords: [...editor.smart.complex_keywords, word] } }); setKeywordInput(''); }}>{text('添加', 'Add')}</button></div></Disclosure>
- </section>}
+ </section></>}
{editor.mode === 'free_first' && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('免费候选', 'Free candidates')}</h3><p>{text('当前候选与顺序在发布后保持固定。', 'Candidates and order stay fixed after publication.')}</p></div><button className="btn" type="button" onClick={() => void useAllFree()}>{text('使用当前全部可用免费模型', 'Use all available free models')}</button></div><div className="free-lane">{group(text('免费模型', 'Free models'), text('固定顺序', 'Fixed order'), editor.free.candidates, candidates => update({ free: { ...editor.free, candidates } }), { free: true, preferred: 'low', groupId: 'free' })}</div><div className="editor-section-heading fallback-heading"><div><h3>{text('免费模型都不可用时', 'When all free models are unavailable')}</h3></div></div><div className="option-panel"><button type="button" className="option-row" aria-pressed={!editor.free.primary_fallback} onClick={() => update({ free: { ...editor.free, primary_fallback: false } })}><div><strong>{text('停止并提示,只使用免费模型', 'Stop and report; free models only')}</strong><span>{text('绝不会进入订阅或付费模型', 'Never use subscription or paid models')}</span></div><span className={`badge ${!editor.free.primary_fallback ? 'info' : ''} no-dot`}>{!editor.free.primary_fallback ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button><button type="button" className="option-row" aria-pressed={editor.free.primary_fallback} onClick={() => update({ free: { ...editor.free, primary_fallback: true } })}><div><strong>{text('继续使用主力模型', 'Continue with primary models')}</strong><span>{text('只有免费池全部不可用时才进入主力组合', 'Use primary only when the free pool is unavailable')}</span></div><span className={`badge ${editor.free.primary_fallback ? 'info' : ''} no-dot`}>{editor.free.primary_fallback ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button></div>{editor.free.primary_fallback && <div className="free-lane">{group(text('主力模型', 'Primary models'), text('免费池的兜底', 'Fallback for free pool'), editor.free.primary, primary => update({ free: { ...editor.free, primary } }), { preferred: 'high', primary: true, groupId: 'free-primary' })}</div>}</section>}
- <section className="editor-section" data-plan-context-window>
- <div className="editor-section-heading"><div><h3>{text('上下文窗口', 'Context window')}</h3><p>{text('默认最多使用 272,000 tokens;可在候选共同上界内调整。较大的窗口可能增加上下文与缓存费用。', 'Defaults to at most 272,000 tokens. Adjust within the shared candidate limit. Larger windows may increase context and cache costs.')}</p></div></div>
- <label className="field"><span className="field-label">{text('自定义窗口 · tokens(留空使用默认值)', 'Custom window · tokens (leave empty for default)')}</span>
- <input className="input plan-context-window-field" type="number" min="1" step="1" max={options?.context_window?.maximum_tokens} placeholder={String(options?.context_window?.default_tokens ?? 272000)} value={editor.limits.context_window_tokens ?? ''} aria-invalid={Boolean(!timeoutValidationError && editor.limits.context_window_tokens !== undefined && contextWindowError(editor.limits.context_window_tokens, options?.context_window, language))} onChange={event => update({ limits: { ...editor.limits, context_window_tokens: event.target.value === '' ? undefined : Number(event.target.value) } })} />
- </label>
- <p className="field-help">{text('已接入的 Agent 需重新保存模型设置并重新启动,才能加载更新后的窗口;进行中的会话不会立即改变。', 'For an existing Codex connection, save the Agent model settings again and restart Codex to load the updated window. Running sessions do not change immediately.')}</p>
- <button type="button" className="btn" disabled={editor.limits.context_window_tokens === undefined} onClick={() => update({ limits: { ...editor.limits, context_window_tokens: undefined } })}>{text('恢复默认', 'Restore default')}</button>
- <p className="field-help">{options?.context_window ? text(`默认 ${options.context_window.default_tokens.toLocaleString()} tokens · 候选共同上界 ${options.context_window.maximum_tokens.toLocaleString()} tokens`, `Default ${options.context_window.default_tokens.toLocaleString()} tokens · Shared candidate limit ${options.context_window.maximum_tokens.toLocaleString()} tokens`) : text('完成候选配置后显示可用上界。', 'Complete the candidate configuration to see the available limit.')}</p>
- {!timeoutValidationError && editor.limits.context_window_tokens !== undefined && contextWindowError(editor.limits.context_window_tokens, options?.context_window, language) && <p className="oc-inline-error" role="alert">{contextWindowError(editor.limits.context_window_tokens, options?.context_window, language)}</p>}
- </section>
- <section className="editor-section" data-plan-request-timeout>
- <div className="editor-section-heading"><div><h3>{text('单次请求最长等待', 'Maximum wait per request')}</h3><p>{text('包含请求内重试和流式输出;超过时限会中断仍在输出的回复。新计划默认 1 小时。', 'Includes retries and streaming output. A response still streaming at the limit is interrupted. New plans default to 1 hour.')}</p></div></div>
- <label className="field"><span className="field-label">{text('等待时间(秒)', 'Wait time (seconds)')}</span>
- <input className="input plan-request-timeout-field" type="number" min={Math.ceil(editor.limits.attempt_timeout_ms / 1000)} max={3600} step={1} value={editor.limits.request_timeout_ms / 1000} aria-invalid={Boolean(timeoutValidationError)} onChange={event => update({ limits: { ...editor.limits, request_timeout_ms: event.target.value === '' ? 0 : Number(event.target.value) * 1000 } })} />
- </label>
- {timeoutValidationError && <p className="oc-inline-error" role="alert">{timeoutValidationError}</p>}
- </section>
- <section className="editor-section"><label className="field-label">{text('目标 Agent 能力预览', 'Target Agent capability preview')}<select className="select" value={previewAgent} onChange={event => setPreviewAgent(event.target.value as 'codex' | 'claude')}><option value="codex">Codex</option><option value="claude">Claude Code</option></select></label></section>
- {previewAgent === 'claude' && <section className="editor-section"><h3>Claude Code</h3>{options?.claude_capabilities?.state === 'available' ? <><p>{text(`自动压缩窗口最多 ${formatContext(options.claude_capabilities.context_window)} tokens`, `Auto-compact window up to ${formatContext(options.claude_capabilities.context_window)} tokens`)}</p><p className="field-help">{text('作用于整个 Claude Code 进程;接入多个计划时取最小窗口,原生模型可能更早压缩。接入时会核对窗口、配置冲突和请求能力。', 'Applies to the whole Claude Code process. Multiple plans share the smallest window; native models may compact earlier. Connection checks window constraints, configuration conflicts and request capabilities.')}</p></> : <p className="field-help">{options?.claude_capabilities?.state === 'unavailable' && options.claude_capabilities.reason === 'context_window_below_minimum' ? text('Claude Code 自动压缩窗口最低为 100K;请调整计划窗口或使用 Codex。', 'Claude Code requires an auto-compact window of at least 100K. Adjust the plan window or use Codex.') : text('当前候选或窗口尚不能用于 Claude Code;需要可用的 Messages 入口和有效窗口。', 'The current candidates or window are unavailable for Claude Code. A usable Messages ingress and valid window are required.')}</p>}</section>}
- {previewAgent === 'codex' && codexCapabilities && <section className="editor-section codex-capability-summary" data-codex-capability-state={codexCapabilities.state}><div className="editor-section-heading"><div><h3>{text('对 Codex 的能力预览', 'Codex capability preview')}</h3><p>{text('依据当前编辑内容及候选的 Codex Responses 入口能力计算。上游使用其他协议时仍可能通过 HiRoute 适配;发布和接入时会重新核对,预览不代表真实客户端验证。', 'Calculated from the current edit and candidate Codex Responses ingress capabilities. HiRoute may adapt another upstream protocol; publication and connection recheck compatibility, and this preview is not a live client verification.')}</p></div></div>{codexCapabilities.state === 'available' ? <div className="option-panel"><div className="option-row" data-codex-capability-summary><div><strong>{text(`上下文 ${formatContext(codexCapabilities.context_window)} · 输入 ${codexCapabilities.input_modalities.includes('image') ? '文本/图片' : '文本'}`, `Context ${formatContext(codexCapabilities.context_window)} · Input ${codexCapabilities.input_modalities.includes('image') ? 'text/images' : 'text'}`)}</strong><span>{text('推理强度由路由配置决定', 'Reasoning effort is determined by the route configuration')}</span></div></div>{codexCapabilities.limitations.map(limit => <div className="callout warn" role="status" data-codex-capability-limit={limit.kind} key={limit.kind}><UiIcon name="warning" /><div><strong>{limit.kind === 'context_window' ? text('候选收窄了共同上下文', 'A candidate narrows the shared context') : text('候选收窄了图片输入', 'A candidate narrows image input')}</strong><p>{limit.kind === 'context_window' ? text(`${capabilityBindings(limit.binding_ids)} 将共同上下文限制为 ${formatContext(options?.context_window?.maximum_tokens ?? codexCapabilities.context_window)}。`, `${capabilityBindings(limit.binding_ids)} limits the shared context to ${formatContext(options?.context_window?.maximum_tokens ?? codexCapabilities.context_window)}.`) : text(`${capabilityBindings(limit.binding_ids)} 不支持完整的 Codex 图片输入;最终目录只声明文本。`, `${capabilityBindings(limit.binding_ids)} does not support complete Codex image input, so the final catalog declares text only.`)}</p></div></div>)}{codexCapabilities.fixed_limits.includes('parallel_tool_calls_disabled') && <div className="callout" data-codex-fixed-limit="parallel_tool_calls_disabled"><UiIcon name="info" /><div><strong>{text('HiRoute 当前固定使用串行工具调用', 'HiRoute currently uses serial tool calls')}</strong><p>{text('这是当前实现限制,不由任何候选模型造成。', 'This is a fixed implementation limit, not a candidate-model limitation.')}</p></div></div>}</div> : <div className="callout bad" role="alert" data-codex-capability-unavailable><UiIcon name="warning" /><div><strong>{text('无法生成可靠的 Codex 客户端能力', 'Reliable Codex client capabilities are unavailable')}</strong>{codexCapabilities.issues.map((issue, index) => <p key={`${issue.kind}:${issue.binding_id ?? index}`}>{capabilityIssue(issue)}</p>)}</div></div>}</section>}
- <section className="editor-section" data-route-group="executor"><div className="editor-section-heading"><div><h3>{text('任务委派', 'Task delegation')}</h3><p>{text('关闭时只使用模型路由,不显示或检测本机执行环境。', 'When off, this plan only routes models and does not show or detect a local execution environment.')}</p></div></div><div className="option-panel"><button type="button" className="option-row" aria-pressed={editor.delegation_enabled} onClick={() => update({ delegation_enabled: !editor.delegation_enabled })}><div><strong>{text('允许委派任务给执行 Agent', 'Allow delegation to an execution agent')}</strong><span>{text('开启后需要为这份计划选择一个执行 Agent;安装缺失不会阻止保存。', 'When enabled, choose one execution agent for this plan. Missing installation does not block saving.')}</span></div><span className={`switch${editor.delegation_enabled ? ' on' : ''}`} aria-hidden="true" /></button></div>
+ <PlanRuntimeSettings limits={editor.limits} options={options} language={language} editingMemory={memory} onChange={limits => update({ limits })} />
+ <section className="editor-section">
+ <Disclosure className="native-details plan-more-settings" label={text('更多设置', 'More settings')} language={language} defaultOpen={moreSettingsOpen} onOpenChange={setMoreSettingsOpen}>
+ {editor.mode === 'smart_saving' && <section className="editor-subsection"><h3>{text('追问策略', 'Follow-up strategy')}</h3>
+ <div className="option-panel"><button type="button" className="option-row route-toggle-row" aria-pressed={editor.smart.reselect_on_user_message} onClick={() => update({ smart: { ...editor.smart, reselect_on_user_message: !editor.smart.reselect_on_user_message } })}><div><strong>{text('追问时重新选择模型', 'Reselect model for each follow-up')}</strong><span>{editor.smart.reselect_on_user_message ? text('每次追问可重新选择模型。切换可能影响对话连贯性、缓存命中率,并因模型间推理状态不兼容导致请求失败。', 'Each follow-up may reselect a model. Switching can affect continuity and cache hits, and incompatible reasoning state can cause a request to fail.') : text('连续对话中的追问优先沿用当前模型。上下文重建或模型不可用时仍可能切换。', 'Follow-ups prefer the current model. A rebuilt context or an unavailable model can still cause a switch.')}</span></div><span className={`switch${editor.smart.reselect_on_user_message ? ' on' : ''}`} aria-hidden="true" /></button></div>
+ </section>}
+ <section className="editor-subsection" data-route-group="executor"><div className="editor-section-heading"><div><h3>{text('任务委派', 'Task delegation')}</h3><p>{text('关闭时只使用模型路由,不显示或检测本机执行环境。', 'When off, this plan only routes models and does not show or detect a local execution environment.')}</p></div></div><div className="option-panel"><button type="button" className="option-row" aria-pressed={editor.delegation_enabled} onClick={() => update({ delegation_enabled: !editor.delegation_enabled })}><div><strong>{text('允许委派任务给执行 Agent', 'Allow delegation to an execution agent')}</strong><span>{text('开启后需要为这份计划选择一个执行 Agent;安装缺失不会阻止保存。', 'When enabled, choose one execution agent for this plan. Missing installation does not block saving.')}</span></div><span className={`switch${editor.delegation_enabled ? ' on' : ''}`} aria-hidden="true" /></button></div>
{editor.delegation_enabled && <div className="field"><label className="field-label">{text('执行任务的 Agent', 'Task execution agent')}</label><p className="field-help">{text('每份计划选择一个执行 Agent,不做自动回退。', 'Choose one execution agent per plan; there is no automatic fallback.')}</p><div className="v3-executors">{([
['codex_cli', 'Codex CLI', text('使用 Codex CLI 执行委派任务', 'Use Codex CLI for delegated tasks')],
['claude_code', 'Claude Code', text('使用 Claude Code 执行委派任务', 'Use Claude Code for delegated tasks')],
] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } })}><BrandIcon kind={value === 'codex_cli' ? 'codex' : 'claude-code'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}
- {editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active} onOperation={onOperation} />}
+ {editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active && moreSettingsOpen} onOperation={onOperation} />}
</div>}</section>
+ </Disclosure>
+ </section>
{plan && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('在哪里使用', 'Where it is used')}</h3><p>{text('在 Agent 页面修改默认模型路由。', 'Change the default model route from the Agent page.')}</p></div></div>{usedBy.length ? <div className="agent-card-list">{usedBy.map(agent => <button className="agent-card" type="button" key={agent.id} onClick={() => onOpenAgent?.(agent.id)} disabled={!onOpenAgent}><BrandIcon kind={agent.brand} label={`${agent.name} logo`} /><div className="agent-main"><strong>{agent.name}</strong><span>{agent.isDefault ? text('主 Agent 默认使用', 'Default for main agent') : text('用于模型路由', 'Used for model routing')}</span></div><UiIcon name="chevronRight" /></button>)}</div> : <span className="muted plan-unused">{text('尚未被任何 Agent 用作模型路由', 'Not used by any agent for model routing yet')}</span>}</section>}
diff --git a/apps/desktop/src/product/RoutingPage.tsx b/apps/desktop/src/product/RoutingPage.tsx
index a17b32f4..59db685d 100644
--- a/apps/desktop/src/product/RoutingPage.tsx
+++ b/apps/desktop/src/product/RoutingPage.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
-import { PlanEditor, type Draft, type Plan, type PlanEditorHandle } from '../plan-editor';
+import { PlanEditor, type Draft, type Plan, type PlanEditorHandle, type PlanEditorMemory } from '../plan-editor';
import { persistenceTargetWasSuperseded, resolvePersistedEditor, type PersistenceIdentity } from '../plan-editor-persistence';
import { requestEditorReplacement } from '../ui/discard-guard';
import { ProductPage, UiIcon } from '../ui';
@@ -8,7 +8,7 @@ import type { DesktopOperation, DesktopSnapshot } from './home-projections';
import type { AgentSnapshot } from '../agents';
import { routingEditorEntries } from '../routing-editor-entries';
-export type RoutingEditorIntent = { key: string; plan?: Plan; draft?: Draft; staleDraft?: boolean; initialBindingId?: string };
+export type RoutingEditorIntent = { key: string; plan?: Plan; draft?: Draft; staleDraft?: boolean; initialBindingId?: string; editingMemory?: PlanEditorMemory };
export function RoutingPage({ language, active = true, snapshot, agentSnapshot, operation, loading, busy, initialEditor = null, notice, onRefresh, onOperation, onOpenAgent, onOpenSession }: {
language: 'zh' | 'en'; snapshot: DesktopSnapshot | null; agentSnapshot?: AgentSnapshot | null; loading: boolean; busy: boolean;
@@ -18,7 +18,7 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
onOperation(operation: DesktopOperation | null): void; onOpenAgent?(agentId: string): void; onOpenSession?(sessionId: string, requestId: string): void;
}) {
const text = (cn: string, en: string) => language === 'zh' ? cn : en;
- const [editor, setEditor] = useState<RoutingEditorIntent | null>(initialEditor);
+ const [editor, setEditor] = useState<RoutingEditorIntent | null>(() => initialEditor ? { ...initialEditor, editingMemory: {} } : null);
const [dirty, setDirty] = useState(false);
const [showList, setShowList] = useState(false);
const [localBusy, setLocalBusy] = useState(false);
@@ -59,7 +59,7 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
return;
}
if (!persisted) return;
- setEditor(persisted);
+ setEditor(current => ({ ...persisted, editingMemory: current?.editingMemory ?? {} }));
returnEditor.current = null;
setDirty(false);
setPendingPersistence(null);
@@ -83,13 +83,13 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
useEffect(() => {
if (!initialized.current && snapshot && !snapshot.catalog_error && entries.length) {
initialized.current = true;
- setEditor(entries[0]);
+ setEditor({ ...entries[0], editingMemory: {} });
}
}, [snapshot]);
async function choose(next: RoutingEditorIntent, source: HTMLElement) {
if (editor?.key !== next.key && dirty && !(await requestEditorReplacement('routing'))) return;
trigger.current = source;
- if (editor?.key !== next.key) { setDirty(false); setPendingPersistence(null); setPersistedNotice(''); setEditor(next); }
+ if (editor?.key !== next.key) { setDirty(false); setPendingPersistence(null); setPersistedNotice(''); setEditor({ ...next, editingMemory: {} }); }
returnEditor.current = null;
setShowList(false);
}
@@ -108,7 +108,7 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
setDirty(false);
setPendingPersistence(null);
setPersistedNotice('');
- setEditor({ key: crypto.randomUUID() });
+ setEditor({ key: crypto.randomUUID(), editingMemory: {} });
setShowList(false);
}
const agentName = (agentId: string) => agentId === 'agent_codex_default' ? 'Codex' : agentId === 'agent_claude_default' ? 'Claude Code' : text('本机 Agent', 'Local Agent');
@@ -143,7 +143,7 @@ export function RoutingPage({ language, active = true, snapshot, agentSnapshot,
};
const editorView = editor ? <fieldset className="detail-fieldset" disabled={!mutable || busy || localBusy || editorBusy}>
{editor.staleDraft && <div className="callout warn" role="status"><UiIcon name="warning" /><div><strong>{text('这是基于旧版本的草稿', 'This draft is based on an older version')}</strong><p>{text('当前生效路由已单独显示在列表中。保留此草稿供查看;如需继续,请先读取当前配置再重新编辑。', 'The active route is listed separately. This draft is retained for inspection; reload the current route before editing further.')}</p></div></div>}
- <PlanEditor ref={planEditor} key={`${editor.key}:${editor.draft?.revision ?? editor.plan?.head.head_revision ?? 'new'}`} creating={creating} plan={editor.plan} draft={editor.draft} initialBindingId={editor.initialBindingId} language={language} active={active} usedBy={usedBy} onOpenAgent={onOpenAgent} onOpenSession={onOpenSession} onDirty={next => { setDirty(next); if (next) setPersistedNotice(''); }} onEdit={() => setPendingPersistence(null)} onBusyChange={setEditorBusy} onOperation={onOperation} onPersisted={(next, action, identity, submitted) => { setPendingPersistence(next ? null : { action, identity, operationId: submitted?.operation_id ?? null }); if (next) { returnEditor.current = null; setEditor(next); setDirty(false); setPersistedNotice(action === 'save_draft' ? text('草稿已保存,可以继续编辑或发布。', 'Draft saved. Continue editing or publish.') : text('更改已发布,新请求将使用当前路由。', 'Changes published. New requests will use this routing.')); } }} onDone={onRefresh} onClose={closeEditor} />
+ <PlanEditor ref={planEditor} key={`${editor.key}:${editor.draft?.revision ?? editor.plan?.head.head_revision ?? 'new'}`} creating={creating} plan={editor.plan} draft={editor.draft} initialBindingId={editor.initialBindingId} editingMemory={editor.editingMemory} language={language} active={active} usedBy={usedBy} onOpenAgent={onOpenAgent} onOpenSession={onOpenSession} onDirty={next => { setDirty(next); if (next) setPersistedNotice(''); }} onEdit={() => setPendingPersistence(null)} onBusyChange={setEditorBusy} onOperation={onOperation} onPersisted={(next, action, identity, submitted) => { setPendingPersistence(next ? null : { action, identity, operationId: submitted?.operation_id ?? null }); if (next) { returnEditor.current = null; setEditor(current => ({ ...next, editingMemory: current?.editingMemory ?? {} })); setDirty(false); setPersistedNotice(action === 'save_draft' ? text('草稿已保存,可以继续编辑或发布。', 'Draft saved. Continue editing or publish.') : text('更改已发布,新请求将使用当前路由。', 'Changes published. New requests will use this routing.')); } }} onDone={onRefresh} onClose={closeEditor} />
</fieldset> : null;
return <ProductPage
title={creating ? text('新建智能路由', 'New smart routing') : text('智能路由', 'Smart routing')}
diff --git a/apps/desktop/src/ui/Disclosure.tsx b/apps/desktop/src/ui/Disclosure.tsx
index c6259028..af207189 100644
--- a/apps/desktop/src/ui/Disclosure.tsx
+++ b/apps/desktop/src/ui/Disclosure.tsx
@@ -12,19 +12,24 @@ export function Disclosure({
language,
defaultOpen = false,
className = '',
+ onOpenChange,
children,
}: PropsWithChildren<{
label: string;
language: Language;
defaultOpen?: boolean;
className?: string;
+ onOpenChange?(open: boolean): void;
}>) {
const [open, setOpen] = useState(defaultOpen);
return <details
className={`disclosure ${className}`.trim()}
open={open}
data-state={open ? 'open' : 'closed'}
- onToggle={event => setOpen(event.currentTarget.open)}
+ onToggle={event => {
+ setOpen(event.currentTarget.open);
+ onOpenChange?.(event.currentTarget.open);
+ }}
>
<summary aria-expanded={open}>
<span className="disclosure-label">{label}</span>
diff --git a/apps/desktop/tests/ui-consistency.test.mjs b/apps/desktop/tests/ui-consistency.test.mjs
index 33c253a7..3373c3db 100644
--- a/apps/desktop/tests/ui-consistency.test.mjs
+++ b/apps/desktop/tests/ui-consistency.test.mjs
@@ -84,13 +84,15 @@ test('the routing connection name is direct and documents its stable Agent ident
test('classifier choices expose an unmistakable selected state and left-aligned copy', () => {
const editor = read('src/plan-editor.tsx');
assert.match(editor, /className="option-row classifier-choice"/);
- assert.match(editor, /如何判断任务复杂度/);
+ assert.match(editor, /任务判断/);
assert.match(editor, /内置规则/);
assert.match(editor, /自定义分类服务/);
assert.match(editor, /Jev、LLM 或其他自定义策略/);
assert.doesNotMatch(editor, /BERT/);
- assert.match(editor, /classifier\.kind === 'local_rules' \? text\('已选择', 'Selected'\)/);
- assert.match(editor, /classifier\.kind === 'rest' \? text\('已选择', 'Selected'\)/);
+ assert.match(editor, /aria-pressed=\{classifier\.kind === 'local_rules'\}/);
+ assert.match(editor, /aria-pressed=\{classifier\.kind === 'rest'\}/);
+ assert.match(editor, /classifier\.kind === 'local_rules' && <UiIcon name="check"/);
+ assert.match(editor, /classifier\.kind === 'rest' && <UiIcon name="check"/);
const pages = read('src/occami/styles/pages.css');
assert.match(pages, /button\.option-row\[aria-pressed='true'\]\s*\{[^}]*border-color:\s*var\(--accent\)/);
assert.match(pages, /\.option-row > div\s*\{[^}]*text-align:\s*left/);
diff --git a/apps/desktop/tests/v3/browser/plan-editor-ux.html b/apps/desktop/tests/v3/browser/plan-editor-ux.html
new file mode 100644
index 00000000..0faeba02
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/plan-editor-ux.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>HiRoute routing UX — component regression only</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./plan-editor-ux.tsx"></script>
+ </body>
+</html>
diff --git a/apps/desktop/tests/v3/browser/plan-editor-ux.tsx b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx
new file mode 100644
index 00000000..4ffc205a
--- /dev/null
+++ b/apps/desktop/tests/v3/browser/plan-editor-ux.tsx
@@ -0,0 +1,207 @@
+// @ts-expect-error Existing JavaScript browser scenarios have no TypeScript declaration.
+import { runRoutingWorkerScenarios } from './routing-worker-scenarios.mjs';
+import { useState } from 'react';
+import { createRoot } from 'react-dom/client';
+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 { dailyPlan, fixtureTrace, mockProductInvoke, readyDesktop, resetFixtureTrace } from './product-fixtures';
+import '../../../src/occami/styles.css';
+
+const workerChecks = new URLSearchParams(location.search).get('checks') === 'workers';
+const plan = structuredClone(dailyPlan);
+if (!workerChecks) { plan.desired.delegation_enabled = false; plan.desired.work = undefined; }
+const submitted: { action: string; editor: Editor }[] = [];
+const savedSnapshot = structuredClone(readyDesktop);
+savedSnapshot.catalog = { ...savedSnapshot.catalog, plans: [plan], drafts: [] };
+resetFixtureTrace();
+(window as typeof window & { __HIRouteFixtureTrace?: typeof fixtureTrace }).__HIRouteFixtureTrace = fixtureTrace;
+mockIPC((command, payload) => {
+ const input = payload as { input?: { action: string; editor: Editor; draft_id: string; plan_id: string; expected_head_revision: number; expected_draft_revision: number | null } };
+ if (command === 'desktop_snapshot') {
+ fixtureTrace.commands.push(command);
+ return structuredClone(savedSnapshot);
+ }
+ if (command === 'preview_plan_editor') {
+ fixtureTrace.commands.push(command);
+ const request = input.input!;
+ submitted.push(structuredClone(request));
+ if (request.action === 'save_draft') {
+ const draft: Draft = { draft_id: request.draft_id, plan_id: request.plan_id, base_head_revision: request.expected_head_revision, revision: (request.expected_draft_revision ?? 0) + 1, editor: structuredClone(request.editor) };
+ savedSnapshot.catalog.drafts = [draft];
+ }
+ return { state: 'succeeded', operation: { operation_id: `operation/ux-${submitted.length}`, state: 'succeeded', sequence: 1, cancellable: false, safe_error_code: null } };
+ }
+ return mockProductInvoke(command, payload as Record<string, unknown>, 'ready');
+});
+
+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 element<T extends HTMLElement>(selector: string) {
+ const found = document.querySelector<T>(selector);
+ assert(found, `Missing ${selector}`);
+ return found;
+}
+function button(label: string) {
+ const found = [...document.querySelectorAll<HTMLButtonElement>('button')].find(item => item.textContent?.trim() === label);
+ assert(found, `Missing button ${label}`);
+ return found;
+}
+function setInput(selector: string, value: string) {
+ const input = element<HTMLInputElement>(selector);
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+function chooseWindow(value: 'auto' | 'custom') {
+ const select = element<HTMLSelectElement>('.plan-context-mode');
+ select.value = value;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+}
+const selectClassifier = async (kind: 'local' | 'rest') => {
+ element<HTMLButtonElement>(`.classifier-choice:nth-child(${kind === 'local' ? 1 : 2})`).click();
+ await tick();
+};
+
+const checks: [string, () => Promise<void>][] = [
+ ['Built-in rules hide external connection controls and protocol', async () => {
+ await until(() => Boolean(document.querySelector('[data-codex-capability-state]')), 'editor options');
+ assert(!document.querySelector('.classifier-endpoint-field'), 'Built-in rules exposed the endpoint');
+ assert(![...document.querySelectorAll('button')].some(item => item.textContent === '查看接入协议'), 'Built-in rules exposed the protocol');
+ assert(!element<HTMLDetailsElement>('.plan-more-settings').open, 'New optional settings were expanded');
+ assert(fixtureTrace.commands.every(command => !command.startsWith('worker_')), 'Hidden delegation queried an executor');
+ }],
+ ['Switching classifiers preserves configuration but clears unsaved authentication plaintext', async () => {
+ await selectClassifier('rest');
+ assert(button('查看接入协议'), 'Custom service lost the protocol entry');
+ setInput('.classifier-endpoint-field', 'https://classifier.example/v1/decisions');
+ setInput('.classifier-timeout-field', '3900');
+ element<HTMLDetailsElement>('.classifier-auth').querySelector('summary')!.click();
+ await tick();
+ element<HTMLButtonElement>('.classifier-auth .option-row:nth-child(2)').click();
+ await tick();
+ setInput('.classifier-header-field', 'X-Classifier');
+ setInput('.classifier-secret-ref-field', 'classifier/review');
+ setInput('.classifier-secret-create input', 'synthetic-placeholder');
+ await tick();
+ await selectClassifier('local');
+ assert(!document.querySelector('.classifier-endpoint-field'), 'Inactive REST controls remained visible');
+ await selectClassifier('rest');
+ assert(element<HTMLInputElement>('.classifier-endpoint-field').value === 'https://classifier.example/v1/decisions', 'Endpoint was reset');
+ assert(element<HTMLInputElement>('.classifier-timeout-field').value === '3900', 'Timeout was reset');
+ assert(element<HTMLInputElement>('.classifier-header-field').value === 'X-Classifier', 'Header name was reset');
+ assert(element<HTMLInputElement>('.classifier-secret-ref-field').value === 'classifier/review', 'Secret reference was reset');
+ assert(element<HTMLInputElement>('.classifier-secret-create input').value === '', 'Unsaved authentication plaintext was cached');
+ }],
+ ['Draft save rebuilds the real page and retains inactive inputs without submitting them', async () => {
+ await selectClassifier('local');
+ chooseWindow('custom');
+ await tick();
+ setInput('.plan-context-window-field', '32000');
+ await tick();
+ chooseWindow('auto');
+ setInput('.plan-identity-fields input', 'Review-local-rules');
+ await tick();
+ const before = submitted.length;
+ const previousEditor = element('.plan-editor');
+ button('保存草稿').click();
+ await until(() => submitted.length === before + 1 && !previousEditor.isConnected && !element<HTMLFieldSetElement>('.detail-fieldset').disabled, 'persisted draft rebuilt the editor');
+ const classifier = submitted.at(-1)!.editor.smart.classifier;
+ assert(JSON.stringify(classifier) === '{"kind":"local_rules"}', 'Inactive REST fields leaked into the submitted draft');
+ assert(submitted.at(-1)!.editor.limits.context_window_tokens === undefined, 'Inactive window leaked into the draft');
+ await selectClassifier('rest');
+ assert(element<HTMLInputElement>('.classifier-endpoint-field').value === 'https://classifier.example/v1/decisions', 'Draft save reset the endpoint');
+ assert(element<HTMLInputElement>('.classifier-timeout-field').value === '3900', 'Draft save reset the timeout');
+ assert(element<HTMLInputElement>('.classifier-secret-ref-field').value === 'classifier/review', 'Draft save reset the authentication reference');
+ assert(element<HTMLInputElement>('.classifier-secret-create input').value === '', 'Draft save cached authentication plaintext');
+ await selectClassifier('local');
+ await until(() => Boolean(document.querySelector('[data-codex-capability-state]')), 'options after draft reconstruction');
+ }],
+ ['Custom windows retain input and reject empty or out-of-bounds values before publication', async () => {
+ chooseWindow('custom');
+ await tick();
+ assert(element<HTMLInputElement>('.plan-context-window-field').value === '32000', 'Draft save reset the custom window');
+ chooseWindow('auto');
+ await tick();
+ assert(!document.querySelector('.plan-context-window-field'), 'Automatic mode exposed a custom input');
+ chooseWindow('custom');
+ await tick();
+ assert(element<HTMLInputElement>('.plan-context-window-field').value === '32000', 'Custom window was reset');
+ for (const value of ['64001', '']) {
+ setInput('.plan-context-window-field', value);
+ await tick();
+ const before = submitted.length;
+ button('发布更改').click();
+ await tick();
+ assert(submitted.length === before, 'Invalid custom window was submitted');
+ assert(element<HTMLSelectElement>('.plan-context-mode').value === 'custom', 'Empty input silently selected automatic mode');
+ assert(document.activeElement === element('.plan-context-window-field'), 'Invalid window was not focused');
+ assert(element('[data-plan-context-window] [role="alert"]').textContent, 'Invalid window has no inline error');
+ }
+ setInput('.plan-context-window-field', '32000');
+ await tick();
+ chooseWindow('auto');
+ await tick();
+ }],
+ ['Publication unfolds executor errors and collapsed installations stop discovery', async () => {
+ const details = element<HTMLDetailsElement>('.plan-more-settings');
+ details.querySelector('summary')!.click();
+ await tick();
+ element<HTMLButtonElement>('[data-route-group="executor"] .option-row').click();
+ await tick();
+ details.querySelector('summary')!.click();
+ await tick();
+ button('发布更改').click();
+ await tick();
+ assert(details.open, 'Executor error remained hidden');
+ assert(document.activeElement === document.querySelector('.v3-executors button'), 'Executor error did not focus the selection');
+ element<HTMLButtonElement>('.v3-executors button').click();
+ await until(() => fixtureTrace.commands.includes('worker_dependencies_discover'), 'visible worker discovery');
+ details.querySelector('summary')!.click();
+ await tick();
+ const before = fixtureTrace.commands.filter(command => command.startsWith('worker_')).length;
+ await new Promise(resolve => setTimeout(resolve, 250));
+ assert(fixtureTrace.commands.filter(command => command.startsWith('worker_')).length === before, 'Collapsed executor started another query');
+ }],
+];
+
+function Harness() {
+ const [snapshot, setSnapshot] = useState(() => structuredClone(savedSnapshot));
+ const [running, setRunning] = useState(false);
+ const [results, setResults] = useState<{ name: string; state: string; error?: string }[]>([]);
+ async function run() {
+ setRunning(true);
+ if (workerChecks) {
+ const outcome = await runRoutingWorkerScenarios(0, 5);
+ setResults(outcome.results);
+ setRunning(false);
+ return;
+ }
+ const next = [];
+ for (const [name, check] of checks) {
+ try { await check(); 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 <PresentationRoot language="zh" theme="light" textScale={1}>
+ <aside style={{ padding: 16 }}>
+ <p>React + mock IPC 回归检查;不代表原生 Desktop 或真实 daemon 验收。</p>
+ <button className="btn" disabled={running || results.length > 0} onClick={() => void run()}>运行智能路由交互检查</button>
+ <output aria-live="polite" data-ux-results>{results.length > 0 && JSON.stringify({ tests: results.length, passed: results.filter(result => result.state === 'green').length, results })}</output>
+ </aside>
+ <RoutingPage language="zh" snapshot={snapshot} initialEditor={{ key: plan.agent_plan_id, plan }} loading={false} busy={false} onRefresh={async () => setSnapshot(structuredClone(savedSnapshot))} onOperation={() => {}} />
+ </PresentationRoot>;
+}
+createRoot(document.getElementById('root')!).render(<Harness />);
diff --git a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
index 13c5a995..1a229a73 100644
--- a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
@@ -27,14 +27,19 @@ const scenarios = [
await until(() => document.querySelector('[data-codex-capability-state="available"]'), 'Codex capability summary');
const summary = document.querySelector('[data-codex-capability-summary]');
assert(summary.textContent.includes('上下文 64K') && summary.textContent.includes('输入 文本'), 'The shared Codex capability summary is incomplete');
- assert(document.querySelector('.codex-capability-summary').textContent.includes('当前编辑内容') && document.querySelector('.codex-capability-summary').textContent.includes('Codex Responses 入口'), 'The capability preview claims published or upstream protocol support');
+ const details = document.querySelector('.plan-capability-details');
+ assert(details && !details.open, 'Lengthy capability explanations are not folded by default');
+ assert(visible(summary), 'The capability summary was folded');
+ details.querySelector('summary').click();
+ await tick();
+ assert(details.textContent.includes('当前编辑内容') && details.textContent.includes('Codex Responses 入口'), 'The capability preview claims published or upstream protocol support');
const context = document.querySelector('[data-codex-capability-limit="context_window"]');
const image = document.querySelector('[data-codex-capability-limit="image_input"]');
- assert(context?.textContent.includes('Qwen3-Coder-Plus'), 'The context narrowing candidate is not identified');
- assert(image?.textContent.includes('Qwen3-Coder-Plus'), 'The image narrowing candidate is not identified');
+ assert(visible(context) && context?.textContent.includes('Qwen3-Coder-Plus'), 'The context narrowing candidate is not identified');
+ assert(visible(image) && image?.textContent.includes('Qwen3-Coder-Plus'), 'The image narrowing candidate is not identified');
assert(!document.querySelector('[data-codex-capability-limit="messages_protocol_boundary"]'), 'A native Responses candidate was labeled as Messages-limited');
const fixed = document.querySelector('[data-codex-fixed-limit="parallel_tool_calls_disabled"]');
- assert(fixed?.textContent.includes('不由任何候选模型造成'), 'The fixed serial-tool limit is attributed to a candidate');
+ assert(visible(fixed) && fixed?.textContent.includes('不由任何候选模型造成'), 'The fixed serial-tool limit is attributed to a candidate');
assert(!document.querySelector('[data-codex-capability-unavailable]'), 'Complete metadata was rendered as unavailable');
}],
['configured delegation discovers only while its configuration is visible', async () => {