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(desktop): keep subscription setup inside device scan (#96)
澄潭dc5d2c0dbc3d
diff --git a/apps/desktop/src/features/SubscriptionProxySettings.tsx b/apps/desktop/src/features/SubscriptionProxySettings.tsxindex 73724380..a9993116 100644--- a/apps/desktop/src/features/SubscriptionProxySettings.tsx+++ b/apps/desktop/src/features/SubscriptionProxySettings.tsx@@ -1,64 +1,109 @@import { invoke } from '@tauri-apps/api/core';-import { useEffect, useState } from 'react';+import { useEffect, useId, useRef, useState, type ReactNode } from 'react';import { safeDiagnosticCode } from '../error-code';+import { clearSubscriptionProxyReturn, requestSubscriptionProxyReturn } from './subscription-proxy-return';type Mode = 'inherit' | 'direct' | 'manual';type Policy = { mode: Mode; url?: string; no_proxy?: string };type View = { config: { revision: string; policy: Policy }; applied: boolean };-export function SubscriptionProxySettings({ active, language }: { active: boolean; language: 'zh' | 'en' }) {+// Scan owns the dialog and its retained results; this editor owns the draft and+// footer actions so reading/saving cannot leave unrelated scan actions enabled.+export function SubscriptionProxySettings({ editing, language, writable, onCancel, children }: {+ editing: boolean;+ language: 'zh' | 'en';+ writable: boolean;+ onCancel(): void;+ children(parts: { panel: ReactNode; actions: ReactNode; saving: boolean }): ReactNode;+}) {const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ const formId = useId();+ const panel = useRef<HTMLFormElement>(null);+ const inFlight = useRef(false);const [view, setView] = useState<View | null>(null);const [mode, setMode] = useState<Mode>('inherit');const [url, setUrl] = useState('');const [bypass, setBypass] = useState('');- const [busy, setBusy] = useState(false);- const [error, setError] = useState('');+ const [reading, setReading] = useState(false);+ const [saving, setSaving] = useState(false);+ const [retry, setRetry] = useState(0);+ const [error, setError] = useState<{ phase: 'read' | 'save'; code: string } | null>(null);+useEffect(() => {- if (!active) return;+ if (!editing) return;let current = true;- setBusy(true);+ setView(null); setReading(true); setError(null);+ panel.current?.scrollIntoView({ block: 'nearest' });void invoke<View>('subscription_proxy_status').then(value => {if (!current) return;- setView(value); setMode(value.config.policy.mode); setUrl(value.config.policy.url ?? ''); setBypass(value.config.policy.no_proxy ?? ''); setError('');- }).catch(reason => { if (current) setError(safeDiagnosticCode(reason, 'SUBSCRIPTION_PROXY_UNAVAILABLE')); })- .finally(() => { if (current) setBusy(false); });+ setView(value); setMode(value.config.policy.mode);+ setUrl(value.config.policy.url ?? ''); setBypass(value.config.policy.no_proxy ?? '');+ }).catch(reason => {+ if (current) setError({ phase: 'read', code: safeDiagnosticCode(reason, 'SUBSCRIPTION_PROXY_UNAVAILABLE') });+ }).finally(() => { if (current) setReading(false); });return () => { current = false; };- }, [active]);+ }, [editing, retry]);++ useEffect(() => {+ if (editing && view && !reading) panel.current?.querySelector<HTMLSelectElement>('select')?.focus();+ }, [editing, view, reading]);+async function save() {- setBusy(true); setError('');+ if (!view || reading || !writable || inFlight.current) return;+ inFlight.current = true; setSaving(true); setError(null);try {const policy: Policy = mode === 'manual' ? { mode, url: url.trim(), no_proxy: bypass.trim() } : { mode };+ requestSubscriptionProxyReturn();await invoke('subscription_proxy_apply', { policy });+ // The native command restarts the application; retain the busy state until+ // that happens rather than offering a second save during shutdown.} catch (reason) {- setError(safeDiagnosticCode(reason, 'SUBSCRIPTION_PROXY_UNAVAILABLE')); setBusy(false);+ clearSubscriptionProxyReturn();+ setError({ phase: 'save', code: safeDiagnosticCode(reason, 'SUBSCRIPTION_PROXY_UNAVAILABLE') });+ inFlight.current = false; setSaving(false);}}- return <section className="settings-group" id="subscription-proxy-settings">- <h2>{text('网络', 'Network')}</h2>- <div className="settings-list"><div className="settings-row">- <div className="settings-copy"><strong>{text('订阅连接代理', 'Subscription connection proxy')}</strong>- <span>{text('作用于 HiRoute 接入的全部订阅及订阅检查。', 'Applies to all subscriptions connected through HiRoute and their connection checks.')}</span>- <span>{view ? text(`保存的模式:${{ inherit: '继承启动环境', direct: '直接连接', manual: '手动代理' }[view.config.policy.mode]} · ${view.applied ? '配置已应用' : '等待应用或服务尚未就绪'}`, `Saved mode: ${view.config.policy.mode} · ${view.applied ? 'Configuration applied' : 'Pending or service not ready'}`) : text('正在读取设置…', 'Loading settings…')}</span>- <span>{text('配置已应用不代表订阅可用;请在“模型 → 添加模型”中检查订阅,再发起一次真实请求。', 'An applied configuration does not confirm subscription availability. Check the subscription in Models → Add model, then send a real request.')}</span>- </div>- <div className="subscription-proxy-control">- <label className="field-label">{text('连接方式', 'Connection mode')}- <select className="select" aria-label={text('订阅代理模式', 'Subscription proxy mode')} value={mode} disabled={busy} onChange={event => setMode(event.target.value as Mode)}>- <option value="inherit">{text('继承启动环境', 'Inherit launch environment')}</option>- <option value="direct">{text('直接连接', 'Direct connection')}</option>- <option value="manual">{text('手动代理', 'Manual proxy')}</option>- </select>- </label>- {mode === 'manual' && <>- <label className="field-label">{text('HTTP / HTTPS 代理地址', 'HTTP / HTTPS proxy URL')}<input className="input" aria-label={text('订阅代理地址', 'Subscription proxy URL')} placeholder="http://127.0.0.1:1187" value={url} disabled={busy} onChange={event => setUrl(event.target.value)} /></label>- <label className="field-label">{text('绕过代理的地址(可选)', 'Proxy bypass list (optional)')}<input className="input" aria-label={text('订阅代理绕过列表', 'Subscription proxy bypass list')} placeholder="example.com,192.168.0.0/16" value={bypass} disabled={busy} onChange={event => setBypass(event.target.value)} /></label>- <span className="field-help">{text('多个地址用逗号分隔;本机地址自动绕过。暂不支持在代理地址中填写用户名或密码。', 'Separate entries with commas; local addresses always bypass the proxy. Usernames and passwords in proxy URLs are not supported.')}</span>- </>}- {mode === 'inherit' && <span className="field-help">{text('继承 HiRoute 启动时的 HTTP(S)_PROXY 与 NO_PROXY,不会运行 startProxy 或读取 shell 配置。', 'Uses HTTP(S)_PROXY and NO_PROXY from HiRoute’s launch environment; shell startup functions are not executed.')}</span>}- <span className="field-help">{text('保存后会重启 HiRoute,正在执行的请求和任务可能中断。', 'Saving restarts HiRoute and may interrupt active requests and tasks.')}</span>- <button className="btn" type="button" disabled={busy || (mode === 'manual' && !url.trim())} onClick={() => void save()}>{busy ? text('处理中…', 'Working…') : text('保存并重启 HiRoute', 'Save and restart HiRoute')}</button>- </div>- </div>{error && <div className="settings-inline-error" role="status">{text(`代理设置未完成(${error})。请检查地址格式和服务状态。`, `Proxy setup failed (${error}). Check the URL and service status.`)}</div>}</div>- </section>;++ const busy = reading || saving;+ const modeName = (value: Mode) => ({+ inherit: text('自动(使用启动时的代理)', 'Automatic (use launch proxy)'),+ direct: text('直接连接', 'Direct connection'),+ manual: text('手动代理', 'Manual proxy'),+ })[value];+ return children({+ saving,+ actions: <>+ <button className="btn" type="button" disabled={saving} onClick={onCancel}>{text('取消', 'Cancel')}</button>+ <button className="btn btn-primary" type="submit" form={formId} disabled={busy || !view || !writable || (mode === 'manual' && !url.trim())}>{saving ? text('正在保存并重启…', 'Saving and restarting…') : text('保存并重启 HiRoute', 'Save and restart HiRoute')}</button>+ </>,+ panel: editing && <form ref={panel} id={formId} className="subscription-proxy-panel" aria-label={text('订阅连接代理', 'Subscription connection proxy')} onSubmit={event => { event.preventDefault(); void save(); }}>+ <strong>{text('订阅连接代理', 'Subscription connection proxy')}</strong>+ <p className="oc-meta">{text('用于 HiRoute 接入的全部订阅及订阅检查。以后可从这里修改。', 'Applies to all subscriptions connected through HiRoute and their checks. Return here to change it.')}</p>+ {reading && <p role="status">{text('正在读取代理配置…', 'Loading proxy configuration…')}</p>}+ {view && <>+ <p className="oc-meta">{text(`当前保存:${modeName(view.config.policy.mode)} · ${view.applied ? '已应用' : '等待应用或服务就绪'}`, `Currently saved: ${modeName(view.config.policy.mode)} · ${view.applied ? 'Applied' : 'Pending or service not ready'}`)}</p>+ <div className="subscription-proxy-control">+ <label className="field-label">{text('连接方式', 'Connection mode')}+ <select className="select" aria-label={text('订阅代理模式', 'Subscription proxy mode')} value={mode} disabled={busy || !writable} onChange={event => setMode(event.target.value as Mode)}>+ {(['inherit', 'direct', 'manual'] as const).map(value => <option key={value} value={value}>{modeName(value)}</option>)}+ </select>+ </label>+ {mode === 'manual' && <>+ <label className="field-label">{text('HTTP / HTTPS 代理地址', 'HTTP / HTTPS proxy URL')}<input className="input" type="url" required maxLength={2048} aria-label={text('订阅代理地址', 'Subscription proxy URL')} placeholder={text('http://127.0.0.1:端口', 'http://127.0.0.1:port')} value={url} disabled={busy || !writable} onChange={event => setUrl(event.target.value)} /></label>+ <label className="field-label">{text('绕过代理的地址(可选)', 'Proxy bypass list (optional)')}<input className="input" maxLength={4096} aria-label={text('订阅代理绕过列表', 'Subscription proxy bypass list')} placeholder="example.com,192.168.0.0/16" value={bypass} disabled={busy || !writable} onChange={event => setBypass(event.target.value)} /></label>+ <span className="field-help">{text('多个地址用逗号分隔;本机地址自动绕过。代理地址暂不支持用户名或密码。', 'Separate entries with commas; local addresses always bypass the proxy. Proxy URLs do not support usernames or passwords.')}</span>+ </>}+ {mode === 'inherit' && <span className="field-help">{text('使用 HiRoute 启动时已有的代理设置。', 'Uses the proxy settings available when HiRoute starts.')}</span>}+ {mode === 'direct' && <span className="field-help">{text('订阅连接不使用代理。', 'Subscription connections bypass the proxy.')}</span>}+ </div>+ </>}+ {error && <div className="callout bad" role="alert" data-error-code={error.code}>+ <span>{error.phase === 'read'+ ? text(`无法读取代理配置(${error.code})。请重试后再修改。`, `Could not read the proxy configuration (${error.code}). Retry before editing.`)+ : text(`代理配置未保存(${error.code})。输入已保留,请检查地址格式后重试。`, `Proxy configuration was not saved (${error.code}). Your input is retained; check the URL and retry.`)}</span>+ {error.phase === 'read' && <button className="btn" type="button" onClick={() => setRetry(value => value + 1)}>{text('重试读取', 'Retry loading')}</button>}+ </div>}+ <p className="field-help">{text('保存后会重启 HiRoute,正在执行的请求和任务可能中断。重启后将回到扫描本机,继续检查订阅。', 'Saving restarts HiRoute and may interrupt active requests and tasks. After restart, return to this device scan to check subscriptions.')}</p>+ </form>,+ });}diff --git a/apps/desktop/src/features/device-scan/DeviceScanList.tsx b/apps/desktop/src/features/device-scan/DeviceScanList.tsxindex ea888cf8..ecd3305f 100644--- a/apps/desktop/src/features/device-scan/DeviceScanList.tsx+++ b/apps/desktop/src/features/device-scan/DeviceScanList.tsx@@ -109,6 +109,7 @@ export function DeviceScanList({computeScanFailed,repairingSubscriptionSource,trustedAuthority,+ onConnectSubscription,onOpenSubscription,onViewConnectedSubscription,onOpenDiscoveredConfiguration,@@ -122,6 +123,7 @@ export function DeviceScanList({computeScanFailed: boolean;repairingSubscriptionSource: string | null;trustedAuthority: boolean;+ onConnectSubscription(): void;onOpenSubscription(candidate: SubscriptionCandidate): void;onViewConnectedSubscription(candidate: SubscriptionCandidate): void;onOpenDiscoveredConfiguration(item: ComputeScanItem): void;@@ -132,6 +134,11 @@ export function DeviceScanList({return <div className="oc-scan-list"><p className="v3-select-intro">{text('逐项查看和接入,不改变 Agent 的现有路由设置。', 'Review and connect each source without changing the agents’ routing settings.')}</p><h3 className="oc-section-label">{text('可复用的订阅', 'Available subscriptions')}</h3>+ <div className="subscription-reuse-note">+ <p className="oc-meta">{text('复用本机登录依赖 Codex / Claude Code 刷新登录凭据,HiRoute 会定时同步。未更新时,连接可能因登录过期而暂停。', 'Reusing a local sign-in depends on Codex / Claude Code refreshing its credentials. HiRoute syncs those updates periodically; the connection may pause if the sign-in expires.')}</p>+ <p className="oc-meta">{text('长期使用推荐连接订阅,由 HiRoute 自动刷新登录凭据。', 'For ongoing use, connect a subscription so HiRoute can automatically refresh sign-in credentials.')}</p>+ <button className="btn" type="button" disabled={!trustedAuthority} onClick={onConnectSubscription}>{text('连接订阅(推荐)', 'Connect subscription (recommended)')}</button>+ </div>{subscriptions.map(candidate => {const repairing = Boolean(candidate.existing_source_id && candidate.existing_source_id === repairingSubscriptionSource);return <div className="oc-status-row" key={candidate.candidate.candidate_ref}>diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsxindex 6dcae3a2..dda67323 100644--- a/apps/desktop/src/features/models/Models.tsx+++ b/apps/desktop/src/features/models/Models.tsx@@ -427,9 +427,9 @@ export function Models(props: Props) {<p className="field-help">{text(`此接入包含 ${source.models.length} 个模型。端点、Key 和启停操作作用于这份接入。`, `This connection has ${source.models.length} models. Endpoints, keys and enabled state belong to this connection.`)}</p><p className="muted">{access === 'subscription'? subscriptionMode === 'cpa_managed'- ? text('独立登录 · 由 HiRoute 自动续期,不依赖原生客户端。', 'Independent sign-in · HiRoute renews access without the native client.')+ ? text('独立登录 · 由 HiRoute 自动刷新登录凭据,不依赖原生客户端。', 'Independent sign-in · HiRoute automatically refreshes sign-in credentials without the native client.'): subscriptionMode === 'native_borrowed'- ? text('复用本机登录 · 仅同步当前访问凭据,续期依赖原生客户端。', 'Local sign-in reuse · Syncs current access; renewal depends on the native client.')+ ? text('复用本机登录 · 仅同步当前访问凭据,凭据刷新依赖原生客户端。', 'Local sign-in reuse · Syncs current access; credential refresh depends on the native client.'): text('使用订阅连接,无需重复填写 API Key。', 'Uses a subscription; no additional API key is needed.'): connectorManaged? text('凭据由本机连接器管理,无需在 HiRoute 中填写 API Key。', 'Credentials are managed by the local connector; no API key is entered in HiRoute.')diff --git a/apps/desktop/src/features/subscription-proxy-return.ts b/apps/desktop/src/features/subscription-proxy-return.tsnew file mode 100644index 00000000..474282c3--- /dev/null+++ b/apps/desktop/src/features/subscription-proxy-return.ts@@ -0,0 +1,22 @@+// A short-lived navigation hint only: never store proxy addresses, credentials,+// scan candidates or check authority in WebView storage.+const key = 'hiroute.subscription-proxy-return';+const lifetime = 5 * 60 * 1000;++export function requestSubscriptionProxyReturn() {+ window.localStorage.setItem(key, String(Date.now()));+}++export function clearSubscriptionProxyReturn() {+ try { window.localStorage.removeItem(key); } catch { /* Navigation storage is optional at startup. */ }+}++export function takeSubscriptionProxyReturn(): boolean {+ try {+ const value = window.localStorage.getItem(key);+ window.localStorage.removeItem(key);+ if (!value || !/^\d+$/.test(value)) return false;+ const age = Date.now() - Number(value);+ return age >= 0 && age < lifetime;+ } catch { return false; }+}diff --git a/apps/desktop/src/features/subscriptions/README.md b/apps/desktop/src/features/subscriptions/README.mdindex c9a6ddb6..153ca33b 100644--- a/apps/desktop/src/features/subscriptions/README.md+++ b/apps/desktop/src/features/subscriptions/README.md@@ -14,7 +14,11 @@ check → model selection → Preview/Apply save flow. No sign-in action publishThe native reuse option opens the existing device scan. Background token synchronizationdoes not grant refresh authority: native clients retain their refresh tokens. Copy must-distinguish this dependency from an independent sign-in's automatic renewal.+distinguish this dependency from an independent sign-in's automatic credential refresh.+The device scan explains that dependency before connection and links to the existing+independent sign-in interaction. Opening that entry releases the prior scan check;+it neither starts authorization nor saves a connection. Product copy calls this+automatic sign-in credential refresh, never renewal of the paid subscription.Tests belong to the Desktop subscription suites and the production Pilot path; sharedcontract and protected callback admission regressions belong to Application API, CLI anddiff --git a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsxindex 27917767..478d7557 100644--- a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx+++ b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx@@ -127,7 +127,7 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,}return <section className="oc-scan-list" aria-label={text('连接订阅', 'Connect subscription')}>- <p className="v3-select-intro">{text('独立登录后可自动续期,无需保持原生客户端运行。登录完成后,检查并选择模型,保存后才会接入。', 'An independent sign-in renews automatically without keeping the native client running. After signing in, check and choose models, then save to connect them.')}</p>+ <p className="v3-select-intro" data-autofocus tabIndex={-1}>{text('独立登录后,HiRoute 可自动刷新登录凭据,无需保持原生客户端运行。登录完成后,检查并选择模型,保存后才会接入。', 'After an independent sign-in, HiRoute can automatically refresh sign-in credentials without keeping the native client running. After signing in, check and choose models, then save to connect them.')}</p>{providers.map(provider => {const name = provider === 'codex' ? 'Codex' : 'Claude Code';const accounts = sessions.filter(session => session.provider === provider && !['cancelled', 'forgotten'].includes(session.status));@@ -150,7 +150,7 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,</div>)}</div>;})}- <Disclosure label={text('复用本机登录', 'Reuse a local sign-in')} language={language}><p className="oc-meta">{text('本机 Codex / Claude Code 更新登录后,HiRoute 会定时同步访问令牌。续期依赖原生客户端;未更新时,连接可能因过期而暂停。', 'Syncs access periodically after the local Codex / Claude Code client updates its sign-in. Renewal depends on the native client; the connection may pause if it has not renewed access.')}</p><p className="oc-meta">{text('Codex 仅支持复用文件中的登录;钥匙串等存储请使用独立登录。Claude Code 支持现有文件及 macOS 钥匙串登录。', 'Codex reuse supports file-based sign-ins; use independent sign-in for Keychain or other stores. Claude Code supports its existing file and macOS Keychain sign-ins.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={onReuseNative}>{text('扫描本机登录', 'Find local sign-ins')}</button></Disclosure>+ <Disclosure label={text('复用本机登录', 'Reuse a local sign-in')} language={language}><p className="oc-meta">{text('本机 Codex / Claude Code 刷新登录凭据后,HiRoute 会定时同步。凭据刷新依赖原生客户端;未更新时,连接可能因登录过期而暂停。', 'HiRoute syncs sign-in credentials periodically after the local Codex / Claude Code client refreshes them. Credential refresh depends on the native client; the connection may pause if the sign-in expires.')}</p><p className="oc-meta">{text('Codex 仅支持复用文件中的登录;钥匙串等存储请使用独立登录。Claude Code 支持现有文件及 macOS 钥匙串登录。', 'Codex reuse supports file-based sign-ins; use independent sign-in for Keychain or other stores. Claude Code supports its existing file and macOS Keychain sign-ins.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={onReuseNative}>{text('扫描本机登录', 'Find local sign-ins')}</button></Disclosure>{error && <div className="callout bad" role="alert" data-error-code={error}><UiIcon name="warning" /><span>{text('操作未完成,请重试。已接入的模型配置会保留。', 'The operation did not complete. Try again; existing model settings are retained.')}</span></div>}</section>;}diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.cssindex b602c5bf..5609fb42 100644--- a/apps/desktop/src/occami/styles.css+++ b/apps/desktop/src/occami/styles.css@@ -97,6 +97,11 @@.connection-fields,.model-result-list {min-width:0;margin:0;padding:0;border:0;}.connection-fields>.option-row {margin-bottom:4px;}.connection-fields>.field+.field {margin-top:0;}+.subscription-proxy-panel {border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-soft);padding:16px;margin-block:12px 20px;min-width:0;}+.subscription-proxy-control {display:flex;flex-direction:column;gap:12px;width:100%;min-width:0;}+.subscription-proxy-control .field-label {flex-direction:column;align-items:stretch;gap:6px;min-width:0;}+.subscription-proxy-control .input,.subscription-proxy-control .select {width:100%;min-width:0;}+.subscription-proxy-scan-content {border:0;padding:0;margin:0;min-width:0;}.model-result-search {margin:0;}.model-result-list {margin-top:-2px;overflow:hidden;border:1px solid var(--border);border-radius:12px;}.model-result-row {display:flex;align-items:center;border-bottom:1px solid var(--divider);}diff --git a/apps/desktop/src/occami/styles/occami.css b/apps/desktop/src/occami/styles/occami.cssindex fe2ea6cc..2364b522 100644--- a/apps/desktop/src/occami/styles/occami.css+++ b/apps/desktop/src/occami/styles/occami.css@@ -14,6 +14,9 @@.oc-status-row strong {display:block;font-size:calc(13px * var(--hr-text-scale));}.oc-status-row p {margin:6px 0 0;font-size:calc(12px * var(--hr-text-scale));line-height:1.7;color:var(--text-muted);}.oc-scan-detail {display:grid;gap:16px;}+.subscription-reuse-note {display:flex;flex-direction:column;align-items:flex-start;gap:10px;min-width:0;margin:0 0 16px;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-soft);}+.subscription-reuse-note>.oc-meta {margin:0;overflow-wrap:anywhere;}+.subscription-reuse-note>.btn {max-width:100%;height:auto;min-height:calc(36px * var(--hr-text-scale));padding:8px 14px;white-space:normal;line-height:1.45;text-align:center;}.oc-section-label {font-size:calc(12px * var(--hr-text-scale));font-weight:500;color:var(--text-muted);margin:22px 0 12px;}.oc-field-grid {display:grid;grid-template-columns:1fr 1fr;gap:0 16px;}.oc-field-grid>.field {min-width:0;}diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsxindex 8a1a28b5..103f231d 100644--- a/apps/desktop/src/product/DesktopApp.tsx+++ b/apps/desktop/src/product/DesktopApp.tsx@@ -40,6 +40,7 @@ import { RoutingPage, type RoutingEditorIntent } from './RoutingPage';import { SettingsPage } from './SettingsPage';import { useDesktopHome } from './use-desktop-home';import { safeDiagnosticCode } from '../error-code';+import { takeSubscriptionProxyReturn } from '../features/subscription-proxy-return';import { planErrorMessage } from '../plan-editor-errors';import {acceptObservedOperation,@@ -58,6 +59,7 @@ type ModelIntent = {key: string;sourceId?: string | null;startAdding?: boolean;+ startScanning?: boolean;notice?: string;};@@ -129,6 +131,14 @@ export function DesktopApp() {const pollingGeneration = useRef(0);const supersededPendingKey = useRef<string | null>(null);+ useEffect(() => {+ if (!home.desktopSnapshot?.trusted_authority || !home.desktopSnapshot.service.mutation_available) return;+ if (!takeSubscriptionProxyReturn()) return;+ setModelIntent({ key: 'models/proxy-return', startScanning: true });+ setVisited(current => new Set([...current, 'models']));+ setPage('models');+ }, [home.desktopSnapshot?.trusted_authority, home.desktopSnapshot?.service.mutation_available]);+const text = language === 'zh'? {pages: { home: '首页', models: '模型', routing: '智能路由', agents: 'Agent', sessions: '会话', settings: '设置' },@@ -649,11 +659,11 @@ export function DesktopApp() {language={language}active={page === 'models' && modelTab === 'general'}tabs={modelTabs}- onOpenNetworkSettings={() => void navigate('settings')}trustedAuthority={Boolean(home.desktopSnapshot?.trusted_authority && home.desktopSnapshot.service.mutation_available)}refreshVersion={refreshVersion}initialSourceId={modelIntent.sourceId}startAdding={modelIntent.startAdding}+ startScanning={modelIntent.startScanning}notice={modelIntent.notice}onOperation={value => acceptOperation(value, { kind: 'model-connection' })}onRecoveryRefresh={() => void home.refreshAll()}@@ -742,13 +752,11 @@ export function DesktopApp() {language={language}languagePreference={preferences.languagePreference}theme={preferences.theme}- textScale={preferences.textScale}serviceLabel={settingsServiceLabel}serviceReady={serviceOperational}onServiceChanged={home.refreshDesktop}onLanguageChange={preferences.setLanguage}onThemeChange={preferences.setTheme}- onTextScaleChange={preferences.setTextScale}onOpenSessions={() => {void (async () => {if (!await allowPageChange('sessions')) return;diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsxindex c3c3a108..50bbb88f 100644--- a/apps/desktop/src/product/ModelManagementPage.tsx+++ b/apps/desktop/src/product/ModelManagementPage.tsx@@ -2,6 +2,7 @@ import { managementLoadFailureCopy, subscriptionFailureCopy } from '../features/import { requestEditorReplacement } from '../ui/discard-guard';import { useEffect, useMemo, useRef, useState } from 'react';import { invoke } from '@tauri-apps/api/core';+import { SubscriptionProxySettings } from '../features/SubscriptionProxySettings';import { ModelConnectionForm } from '../features/model-connections/ModelConnectionForm';import { blankModel } from '../features/model-connections/form-support';import { checkMatches, clientIdempotencyKey, modelSaveCompleted, savedSourceConnectionFields } from '../features/model-connections/state';@@ -146,6 +147,7 @@ export function ModelManagementPage({trustedAuthority,initialSourceId = null,startAdding = false,+ startScanning = false,notice,onOperation,onRecoveryRefresh,@@ -155,7 +157,6 @@ export function ModelManagementPage({agents = [],onOpenPlan,onCreatePlan,- onOpenNetworkSettings,tabs,}: {language: 'zh' | 'en';@@ -163,6 +164,7 @@ export function ModelManagementPage({trustedAuthority: boolean;initialSourceId?: string | null;startAdding?: boolean;+ startScanning?: boolean;notice?: string;onOperation(operation: OperationReference): void;onRecoveryRefresh(): void;@@ -172,7 +174,6 @@ export function ModelManagementPage({agents?: Agent[];onOpenPlan?(planId: string): void;onCreatePlan?(bindingId: string): void;- onOpenNetworkSettings?(): void;tabs?: import('react').ReactNode;}) {const [management, setManagement] = useState<ManagementSnapshot | null>(null);@@ -196,6 +197,9 @@ export function ModelManagementPage({const [discoveryAction, setDiscoveryAction] = useState<DiscoveryAction>(null);const [discoveryError, setDiscoveryError] = useState('');const [adding, setAdding] = useState(startAdding && trustedAuthority);+ const [editingSubscriptionProxy, setEditingSubscriptionProxy] = useState(false);+ const proxyButton = useRef<HTMLButtonElement>(null);+ const scanResumed = useRef(false);const [reconnectingFrom, setReconnectingFrom] = useState<string | null>(null);const [addStage, setAddStage] = useState<'choose' | 'api' | 'scan' | 'subscription-login' | 'existing'>('choose');const [appendingSource, setAppendingSource] = useState<ManagedSource | null>(null);@@ -667,6 +671,13 @@ export function ModelManagementPage({useEffect(() => { if (refreshVersion > 0) void refreshManagement(); }, [refreshVersion]);+ useEffect(() => {+ if (!startScanning || !trustedAuthority || !active || scanResumed.current) return;+ scanResumed.current = true;+ setAdding(true);+ setAddStage('scan');+ }, [startScanning, trustedAuthority, active]);+const backend = useMemo<ModelConnectionBackend>(() => ({registerProtectedInput: secret => invoke<ProtectedInputRegistration>('register_protected_model_input',@@ -996,6 +1007,7 @@ export function ModelManagementPage({}function closeScan() {+ setEditingSubscriptionProxy(false);setAppendingSource(null);setAppendManual(false);setAdding(false);@@ -1003,6 +1015,11 @@ export function ModelManagementPage({requestAnimationFrame(() => addButton.current?.focus());}+ function cancelSubscriptionProxy() {+ setEditingSubscriptionProxy(false);+ requestAnimationFrame(() => proxyButton.current?.focus());+ }+const subscriptionSaving = subscriptionAction === 'saving';const discoverySaving = discoveryAction === 'saving';const scanWorking = subscriptionWorking || discoveryAction !== null;@@ -1076,7 +1093,7 @@ export function ModelManagementPage({</button><button className="add-choice" type="button" disabled={!trustedAuthority} onClick={() => setAddStage('subscription-login')}><span className="choice-icon"><UiIcon name="plug" /></span>- <div><strong>{language === 'zh' ? '连接订阅' : 'Connect subscription'}</strong><span>{language === 'zh' ? '独立登录 Codex / Claude Code,自动续期' : 'Sign in independently to Codex / Claude Code with automatic renewal'}</span></div>+ <div><strong>{language === 'zh' ? '连接订阅' : 'Connect subscription'}</strong><span>{language === 'zh' ? '独立登录 Codex / Claude Code,自动刷新登录凭据' : 'Sign in independently to Codex / Claude Code with automatic credential refresh'}</span></div><UiIcon name="chevronRight" /></button><button className="add-choice" type="button" disabled={!trustedAuthority} onClick={() => { returnToScanList(); setSelectedSubscriptionRef(null); setRepairingSubscriptionSource(null); setSubscriptionNotice(''); setAddStage('scan'); void Promise.all([refreshSubscriptions(), recoverSubscriptionCheck()]); }}>@@ -1110,8 +1127,15 @@ export function ModelManagementPage({setAddStage('scan');}} />}</Dialog>- <Dialog open={adding && addStage === 'scan'} title={language === 'zh' ? '扫描本机' : 'Scan this device'} closeLabel={subscriptionSaving || discoverySaving ? (language === 'zh' ? '正在保存' : 'Saving') : (language === 'zh' ? '关闭扫描' : 'Close scan')} closeDisabled={subscriptionSaving || discoverySaving} onClose={closeScan} footer={scanFooter}>- {onOpenNetworkSettings && <p className="oc-meta">{language === 'zh' ? '订阅连接需要代理?' : 'Need a proxy for subscriptions?'} <button className="btn" type="button" disabled={scanWorking || subscriptionSaving || discoverySaving} onClick={() => { closeScan(); onOpenNetworkSettings(); }}>{language === 'zh' ? '设置订阅连接代理' : 'Configure subscription proxy'}</button></p>}+ <SubscriptionProxySettings+ language={language}+ editing={adding && addStage === 'scan' && editingSubscriptionProxy}+ writable={trustedAuthority}+ onCancel={cancelSubscriptionProxy}+ >{({ panel, actions, saving }) => <Dialog open={adding && addStage === 'scan'} title={language === 'zh' ? '扫描本机' : 'Scan this device'} closeLabel={editingSubscriptionProxy ? (language === 'zh' ? '取消代理设置' : 'Cancel proxy settings') : subscriptionSaving || discoverySaving ? (language === 'zh' ? '正在保存' : 'Saving') : (language === 'zh' ? '关闭扫描' : 'Close scan')} closeDisabled={saving || subscriptionSaving || discoverySaving} onClose={editingSubscriptionProxy ? cancelSubscriptionProxy : closeScan} footer={editingSubscriptionProxy ? actions : scanFooter}>+ <p className="oc-meta">{language === 'zh' ? '订阅连接需要代理?' : 'Need a proxy for subscriptions?'} <button ref={proxyButton} className="btn" type="button" aria-expanded={editingSubscriptionProxy} disabled={!trustedAuthority || scanWorking || editingSubscriptionProxy} onClick={() => setEditingSubscriptionProxy(true)}>{language === 'zh' ? '设置订阅连接代理' : 'Configure subscription proxy'}</button></p>+ {panel}+ <fieldset className="subscription-proxy-scan-content" disabled={editingSubscriptionProxy}>{scanWorking ? <div className="oc-status-row" role="status"><span className="oc-spinner" /><div className="row-main"><strong>{discoveryAction === 'preparing'? (language === 'zh' ? '正在读取配置' : 'Reading configuration'): discoveryAction === 'saving' || subscriptionAction === 'saving'@@ -1149,6 +1173,7 @@ export function ModelManagementPage({computeScanFailed={Boolean(computeScanError)}repairingSubscriptionSource={repairingSubscriptionSource}trustedAuthority={trustedAuthority}+ onConnectSubscription={() => { closeSubscriptionView(); setAppendingSource(null); setAppendManual(false); setAddStage('subscription-login'); }}onOpenSubscription={openSubscription}onViewConnectedSubscription={viewConnectedSubscription}onOpenDiscoveredConfiguration={item => void prepareDiscoveredConfiguration(item)}@@ -1156,7 +1181,8 @@ export function ModelManagementPage({{subscriptionNotice && !scanWorking && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{subscriptionNotice}</span></div></div>}{subscriptionError && subscriptionError.phase !== 'scan' && !scanWorking && <div className="callout bad" role="alert" data-error-code={subscriptionError.code}><UiIcon name="warning" /><span>{subscriptionFailureMessage(subscriptionError, language)}</span></div>}{discoveryError && !scanWorking && <div className="callout bad" role="alert" data-error-code={discoveryError}><UiIcon name="warning" /><span>{discoveryFailureMessage(discoveryError, language)}</span></div>}- </Dialog>+ </fieldset>+ </Dialog>}</SubscriptionProxySettings>{(notice || modelNotice) && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{notice || modelNotice}</span></div></div>}{loading && <div className="empty-state" role="status"><div><span className="oc-spinner" /><p>{text.loading}</p></div></div>}{error && <div className="callout bad" role="alert" data-error-code={error}><UiIcon name="warning" /><span>{managementLoadFailureCopy(error, language).detail}</span><button className="btn" type="button" onClick={() => void refreshManagement()}>{managementLoadFailureCopy(error, language).retry}</button></div>}diff --git a/apps/desktop/src/product/SettingsPage.tsx b/apps/desktop/src/product/SettingsPage.tsxindex 22978228..0b8d5cad 100644--- a/apps/desktop/src/product/SettingsPage.tsx+++ b/apps/desktop/src/product/SettingsPage.tsx@@ -1,20 +1,18 @@import { invoke } from '@tauri-apps/api/core';import { useEffect, useState } from 'react';-import { SubscriptionProxySettings } from '../features/SubscriptionProxySettings';import { DiagnosticsSettings } from '../features/diagnostics/DiagnosticsSettings';import { UpdatesSettings } from '../features/UpdatesSettings';import { safeDiagnosticCode } from '../error-code';import { ProductPage } from '../ui';-import type { Language, LanguagePreference, TextScale, ThemePreference } from '../ui/preferences';+import type { Language, LanguagePreference, ThemePreference } from '../ui/preferences';import { listenerApplyRequest, listenerScopeFromAddress, type GatewayListenerScope } from './gateway-listener-scope';type SettingsPageProps = {- active: boolean; language: Language; languagePreference: LanguagePreference; theme: ThemePreference; textScale: TextScale;+ active: boolean; language: Language; languagePreference: LanguagePreference; theme: ThemePreference;serviceLabel: string; serviceReady: boolean;onServiceChanged: () => Promise<void>;onLanguageChange: (language: LanguagePreference) => void;onThemeChange: (theme: ThemePreference) => void;- onTextScaleChange: (scale: TextScale) => void;onOpenSessions: (scope?: 'content_only' | 'facts_and_content') => void;};@@ -178,9 +176,6 @@ export function SettingsPage(props: SettingsPageProps) {<div className="settings-row"><div className="settings-copy"><strong>{text('外观', 'Appearance')}</strong><span>{text('默认跟随系统,可随时切换', 'Follows the system by default')}</span></div><div className="segmented">{(['system', 'light', 'dark'] as const).map(theme => <button type="button" key={theme} className={`segment ${props.theme === theme ? 'active' : ''}`} aria-pressed={props.theme === theme} onClick={() => props.onThemeChange(theme)}>{theme === 'system' ? text('跟随系统', 'System') : theme === 'light' ? text('浅色', 'Light') : text('深色', 'Dark')}</button>)}</div></div>- <div className="settings-row"><div className="settings-copy"><strong>{text('文字大小', 'Text size')}</strong><span>{text('标题、正文、提示和控件一起缩放', 'Scales headings, body text, messages, and controls together')}</span></div>- <div className="segmented">{([1, 1.5, 2] as const).map(scale => <button type="button" key={scale} className={`segment ${props.textScale === scale ? 'active' : ''}`} aria-pressed={props.textScale === scale} onClick={() => props.onTextScaleChange(scale)}>{Math.round(scale * 100)}%</button>)}</div>- </div></div></section><section className="settings-group"><h2>Worker</h2><div className="settings-list"><div className="settings-row"><div className="settings-copy"><strong>{text('并发任务上限', 'Concurrent task limit')}</strong><span>{workerLimit === null ? text('允许 1–1000 个任务', 'Allows 1–1000 tasks') : text(`当前生效:${workerLimit}`, `Effective now: ${workerLimit}`)}</span></div>@@ -193,7 +188,6 @@ export function SettingsPage(props: SettingsPageProps) {<div className="settings-copy"><strong>{text('会话内容', 'Session content')}</strong><span>{text('在会话详情中,可以清理该会话的正文或记录。', 'Clear content or records from each session’s detail view.')}</span></div><button className="btn" type="button" onClick={() => props.onOpenSessions()}>{text('查看会话', 'View sessions')}</button></div></div></section>- <SubscriptionProxySettings active={props.active} language={props.language} /><DiagnosticsSettings active={props.active} language={props.language} /><UpdatesSettings active={props.active} language={props.language} onServiceChanged={props.onServiceChanged} /><section className="settings-group"><h2>CLI</h2><div className="settings-list"><div className="settings-row">diff --git a/apps/desktop/src/style.css b/apps/desktop/src/style.cssindex 46e274e1..93b2acd3 100644--- a/apps/desktop/src/style.css+++ b/apps/desktop/src/style.css@@ -143,6 +143,3 @@ body { background: #f5f6f9; }@media (prefers-reduced-motion: reduce) {.hr-ui * { scroll-behavior: auto !important; transition: none !important; }}--.subscription-proxy-control { display: flex; flex-direction: column; gap: 10px; width: min(420px, 100%); min-width: 0; }-.subscription-proxy-control .input, .subscription-proxy-control .select { width: 100%; }diff --git a/apps/desktop/src/ui/PresentationControls.tsx b/apps/desktop/src/ui/PresentationControls.tsxindex 14f2f0c5..8ad6511d 100644--- a/apps/desktop/src/ui/PresentationControls.tsx+++ b/apps/desktop/src/ui/PresentationControls.tsx@@ -1,11 +1,11 @@-import type { Language, LanguagePreference, TextScale, ThemePreference } from './preferences';+import type { Language, LanguagePreference, ThemePreference } from './preferences';const copy = {zh: {- language: '显示语言', theme: '外观', scale: '文字大小', system: '跟随系统', light: '浅色', dark: '深色',+ language: '显示语言', theme: '外观', system: '跟随系统', light: '浅色', dark: '深色',},en: {- language: 'Display language', theme: 'Appearance', scale: 'Text size', system: 'System', light: 'Light', dark: 'Dark',+ language: 'Display language', theme: 'Appearance', system: 'System', light: 'Light', dark: 'Dark',},};@@ -13,18 +13,14 @@ export function PresentationControls({language,languagePreference,theme,- textScale,onLanguageChange,onThemeChange,- onTextScaleChange,}: {language: Language;languagePreference: LanguagePreference;theme: ThemePreference;- textScale: TextScale;onLanguageChange: (language: LanguagePreference) => void;onThemeChange: (theme: ThemePreference) => void;- onTextScaleChange: (scale: TextScale) => void;}) {const text = copy[language];return (@@ -47,14 +43,6 @@ export function PresentationControls({))}</div></fieldset>- <label>- <span>{text.scale}</span>- <select value={String(textScale)} onChange={event => onTextScaleChange(Number(event.target.value) as TextScale)}>- <option value="1">100%</option>- <option value="1.5">150%</option>- <option value="2">200%</option>- </select>- </label></div>);}diff --git a/apps/desktop/src/ui/preferences.ts b/apps/desktop/src/ui/preferences.tsindex 884028ec..d2e52848 100644--- a/apps/desktop/src/ui/preferences.ts+++ b/apps/desktop/src/ui/preferences.ts@@ -9,7 +9,7 @@ export type TextScale = 1 | 1.5 | 2;export type PresentationPreferences = {language: LanguagePreference;theme: ThemePreference;- textScale: TextScale;+ textScale: 1;};export type PresentationPreferenceController = Omit<PresentationPreferences, 'language'> & {@@ -18,7 +18,6 @@ export type PresentationPreferenceController = Omit<PresentationPreferences, 'laresolvedTheme: ResolvedTheme;setLanguage: (language: LanguagePreference) => void;setTheme: (theme: ThemePreference) => void;- setTextScale: (scale: TextScale) => void;};export type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;@@ -58,18 +57,16 @@ export function loadPresentationPreferences(): PresentationPreferences {let language: string | null = null;let theme: string | null = null;- let textScale: string | null = null;try {language = storage?.getItem(LANGUAGE_STORAGE_KEY) ?? null;theme = storage?.getItem(THEME_STORAGE_KEY) ?? null;- textScale = storage?.getItem(TEXT_SCALE_STORAGE_KEY) ?? null;} catch {// A denied or damaged localStorage must not prevent the UI from starting.}return {language: parseLanguagePreference(language),theme: parseTheme(theme),- textScale: parseTextScale(textScale),+ textScale: 1,};}@@ -81,7 +78,8 @@ export function savePresentationPreferences(try {storage.setItem(LANGUAGE_STORAGE_KEY, preferences.language);storage.setItem(THEME_STORAGE_KEY, preferences.theme);- storage.setItem(TEXT_SCALE_STORAGE_KEY, String(preferences.textScale));+ // Normalize previously enlarged application text to the fixed default.+ storage.setItem(TEXT_SCALE_STORAGE_KEY, '1');} catch {// Preferences remain effective for this session when persistence is unavailable.}@@ -142,6 +140,5 @@ export function usePresentationPreferences(resolvedTheme: resolveTheme(preferences.theme, prefersDark),setLanguage: (language: LanguagePreference) => setPreferences(current => ({ ...current, language })),setTheme: (theme: ThemePreference) => setPreferences(current => ({ ...current, theme })),- setTextScale: (textScale: TextScale) => setPreferences(current => ({ ...current, textScale })),}), [preferences, prefersDark, systemLanguage]);}diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex 71f22e90..f41f7bb8 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -23,7 +23,9 @@ proves native authorization, persistence, process cleanup or real model calls.| Continue editing after route save | `routing.save.unobserved-editable` | An unobserved result does not lock the editor or other routes. || Publish a smaller budget used by Qoder | `routing.publish.qoder-budget-conflict`, `desktop.routing.qoder-budget-checkpoint` | Both immediate rejection and an accepted operation's checkpoint failure keep edits and explain disabling only Qoder model routing before publication and reconfiguration; neither disables collaboration nor calls models. || Follow a submitted operation | `desktop.operation.dismiss-observes`, `desktop.operation.identity-retry-converges`, `desktop.operation.repeated-submission` in [shell scenarios](v3/browser/product-shell-scenarios.mjs); [operation rules](operation-feedback.test.mjs) | Dismissal does not cancel observation; mismatched identity stays neutral through grace/retry; repeated accepted or unknown saves restart observation; success refreshes and dismisses. Pure tests retain identity, sequence and terminal-state edges. |-| Adjust presentation | `desktop.settings.persisted-scale`; [preference tests](presentation-preferences.test.mjs) | All supported scales reach the real shell and storage; parsing/storage failure rules remain separately testable. |+| Adjust presentation | `desktop.settings.fixed-scale`; [preference tests](presentation-preferences.test.mjs) | Settings retain language and appearance controls; application text stays at 100% with no size selector. Previous 150/200% browser preferences normalize to 100% without changing language or theme, including after remount. Storage failure rules remain separately testable. |+| Configure the shared subscription proxy from a device scan | `desktop.models.subscription-proxy.inline-cancel`, `desktop.models.subscription-proxy.read-retry`, `desktop.models.subscription-proxy.save-retry-return`; [restart hint tests](subscription-proxy-return.test.mjs) | The inline editor preserves scan results and selection, removes the Settings entry, prevents an unread-policy overwrite and retains failed-save input. A simulated restart reloads the scan and saved policy; native restart, persistence and provider transport require production acceptance. |+| Choose independent subscription sign-in from a device scan | `desktop.models.subscription-scan.recommended-login`, `desktop.models.subscription-scan.append-to-login` | Scan explains native credential refresh and links to the existing independent sign-in without starting authorization or saving. Changing from an append scan to independent sign-in clears the previous connection target, so a new account saves as a new connection. Chinese/English at the fixed 100% size and 755×600 protect wrapping, visible actions and the initial login explanation while session loading is delayed, including previously enlarged browser preferences. Real OAuth refresh retains its separate native gate. || Return to routing or configure a classifier | `desktop.routing.reactivation-models`, `desktop.routing.classifier-protocol` | An existing editor refreshes saved model names; quality uses active models; selection, curl copy and native-save outcomes are visible. || Connect decision models and custom extensions | `desktop.decisions.save-test-revision`, `desktop.decisions.discard-navigation`; [authentication and reference rules](decision-presentation.test.mjs) | Save-and-test uses the newly saved credential revision; failures remain actionable, origin changes clear credentials, and discard clears retained editors. || Correct an invalid collapsed connection field | `desktop.decisions.hidden-invalid-field` | Submission opens and focuses the field, scrolls the complete field and error above sticky actions, and does not save the invalid value. |@@ -65,7 +67,7 @@ CHROME_BIN=/path/to/chrome node tests/v3/visual/agent-trust.mjs /tmp/hiroute-ageThe full browser run discovers all Agent, routing/Worker and shell scenarios, plusthe model-to-route scenario. Focused browser flags remain available:`--claude-collaboration-only`, `--worker-replacement-only`, `--route-save-only`,-and `--shell-only` (after the output directory). Unknown flags fail. For selection+`--subscription-proxy-only`, and `--shell-only` (after the output directory). Unknown flags fail. For selectionlogic alone, run `node --test tests/scenario-selection.test.mjs`.Choose the configured native Desktop/Pilot entry separately for real authorization,diff --git a/apps/desktop/tests/mvp16/README.md b/apps/desktop/tests/mvp16/README.mdindex 8953ce54..d2cfa6d6 100644--- a/apps/desktop/tests/mvp16/README.md+++ b/apps/desktop/tests/mvp16/README.md@@ -24,4 +24,6 @@ Example deterministic URLs:- `http://127.0.0.1:4176/?scenario=partial&lang=en&theme=light&scale=1.5`- `http://127.0.0.1:4176/?scenario=drift&lang=zh&theme=dark&scale=2`+`scale` 参数只用于通用组件的布局压力检查;产品界面固定 100% 字号。显示设置与输入保留夹具只提供语言和外观选项。+The surface records navigation intents as local JSON only. It cannot prove model saving, Agent calls, Worker delegation, or any Desktop-to-backend production path.diff --git a/apps/desktop/tests/mvp16/browser/main.tsx b/apps/desktop/tests/mvp16/browser/main.tsxindex a5f53a98..f1d39429 100644--- a/apps/desktop/tests/mvp16/browser/main.tsx+++ b/apps/desktop/tests/mvp16/browser/main.tsx@@ -50,7 +50,7 @@ function Harness() {const [languagePreference, setLanguagePreference] = useState<LanguagePreference>(initialLanguage);const language = resolveLanguage(languagePreference, navigator.language);const [theme, setTheme] = useState<ThemePreference>(initialTheme);- const [textScale, setTextScale] = useState<TextScale>(initialScale);+ const [textScale] = useState<TextScale>(initialScale);const [scenario, setScenario] = useState<ScenarioName>(initialScenario);const [settingsOpen, setSettingsOpen] = useState(false);const [editorOpen, setEditorOpen] = useState(false);@@ -60,8 +60,8 @@ function Harness() {const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;const resolvedTheme = resolveTheme(theme, prefersDark);const text = language === 'zh'- ? { page: '首页', settings: '显示设置', edit: '测试输入保留', close: '关闭', check: '组件检查', scenario: '场景', saveDraft: '保留输入', discardTitle: '放弃未保存输入?', discardBody: '只有这段非敏感测试输入会丢失。', keep: '继续编辑', discard: '放弃输入', draft: '非敏感草稿', draftHint: '切换语言、主题或字号后,这段输入必须仍然存在。' }- : { page: 'Home', settings: 'Display settings', edit: 'Test input retention', close: 'Close', check: 'Component check', scenario: 'Scenario', saveDraft: 'Keep input', discardTitle: 'Discard unsaved input?', discardBody: 'Only this non-sensitive test input will be lost.', keep: 'Keep editing', discard: 'Discard input', draft: 'Non-sensitive draft', draftHint: 'This input must remain after language, theme, or text-size changes.' };+ ? { page: '首页', settings: '显示设置', edit: '测试输入保留', close: '关闭', check: '组件检查', scenario: '场景', saveDraft: '保留输入', discardTitle: '放弃未保存输入?', discardBody: '只有这段非敏感测试输入会丢失。', keep: '继续编辑', discard: '放弃输入', draft: '非敏感草稿', draftHint: '切换语言或主题后,这段输入必须仍然存在。' }+ : { page: 'Home', settings: 'Display settings', edit: 'Test input retention', close: 'Close', check: 'Component check', scenario: 'Scenario', saveDraft: 'Keep input', discardTitle: 'Discard unsaved input?', discardBody: 'Only this non-sensitive test input will be lost.', keep: 'Keep editing', discard: 'Discard input', draft: 'Non-sensitive draft', draftHint: 'This input must remain after language or theme changes.' };function closeEditor() {discard.requestClose();@@ -85,7 +85,7 @@ function Harness() {</div></div><Dialog open={settingsOpen} title={text.settings} description={language === 'zh' ? '偏好是本机非秘密数据;切换不会重建页面业务状态。' : 'Preferences are non-secret local data. Changes do not recreate page state.'} closeLabel={text.close} onClose={() => setSettingsOpen(false)}>- <PresentationControls language={language} languagePreference={languagePreference} theme={theme} textScale={textScale} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} onTextScaleChange={setTextScale} />+ <PresentationControls language={language} languagePreference={languagePreference} theme={theme} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} /></Dialog><Dialogopen={editorOpen}@@ -99,7 +99,7 @@ function Harness() {><label className="hr-test-draft"><span>{text.draft}</span><textarea id="draft-note" data-autofocus value={draft} onChange={event => setDraft(event.target.value)} /></label><div className="hr-test-draft-prefs">- <PresentationControls language={language} languagePreference={languagePreference} theme={theme} textScale={textScale} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} onTextScaleChange={setTextScale} />+ <PresentationControls language={language} languagePreference={languagePreference} theme={theme} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} /></div></Dialog></PresentationRoot>diff --git a/apps/desktop/tests/mvp16/contracts/preferences.test.ts b/apps/desktop/tests/mvp16/contracts/preferences.test.tsindex a7b997c1..6e57a79c 100644--- a/apps/desktop/tests/mvp16/contracts/preferences.test.ts+++ b/apps/desktop/tests/mvp16/contracts/preferences.test.ts@@ -19,11 +19,11 @@ class MemoryStorage implements StorageLike {setItem(key: string, value: string) { this.values.set(key, value); }}-test('preferences reuse existing language and text-scale keys', () => {+test('preferences retain language and normalize the previous enlarged text scale', () => {const storage = new MemoryStorage();storage.setItem(LANGUAGE_STORAGE_KEY, 'zh');storage.setItem(TEXT_SCALE_STORAGE_KEY, '1.5');- assert.deepEqual(loadPresentationPreferences(storage), { language: 'zh', theme: 'system', textScale: 1.5 });+ assert.deepEqual(loadPresentationPreferences(storage), { language: 'zh', theme: 'system', textScale: 1 });});test('language follows the system until an explicit preference is stored', () => {@@ -48,10 +48,10 @@ test('invalid scale fails closed to 100 percent', () => {test('explicit preferences persist without business state', () => {const storage = new MemoryStorage();- savePresentationPreferences(storage, { language: 'en', theme: 'dark', textScale: 2 });+ savePresentationPreferences(storage, { language: 'en', theme: 'dark', textScale: 1 });assert.equal(storage.getItem(LANGUAGE_STORAGE_KEY), 'en');assert.equal(storage.getItem(THEME_STORAGE_KEY), 'dark');- assert.equal(storage.getItem(TEXT_SCALE_STORAGE_KEY), '2');+ assert.equal(storage.getItem(TEXT_SCALE_STORAGE_KEY), '1');assert.equal(storage.values.size, 3);});diff --git a/apps/desktop/tests/presentation-preferences.test.mjs b/apps/desktop/tests/presentation-preferences.test.mjsindex 3c5b12f2..6fd8e5b6 100644--- a/apps/desktop/tests/presentation-preferences.test.mjs+++ b/apps/desktop/tests/presentation-preferences.test.mjs@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';import test from 'node:test';import {LANGUAGE_STORAGE_KEY,+ TEXT_SCALE_STORAGE_KEY,+ THEME_STORAGE_KEY,loadPresentationPreferences,parseLanguagePreference,resolveLanguage,@@ -40,5 +42,19 @@ test('unavailable storage keeps safe in-session defaults', () => {setItem() { throw new Error('denied'); },};assert.deepEqual(loadPresentationPreferences(storage), { language: 'system', theme: 'system', textScale: 1 });- assert.doesNotThrow(() => savePresentationPreferences(storage, { language: 'zh', theme: 'dark', textScale: 2 }));+ assert.doesNotThrow(() => savePresentationPreferences(storage, { language: 'zh', theme: 'dark', textScale: 1 }));+});++test('previous enlarged text normalizes to 100 percent while preserving language and appearance', () => {+ for (const scale of ['1.5', '2']) {+ const storage = new MemoryStorage();+ storage.setItem(LANGUAGE_STORAGE_KEY, 'en');+ storage.setItem(THEME_STORAGE_KEY, 'dark');+ storage.setItem(TEXT_SCALE_STORAGE_KEY, scale);+ const preferences = loadPresentationPreferences(storage);+ assert.deepEqual(preferences, { language: 'en', theme: 'dark', textScale: 1 });+ savePresentationPreferences(storage, preferences);+ assert.equal(storage.getItem(TEXT_SCALE_STORAGE_KEY), '1');+ assert.deepEqual(loadPresentationPreferences(storage), preferences);+ }});diff --git a/apps/desktop/tests/subscription-proxy-return.test.mjs b/apps/desktop/tests/subscription-proxy-return.test.mjsnew file mode 100644index 00000000..b25bb48b--- /dev/null+++ b/apps/desktop/tests/subscription-proxy-return.test.mjs@@ -0,0 +1,41 @@+import assert from 'node:assert/strict';+import { afterEach, test } from 'node:test';+import { requestSubscriptionProxyReturn, clearSubscriptionProxyReturn, takeSubscriptionProxyReturn } from '../src/features/subscription-proxy-return.ts';++function storage() {+ const values = new Map();+ globalThis.window = { localStorage: {+ getItem: key => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: key => values.delete(key),+ } };+ return values;+}+afterEach(() => { delete globalThis.window; });++test('the restart hint is consumed once and stores only a timestamp', () => {+ const values = storage();+ requestSubscriptionProxyReturn();+ assert.equal(values.size, 1);+ assert.match([...values.values()][0], /^\d+$/);+ assert.equal(takeSubscriptionProxyReturn(), true);+ assert.equal(takeSubscriptionProxyReturn(), false);+ requestSubscriptionProxyReturn(); clearSubscriptionProxyReturn();+ assert.equal(takeSubscriptionProxyReturn(), false);+});++test('damaged, expired and future hints do not reopen a scan later', () => {+ const values = storage();+ for (const value of ['broken', String(Date.now() - 300_001), String(Date.now() + 60_000)]) {+ values.set('hiroute.subscription-proxy-return', value);+ assert.equal(takeSubscriptionProxyReturn(), false);+ assert.equal(values.size, 0);+ }+});++test('unavailable WebView storage leaves ordinary startup usable', () => {+ globalThis.window = { get localStorage() { throw new Error('denied'); } };+ assert.equal(takeSubscriptionProxyReturn(), false);+ assert.doesNotThrow(clearSubscriptionProxyReturn);+ assert.throws(requestSubscriptionProxyReturn);+});diff --git a/apps/desktop/tests/v3/browser/main.tsx b/apps/desktop/tests/v3/browser/main.tsxindex c8d6f313..1841474d 100644--- a/apps/desktop/tests/v3/browser/main.tsx+++ b/apps/desktop/tests/v3/browser/main.tsx@@ -69,7 +69,7 @@ function Harness() {const [languagePreference, setLanguagePreference] = useState<LanguagePreference>(() => parseLanguage(params.get('lang'), 'zh'));const language = resolveLanguage(languagePreference, navigator.language);const [theme, setTheme] = useState<ThemePreference>(() => parseTheme(params.get('theme')));- const [textScale, setTextScale] = useState<TextScale>(() => parseTextScale(params.get('scale')));+ const [textScale] = useState<TextScale>(() => parseTextScale(params.get('scale')));const [page, setPage] = useState<Page>(initialPage);const [newRouteFromModel, setNewRouteFromModel] = useState<string | null>(null);const reads = productHomeReads(scenario);@@ -125,7 +125,7 @@ function Harness() {: page === 'routing' ? <RoutingPage language={language} snapshot={freshProduct ? { ...readyDesktop, catalog: { plans: [], drafts: [] } } : readyDesktop} agentSnapshot={freshProduct ? { ...readyAgents, agents: [] } : readyAgents} loading={false} busy={false} initialEditor={newRouteFromModel ? { key: 'new/from-model', initialBindingId: newRouteFromModel } : freshProduct ? null : { key: dailyPlan.agent_plan_id, plan: dailyPlan }} onRefresh={async () => undefined} onOperation={() => undefined} onOpenAgent={() => setPage('agents')} />: page === 'agents' ? <Agents language={language} initialAgentId={params.get('capture') === 'task_routing_only' ? 'agent_claude_default' : null} initialFacet="collaboration" initialTab={scenario === 'task_cancelled' ? 'tasks' : 'configuration'} initialTaskId={scenario === 'task_cancelled' ? 'task/fix-empty-list' : null} taskRead={taskRead} onTaskCancel={async (_task, onAccepted) => { fixtureTrace.commands.push('fixture_task_cancel'); onAccepted?.('cancelling'); await wait(1200); return 'cancelled'; }} onOpenTaskSession={() => setPage('sessions')} onCreatePlan={() => setPage('routing')} onMutation={() => undefined} />: page === 'sessions' ? <Sessions language={language} initialSession={scenario === 'gap' ? 'session/stream-gap' : null} onOpenAgents={() => setPage('agents')} />- : <SettingsPage active language={language} languagePreference={languagePreference} theme={theme} textScale={textScale} serviceLabel={labels.service} serviceReady={serviceReady} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} onTextScaleChange={setTextScale} onOpenSessions={() => setPage('sessions')} />;+ : <SettingsPage active language={language} languagePreference={languagePreference} theme={theme} serviceLabel={labels.service} serviceReady={serviceReady} onServiceChanged={async () => {}} onLanguageChange={setLanguagePreference} onThemeChange={setTheme} onOpenSessions={() => setPage('sessions')} />;return <PresentationRoot language={language} theme={resolveTheme(theme, matchMedia('(prefers-color-scheme: dark)').matches)} textScale={textScale}><div className="app-window">diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjsindex da6d6df1..e90cfa41 100644--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs@@ -14,8 +14,14 @@ async function until(predicate, label, timeout = 6000) {await pause(30);}async function click(label) { await until(() => button(label), label); button(label).click(); await pause(40); }+async function deviceScan() {+ await click('模型'); await click('添加模型');+ await until(() => all('.add-choice').some(item => item.textContent.includes('扫描本机')), 'scan choice');+ all('.add-choice').find(item => item.textContent.includes('扫描本机')).click();+ await until(() => button('设置订阅连接代理') && !button('设置订阅连接代理').disabled, 'ready device scan');+}async function fresh(setup = () => {}) {- c().reset(); setup(); await until(() => text().includes('仅在本机运行'), 'ready DesktopApp');+ c().reset(); setup(); await until(() => visible(document.querySelector('.sidebar-health .status-dot.good')), 'ready DesktopApp');}function setInput(input, value) {assert(input, 'Expected an editable input');@@ -38,6 +44,172 @@ async function routing() {await until(() => document.querySelector('.plan-identity-fields input'), 'route editor');}const scenarios = [+ scenario('desktop.models.subscription-scan.append-to-login', ['subscription-proxy', 'subscription-login'], 'Independent sign-in from an append scan creates a new connection instead of retaining the previous append target', async () => {+ let previous;+ await fresh(() => {+ previous = JSON.stringify(c().management.sources.find(source => source.source_id === 'source/codex/subscription'));+ const borrowed = c().fixtureResponse('compute_subscriptions', {}).candidates[0];+ const pending = { ...borrowed, existing_source_id: undefined, display_name: 'New independent account', candidate: { candidate_ref: 'candidate/independent-new-account', candidate_revision: 1 } };+ const base = c().fixtureResponse('check_subscription', {});+ const checked = { ...base.checked_candidate, existing_source_id: undefined, display_name: pending.display_name,+ candidate: { ...pending.candidate, candidate_revision: 2 },+ models: [{ ...base.checked_candidate.models[0], model_ref: 'model-ref/independent-new-account' }],+ };+ c().handlers.compute_subscriptions = () => ({ discovery_state: 'complete', candidates: [borrowed, pending] });+ c().handlers.manage_subscription_login = ({ request }) => ({ schema: 'hiroute.subscription-login-result/v1', sessions: request.provider === 'codex'+ ? [{ provider: 'codex', login_ref: 'login/independent-new-account', status: 'authorized', candidate: pending.candidate }]+ : [] });+ c().handlers.check_subscription = () => ({ ...base, candidate: checked.candidate, checked_candidate: checked });+ });+ await click('模型'); await click('向此接入添加模型');+ await until(() => button('返回') && text().includes('Codex 本机订阅'), 'append subscription detail');+ await click('返回'); await click('连接订阅(推荐)');+ await click('检查并选择模型'); await click('检查订阅');+ await until(() => button('保存接入'), 'new account checked');+ await click('保存接入');+ await until(() => calls('preview_compute_save').length || document.querySelector('[data-error-code]'), 'save outcome');+ assert(calls('preview_compute_save').length === 1, 'New independent account kept the previous append target and cannot save');+ const change = calls('preview_compute_save')[0].payload.change;+ assert(!change.edit && change.subject.candidate.candidate_ref === 'candidate/independent-new-account', 'New login was saved as an append to the old connection');+ assert(JSON.stringify(change.selected_model_refs) === '["model-ref/independent-new-account"]', 'New login selection reused old membership');+ await until(() => calls('apply_compute_save').length === 1, 'new connection apply');+ assert(JSON.stringify(c().management.sources.find(source => source.source_id === 'source/codex/subscription')) === previous, 'Previous connection was changed');+ }),+ scenario('desktop.models.subscription-scan.recommended-login', ['subscription-proxy', 'subscription-login'], 'Scan explains native credential refresh and opens independent sign-in without authorizing or saving', async () => {+ for (const language of ['zh', 'en']) {+ for (const previousScale of [1, 1.5, 2]) {+ await fresh(() => { c().handlers.manage_subscription_login = async () => { await pause(150); return { schema: 'hiroute.subscription-login-result/v1', sessions: [] }; }; });+ const saved = JSON.stringify(c().management);+ localStorage.setItem('hiroute.language', language);+ localStorage.setItem('hiroute.text-scale', String(previousScale));+ c().remount();+ const label = (zh, en) => language === 'zh' ? zh : en;+ await click(label('模型', 'Models')); await click(label('添加模型', 'Add models'));+ const scanLabel = label('扫描本机', 'Scan this device');+ await until(() => all('.add-choice').some(item => item.textContent.includes(scanLabel)), 'scan choice');+ all('.add-choice').find(item => item.textContent.includes(scanLabel)).click();+ const entryLabel = label('连接订阅(推荐)', 'Connect subscription (recommended)');+ await until(() => button(entryLabel), 'recommended independent sign-in entry');+ assert(document.querySelector('.hr-ui').dataset.textScale === '1', 'Scan retained a previous enlarged text preference');+ const note = document.querySelector('.subscription-reuse-note');+ assert(note.textContent.includes(label('依赖 Codex / Claude Code', 'depends on Codex / Claude Code')) && note.textContent.includes(label('自动刷新登录凭据', 'automatically refresh sign-in credentials')), 'Scan does not explain both credential refresh owners');+ assert(!text().includes('自动续期'), 'Paid-subscription renewal copy remains');+ const entry = button(entryLabel);+ entry.scrollIntoView({ block: 'center' }); await pause(40);+ const bounds = note.getBoundingClientRect();+ const buttonBounds = entry.getBoundingClientRect();+ const footer = document.querySelector('.modal-foot').getBoundingClientRect();+ assert(note.scrollWidth <= note.clientWidth + 1 && entry.scrollWidth <= entry.clientWidth + 1, 'Refresh guidance or recommendation overflows horizontally');+ assert(buttonBounds.left >= bounds.left && buttonBounds.right <= bounds.right && buttonBounds.bottom <= footer.top + 1, 'Recommendation is outside the note or obscured by the footer');+ assert(footer.bottom <= innerHeight + 1, 'Fixed scan actions left the viewport');+ for (const copy of note.querySelectorAll('p')) {+ const range = document.createRange(); range.selectNodeContents(copy);+ assert([...range.getClientRects()].every(rect => rect.left >= bounds.left - 1 && rect.right <= bounds.right + 1), 'Refresh guidance text is clipped');+ }+ const closes = calls('close_subscription_check').length;+ await click(entryLabel);+ await until(() => all('[role="dialog"] h2').some(item => item.textContent === label('连接订阅', 'Connect subscription')), 'independent sign-in dialog');+ await until(() => calls('manage_subscription_login').length > 0, 'existing login session listing');+ await until(() => all('.oc-scan-detail .btn-primary').some(item => !item.disabled), 'login session list completed');+ await pause(40);+ assert(text().includes(label('自动刷新登录凭据', 'automatically refresh sign-in credentials')), 'Sign-in copy does not explain automatic credential refresh');+ const intro = document.querySelector('.v3-select-intro');+ const body = intro.closest('.modal-body');+ assert(intro.getBoundingClientRect().top >= body.getBoundingClientRect().top - 1, 'Initial login focus scrolled the credential-refresh explanation out of view');+ assert(calls('close_subscription_check').length === closes + 1, 'Scan check intent was not released');+ assert(calls('manage_subscription_login').every(item => item.payload.request.action === 'list'), 'Opening the recommendation automatically started authorization');+ assert(calls('check_subscription').length === 0 && calls('apply_compute_save').length === 0 && calls('subscription_proxy_apply').length === 0 && JSON.stringify(c().management) === saved, 'Navigation mutated a connection or proxy');+ all('summary').find(item => item.textContent.includes(label('复用本机登录', 'Reuse a local sign-in'))).click(); await pause(40);+ await click(label('扫描本机登录', 'Find local sign-ins'));+ await until(() => button(entryLabel), 'return to fresh device scan');+ }+ }+ }),+ scenario('desktop.models.subscription-proxy.inline-cancel', ['subscription-proxy'], 'Proxy editing stays in the scan and cancelling retains its results and selected subscription', async () => {+ const saved = { config: { revision: 'fixture', policy: { mode: 'manual', url: 'http://proxy.example:8080', no_proxy: 'example.org' } }, applied: true };+ await fresh(() => { c().handlers.subscription_proxy_status = () => structuredClone(saved); });+ await click('设置');+ assert(!text().includes('订阅连接代理') && calls('subscription_proxy_status').length === 0, 'Settings still owns the proxy entry');+ await deviceScan();+ await until(() => button('调整模型'), 'scanned subscription');+ const dialog = document.querySelector('[role="dialog"]');+ const list = document.querySelector('.oc-scan-list');+ await click('设置订阅连接代理');+ await until(() => document.querySelector('[aria-label="订阅代理地址"]'), 'saved manual proxy');+ assert(document.querySelector('[role="dialog"]') === dialog && document.querySelector('.oc-scan-list') === list, 'Proxy entry replaced the scan');+ assert(all('.subscription-proxy-scan-content button').every(item => item.matches(':disabled')), 'Scan actions remain enabled during proxy editing');+ assert(text().includes('全部订阅及订阅检查') && text().includes('正在执行的请求和任务可能中断'), 'Scope or restart impact missing');+ assert(getComputedStyle(document.querySelector('.subscription-proxy-control')).display === 'flex', 'Proxy form layout is missing from the production stylesheet');+ assert(getComputedStyle(document.querySelector('.subscription-proxy-scan-content')).borderTopWidth === '0px', 'Disabled scan inherited an unintended fieldset border');+ const panelBounds = document.querySelector('.subscription-proxy-panel').getBoundingClientRect();+ const dialogBounds = dialog.getBoundingClientRect();+ assert(panelBounds.left >= dialogBounds.left && panelBounds.right <= dialogBounds.right, 'Proxy form overflows the scan dialog');+ for (const label of all('.subscription-proxy-control .field-label')) {+ const range = document.createRange(); range.selectNodeContents(label.firstChild);+ const labelText = range.getBoundingClientRect();+ const control = label.querySelector('input, select').getBoundingClientRect();+ assert(labelText.height <= parseFloat(getComputedStyle(label).lineHeight) * 2, 'Proxy field label wraps into a narrow column');+ assert(control.top >= labelText.bottom && control.left >= panelBounds.left && control.right <= panelBounds.right, 'Proxy field collides with its label or panel edge');+ }+ assert(document.querySelector('[aria-label="订阅代理地址"]').placeholder === 'http://127.0.0.1:端口', 'Proxy placeholder exposes a fixed port');+ setInput(document.querySelector('[aria-label="订阅代理地址"]'), 'http://draft.example:9000');+ await click('取消');+ assert(document.querySelector('.oc-scan-list') === list && !button('调整模型').matches(':disabled'), 'Cancel lost or locked the scan');+ assert(calls('subscription_proxy_apply').length === 0, 'Cancel applied a draft');+ await click('调整模型');+ const detail = document.querySelector('.oc-scan-detail');+ await click('设置订阅连接代理');+ await until(() => document.querySelector('[aria-label="订阅代理地址"]')?.value === saved.config.policy.url, 'discarded draft and saved readback');+ document.querySelector('[role="dialog"]').dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));+ await until(() => !document.querySelector('.subscription-proxy-panel'), 'Escape collapses editor');+ assert(document.querySelector('.oc-scan-detail') === detail && document.querySelector('[role="dialog"]') === dialog, 'Escape lost the selected subscription');+ }),+ scenario('desktop.models.subscription-proxy.read-retry', ['subscription-proxy'], 'An unread proxy policy cannot be overwritten and retry loads the saved mode', async () => {+ let attempts = 0;+ await fresh(() => { c().handlers.subscription_proxy_status = () => {+ if (++attempts === 1) throw new Error('SUBSCRIPTION_PROXY_UNAVAILABLE');+ return { config: { revision: 'fixture', policy: { mode: 'direct' } }, applied: false };+ }; });+ await deviceScan(); await click('设置订阅连接代理');+ await until(() => button('重试读取'), 'read failure');+ assert(button('保存并重启 HiRoute').disabled && !document.querySelector('[aria-label="订阅代理模式"]'), 'Unknown policy can be edited or saved');+ button('保存并重启 HiRoute').click(); await pause(40);+ assert(calls('subscription_proxy_apply').length === 0, 'Read failure overwrote the saved policy');+ await click('重试读取');+ await until(() => document.querySelector('[aria-label="订阅代理模式"]')?.value === 'direct', 'retried saved policy');+ assert(!button('保存并重启 HiRoute').disabled && text().includes('等待应用或服务就绪'), 'Retry did not restore editing or misreported application');+ }),+ scenario('desktop.models.subscription-proxy.save-retry-return', ['subscription-proxy'], 'Save failure retains the draft and a successful restart returns to a fresh scan with saved configuration', async () => {+ let saved = { config: { revision: 'fixture', policy: { mode: 'inherit' } }, applied: true };+ let fail = true;+ await fresh(() => {+ c().handlers.subscription_proxy_status = () => structuredClone(saved);+ c().handlers.subscription_proxy_apply = ({ policy }) => {+ if (fail) throw new Error('SUBSCRIPTION_PROXY_INVALID_OR_UNAVAILABLE');+ saved = { config: { revision: 'next', policy }, applied: true };+ c().remount();+ };+ });+ await deviceScan(); await click('设置订阅连接代理');+ await until(() => document.querySelector('[aria-label="订阅代理模式"]'), 'proxy modes');+ const select = document.querySelector('[aria-label="订阅代理模式"]');+ assert([...select.options].map(item => item.value).join(',') === 'inherit,direct,manual', 'Existing modes changed');+ select.value = 'manual'; select.dispatchEvent(new Event('change', { bubbles: true })); await pause(40);+ setInput(document.querySelector('[aria-label="订阅代理地址"]'), 'http://proxy.example:8080');+ setInput(document.querySelector('[aria-label="订阅代理绕过列表"]'), 'example.org');+ await click('保存并重启 HiRoute');+ await until(() => text().includes('输入已保留'), 'failed save');+ assert(document.querySelector('[aria-label="订阅代理地址"]').value === 'http://proxy.example:8080' && document.querySelector('[aria-label="订阅代理绕过列表"]').value === 'example.org', 'Save failure discarded input');+ assert(!localStorage.getItem('hiroute.subscription-proxy-return'), 'Failed save left a restart hint');+ const scans = calls('compute_subscriptions').length;+ fail = false; await click('保存并重启 HiRoute');+ await until(() => document.querySelector('.oc-scan-list') && !document.querySelector('.subscription-proxy-panel'), 'restart returned to scan');+ assert(calls('compute_subscriptions').length > scans && !localStorage.getItem('hiroute.subscription-proxy-return'), 'Restart reused stale scan or retained navigation hint');+ assert(calls('subscription_proxy_apply').length === 2 && calls('check_subscription').length === 0, 'Save was duplicated or restart automatically checked a subscription');+ assert(JSON.stringify(calls('subscription_proxy_apply')[1].payload.policy) === JSON.stringify(saved.config.policy), 'Saved policy changed');+ await click('设置订阅连接代理');+ await until(() => document.querySelector('[aria-label="订阅代理地址"]')?.value === saved.config.policy.url, 'saved proxy on reopen');+ }),scenario('desktop.models.selection-survives-save-refresh', ['model-connections'], 'Renaming a selected connection does not jump back to the previous save result', async () => {let a; let b; let beforeB; let latestChange;await fresh(() => {@@ -526,13 +698,23 @@ const scenarios = [}assert(calls('save_decision_service').length === 0, 'Discard persisted an edit');}),- scenario('desktop.settings.persisted-scale', ['desktop-presentation'], 'Settings apply and persist all supported text scales through the shell', async () => {+ scenario('desktop.settings.fixed-scale', ['desktop-presentation'], 'Settings omit text size and normalize old enlarged preferences without losing language or appearance', async () => {await fresh(); await click('设置');- for (const [label, value] of [['150%', '1.5'], ['200%', '2'], ['100%', '1']]) {- await click(label);- assert(button(label).getAttribute('aria-pressed') === 'true', 'Scale choice did not become selected');- assert(document.querySelector('.hr-ui').dataset.textScale === value, 'Shell did not apply the selected scale');- assert(localStorage.getItem('hiroute.text-scale') === value, 'Selected scale was not persisted');+ const titleSize = getComputedStyle(all('.main .page-title')[0]).fontSize;+ for (const previousScale of ['1.5', '2']) {+ localStorage.setItem('hiroute.language', 'zh');+ localStorage.setItem('hiroute.theme', 'dark');+ localStorage.setItem('hiroute.text-scale', previousScale);+ c().remount(); await click('设置');+ assert(document.querySelector('.hr-ui').dataset.textScale === '1' && getComputedStyle(all('.main .page-title')[0]).fontSize === titleSize, 'Previous text size is still applied by the real shell');+ assert(localStorage.getItem('hiroute.text-scale') === '1', 'Previous scale was not normalized in storage');+ assert(!text().includes('文字大小') && !['100%', '150%', '200%'].some(label => button(label)), 'Text size controls remain in Settings');+ assert(button('深色').getAttribute('aria-pressed') === 'true', 'Normalizing text changed the appearance preference');+ await click('English'); await click('Light');+ c().remount(); await click('Settings');+ assert(document.querySelector('.hr-ui').lang === 'en' && document.querySelector('.hr-ui').dataset.theme === 'light', 'Language or appearance did not survive remount');+ assert(document.querySelector('.hr-ui').dataset.textScale === '1' && localStorage.getItem('hiroute.text-scale') === '1', 'Remount restored the enlarged scale');+ assert(!text().includes('Text size') && !['100%', '150%', '200%'].some(label => button(label)), 'English Settings still expose text size controls');}}),scenario('desktop.operation.dismiss-observes', ['operation-feedback'], 'Closing feedback leaves the operation observable and never cancels it', async () => {diff --git a/apps/desktop/tests/v3/browser/product-shell.tsx b/apps/desktop/tests/v3/browser/product-shell.tsxindex b0ebf429..7c17a5cd 100644--- a/apps/desktop/tests/v3/browser/product-shell.tsx+++ b/apps/desktop/tests/v3/browser/product-shell.tsx@@ -17,6 +17,7 @@ const control = {clipboard: [] as string[],handlers: {} as Record<string, (payload: Record<string, unknown>) => unknown>,fixtureResponse: (command: string, payload: Record<string, unknown>) => mockProductInvoke(command, payload, 'ready'),+ remount: () => root.render(<DesktopApp key={++generation} />),reset: () => {control.desktop = structuredClone(readyDesktop);control.agents = structuredClone(readyAgents);@@ -26,7 +27,8 @@ const control = {control.handlers = {};localStorage.setItem('hiroute.language', 'zh');localStorage.setItem('hiroute.text-scale', '1');- root.render(<DesktopApp key={++generation} />);+ localStorage.removeItem('hiroute.subscription-proxy-return');+ control.remount();},};Object.assign(window, { productShell: control });diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex db0efe4f..4a99a379 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -42,6 +42,7 @@ export const routingWorkerRequired = ['routing.capabilities.candidate-vs-fixed','routing.publish.qoder-budget-conflict'];export const focusedRequirements = {+ 'subscription-proxy': ['desktop.models.subscription-scan.recommended-login', 'desktop.models.subscription-scan.append-to-login', 'desktop.models.subscription-proxy.inline-cancel', 'desktop.models.subscription-proxy.read-retry', 'desktop.models.subscription-proxy.save-retry-return'],'claude-collaboration': ['claude.collaboration.check-before-save', 'claude.collaboration.retry-preserves-edit', 'claude.collaboration.obsolete-blocker'],'worker-replacement': ['worker.installation.replace', 'worker.installation.latest-edit'],'qoder': ['qoder.collaboration.enable-without-model', 'qoder.collaboration.retry-and-restore', 'qoder.routing.additional-plans', 'qoder.routing.adjust-and-restore', 'agent.configuration.shared-interactions', 'qoder.routing.resume-pending', 'qoder.installation.single-cli', 'routing.publish.qoder-budget-conflict', 'desktop.routing.qoder-budget-checkpoint'],@@ -49,6 +50,11 @@ export const focusedRequirements = {};export const productShellRequired = [+ 'desktop.models.subscription-scan.recommended-login',+ 'desktop.models.subscription-scan.append-to-login',+ 'desktop.models.subscription-proxy.inline-cancel',+ 'desktop.models.subscription-proxy.read-retry',+ 'desktop.models.subscription-proxy.save-retry-return','desktop.models.selection-survives-save-refresh','desktop.models.connection-template-directory-layout','desktop.models.connection-rename',@@ -67,7 +73,7 @@ export const productShellRequired = ['desktop.decisions.save-test-revision','desktop.decisions.route-detour','desktop.decisions.discard-navigation',- 'desktop.settings.persisted-scale',+ 'desktop.settings.fixed-scale','desktop.operation.dismiss-observes','desktop.operation.identity-retry-converges','desktop.operation.repeated-submission',diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex 36af3f90..ba484f0a 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -7,7 +7,8 @@ import { connectPage, evaluate, navigate, waitFor } from './cdp-client.mjs';const port = Number(process.argv[2]);const baseUrl = process.argv[3];const outputRoot = path.resolve(process.argv[4]);-const shellOnly = process.argv[5] === '--shell-only';+const subscriptionProxyOnly = process.argv[5] === '--subscription-proxy-only';+const shellOnly = process.argv[5] === '--shell-only' || subscriptionProxyOnly;const routeSaveOnly = process.argv[5] === '--route-save-only';const workerReplacementOnly = process.argv[5] === '--worker-replacement-only';const claudeCollaborationOnly = process.argv[5] === '--claude-collaboration-only';@@ -86,11 +87,16 @@ try {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)");- const selected = selectScenarios(catalog, { requiredIds: productShellRequired });+ const selected = selectScenarios(catalog, subscriptionProxyOnly+ ? { capability: 'subscription-proxy', requiredIds: focusedRequirements['subscription-proxy'] }+ : { requiredIds: productShellRequired });const results = [];for (const { id } of selected) {+ const viewport = id === 'desktop.models.subscription-scan.recommended-login'+ ? { width: 755, height: 600 } : { width: 1280, height: 900 };+ await client.send('Emulation.setDeviceMetricsOverride', { ...viewport, deviceScaleFactor: 1, mobile: false });const batch = await evaluate(client, `import('/product-shell-scenarios.mjs').then(module => module.runProductShellScenarios(${JSON.stringify({ ids: [id], requiredIds: [id] })}))`);- results.push(...batch.results);+ results.push(...batch.results.map(item => ({ ...item, viewport })));for (const item of batch.results) process.stdout.write(`${item.state}: ${item.id} · ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);}assertScenarioResults(selected, results);diff --git a/apps/desktop/tests/v3/visual/agent-trust.mjs b/apps/desktop/tests/v3/visual/agent-trust.mjsindex 47311c41..0b2aeab1 100644--- a/apps/desktop/tests/v3/visual/agent-trust.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust.mjs@@ -8,8 +8,9 @@ import { fileURLToPath } from 'node:url';const here = path.dirname(fileURLToPath(import.meta.url));const desktopRoot = path.resolve(here, '../../..');const outputRoot = path.resolve(process.argv[2] ?? path.join(desktopRoot, 'test-results/v3-agent-trust'));-const shellOnly = process.argv[3] === '--shell-only';-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 subscriptionProxyOnly = process.argv[3] === '--subscription-proxy-only';+const shellOnly = process.argv[3] === '--shell-only' || subscriptionProxyOnly;+if (process.argv[3] && !['--shell-only', '--subscription-proxy-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';@@ -73,7 +74,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'] : routeOptionsOnly ? ['--route-options-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, ...(subscriptionProxyOnly ? ['--subscription-proxy-only'] : 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/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex 1c09bbff..648b992a 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -39,9 +39,10 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi| Display, prepare and save the selected source | [Safe Desktop projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Provider/model identity remains visible; privileged scan material stays private; source changes invalidate the prepared candidate || Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. || 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. Claude Keychain interaction is limited to an explicit check; discovery reads metadata only. Codex borrowing reads file storage only and rejects a configured non-file store even if stale auth.json remains. |-| 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. |+| 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) | Device scan explains native credential-refresh dependence and opens the existing independent sign-in. 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. || Inspect saved subscription mode and repair sign-in | [V3 query](../../crates/application/src/compute_management/query_v3.rs), [mode and repair copy](../../apps/desktop/src/features/models/subscription-copy.ts) | Mode derives from the committed source selection and survives missing credentials. Desktop consumes V3; published V2 queries retain their strict response shape. Existing release-version matching still applies; an external service without V3 requires an update. |+| Configure a subscription connection proxy | [Device scan](../../apps/desktop/src/product/ModelManagementPage.tsx), [inline proxy editor](../../apps/desktop/src/features/SubscriptionProxySettings.tsx), [native apply](../../apps/desktop/src-tauri/src/bridge/subscription_proxy.rs) | Scan retains results while editing; cancel restores its actions, and explicit save/restart returns to a fresh scan. Settings has no proxy entry; host policy remains shared by all subscriptions. || 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 |