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: receive subscription callbacks and finish saved checks (#161)
澄潭bd641d69fbb7
diff --git a/apps/desktop/src/features/subscriptions/README.md b/apps/desktop/src/features/subscriptions/README.mdindex 153ca33b..c702cfb0 100644--- a/apps/desktop/src/features/subscriptions/README.md+++ b/apps/desktop/src/features/subscriptions/README.md@@ -6,11 +6,19 @@ WebView never receives credential files, tokens or provider error bodies. Browseonly in the current interaction. Manual callback text is cleared on submission and entersthe native `submit_subscription_login_callback` command, which registers the exact pendingsession's protected input reference before ordinary Local Control submission.+The pinned CPA receives normal browser callbacks on temporary loopback listeners.+The existing optional `reason_code` identifies manual fallback when that listener+is unavailable: show guidance before an explicit browser-open action. A received+callback alone never establishes login; the existing status observer must confirm+authorization. The manual completion form remains available in both modes.List/status recover server-owned sessions after reopening. Closing an interaction cancelsthe pending sessions it started, including a start response that arrives after closing.An authorized session remains a candidate: `ModelManagementPage.tsx` opens the existing-check → model selection → Preview/Apply save flow. No sign-in action publishes a route.+check → model selection → Preview/Apply save flow. Selected subscription details use+the subscription title and hide device-discovery controls, including Hermes profile+scanning; returning to the scan list restores those controls. No sign-in action+publishes a route.The native reuse option opens the existing device scan. Background token synchronizationdoes not grant refresh authority: native clients retain their refresh tokens. Copy mustdiff --git a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsxindex e138bf6f..f8ec6de5 100644--- a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx+++ b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx@@ -111,8 +111,10 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,if (session.status === 'pending') pendingOwned.current.add(session.login_ref);}merge(result.sessions);- const url = result.sessions.find(session => session.status === 'pending')?.authorization_url;- if (url) await invoke('open_external_url', { url });+ const session = result.sessions.find(session => session.status === 'pending');+ if (session?.authorization_url && session.reason_code !== 'SUBSCRIPTION_LOGIN_MANUAL_CALLBACK') {+ await invoke('open_external_url', { url: session.authorization_url });+ }});}@@ -136,17 +138,17 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,return <div className="oc-scan-detail" key={provider}><div className="oc-status-row"><BrandIcon kind={provider === 'codex' ? 'codex' : 'claude-code'} label={name} /><div className="row-main"><strong>{name}</strong><p>{text('独立登录 · 推荐', 'Independent sign-in · Recommended')}</p></div><button type="button" className="btn btn-primary" disabled={!trustedAuthority || Boolean(busy) || pending} onClick={() => void start(provider)}>{pending ? text('等待登录', 'Waiting for sign-in') : text('登录', 'Sign in')}</button></div>{accounts.map(session => <div key={session.login_ref} className="oc-scan-detail">- <p role="status">{session.status === 'authorized' ? text('已登录,可检查并选择模型', 'Signed in. Check and choose models.') : session.status === 'pending' ? text('在浏览器中授权后,粘贴返回地址或授权码以完成登录。', 'After authorizing in your browser, paste the return URL or authorization code to finish signing in.') : session.status === 'expired' ? text('登录已过期,请重新登录', 'Sign-in expired. Start again.') : text('登录未完成,请重试', 'Sign-in did not complete. Try again.')}</p>+ <p role="status">{session.status === 'authorized' ? text('已登录,可检查并选择模型', 'Signed in. Check and choose models.') : session.status === 'pending' ? session.reason_code === 'SUBSCRIPTION_LOGIN_MANUAL_CALLBACK' ? text('无法自动接收浏览器授权。请先结束本机其他登录,再打开登录页面;授权后复制完整返回地址,使用「手动完成授权」。', 'Automatic callback reception is unavailable. Finish any other local sign-in before opening the sign-in page, then copy the full return URL and use “Complete authorization manually”.') : text('请在浏览器中完成授权,HiRoute 会自动接收结果。若未自动完成,可手动粘贴完整返回地址。', 'Authorize in your browser; HiRoute will receive the result automatically. If it does not finish, you can paste the full return URL manually.') : session.status === 'expired' ? text('登录已过期,请重新登录', 'Sign-in expired. Start again.') : text('登录未完成,请重试', 'Sign-in did not complete. Try again.')}</p><div className="task-actions">{session.status === 'pending' && <>{session.authorization_url && <button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, () => invoke('open_external_url', { url: session.authorization_url }))}>{text('打开登录页面', 'Open sign-in page')}</button>}<button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, async () => merge((await manage({ action: 'cancel', login_ref: session.login_ref })).sessions))}>{text('取消登录', 'Cancel sign-in')}</button>- <button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => { setCallback(''); setCallbackLogin(session.login_ref); }}>{text('完成授权', 'Finish authorization')}</button>+ <button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => { setCallback(''); setCallbackLogin(session.login_ref); }}>{text('手动完成授权', 'Complete authorization manually')}</button></>}{session.status === 'authorized' && session.candidate && <button type="button" className="btn btn-primary" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, () => onConnect(session.candidate!))}>{text('检查并选择模型', 'Check and choose models')}</button>}{session.status !== 'pending' && <button type="button" className="btn" disabled={!trustedAuthority || Boolean(busy)} onClick={() => setForgetLogin(session.login_ref)}>{text('移除登录', 'Remove sign-in')}</button>}</div>- {callbackLogin === session.login_ref && session.status === 'pending' && <form autoComplete="off" onSubmit={event => { event.preventDefault(); void submitCallback(session); }}><label className="field"><span>{text('粘贴授权完成页面的回调地址或授权码', 'Paste the callback URL or authorization code from the completed sign-in')}</span><SecretTransportWarning language={language} /><input type="password" autoComplete="off" spellCheck={false} value={callback} onChange={event => setCallback(event.currentTarget.value)} /></label><p className="oc-meta">{text('仅用于完成此次登录,不保存在页面中。', 'Used only to complete this sign-in; it is not saved in the page.')}</p><button className="btn" type="submit" disabled={!trustedAuthority || Boolean(busy) || !callback.trim()}>{text('完成授权', 'Finish authorization')}</button></form>}+ {callbackLogin === session.login_ref && session.status === 'pending' && <form autoComplete="off" onSubmit={event => { event.preventDefault(); void submitCallback(session); }}><label className="field"><span>{text('粘贴浏览器地址栏中的完整回调地址或授权码', 'Paste the full callback URL from your browser address bar, or the authorization code')}</span><SecretTransportWarning language={language} /><input type="password" autoComplete="off" spellCheck={false} value={callback} onChange={event => setCallback(event.currentTarget.value)} /></label><p className="oc-meta">{text('返回页面无法打开时,也可复制地址栏。仅用于此次登录,请勿分享。', 'You can copy the address bar even if the return page cannot load. Used only for this sign-in; do not share it.')}</p><button className="btn" type="submit" disabled={!trustedAuthority || Boolean(busy) || !callback.trim()}>{text('提交授权', 'Submit authorization')}</button></form>}{forgetLogin === session.login_ref && <div className="callout warn"><p>{text('移除此登录会停止相关订阅连接。保留模型和路由配置,之后可重新登录。', 'Removing this sign-in stops its subscription connection. Model and routing settings remain available for a later sign-in.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={() => void act(session.login_ref, async () => { merge((await manage({ action: 'forget', login_ref: session.login_ref })).sessions); if (alive.current) setForgetLogin(null); })}>{text('确认移除', 'Remove sign-in')}</button><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={() => setForgetLogin(null)}>{text('保留', 'Keep')}</button></div>}</div>)}</div>;diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsxindex a24de58d..9bc65420 100644--- a/apps/desktop/src/product/ModelManagementPage.tsx+++ b/apps/desktop/src/product/ModelManagementPage.tsx@@ -1148,11 +1148,14 @@ export function ModelManagementPage({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}>+ >{({ panel, actions, saving }) => <Dialog open={adding && addStage === 'scan'}+ title={selectedSubscription ? (language === 'zh' ? '连接订阅' : 'Connect subscription') : (language === 'zh' ? '扫描本机' : 'Scan this device')}+ closeLabel={editingSubscriptionProxy ? (language === 'zh' ? '取消代理设置' : 'Cancel proxy settings') : subscriptionSaving || discoverySaving ? (language === 'zh' ? '正在保存' : 'Saving') : selectedSubscription ? (language === 'zh' ? '关闭订阅连接' : 'Close subscription connection') : (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}>- {!selectedDiscovery && <Disclosure label={language === 'zh' ? '扫描 Hermes 配置' : 'Scan a Hermes profile'} language={language}>+ {!selectedDiscovery && !selectedSubscription && <Disclosure label={language === 'zh' ? '扫描 Hermes 配置' : 'Scan a Hermes profile'} language={language}><form className="agent-form" data-hermes-source-scope onSubmit={event => {event.preventDefault();if (!hermesScanRoot.trim().startsWith('/') || scanWorking) return;diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjsindex 56b0c913..edb4f80e 100644--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs@@ -79,6 +79,61 @@ const scenarios = [assert(document.querySelector('.plan-identity-fields input').value === draftName, 'Rival revision discarded the local draft');assert(calls('preview_plan_editor').length === 1, 'Stale publication was retried automatically');}),+ scenario('desktop.models.subscription-login.callback-modes', ['subscription-proxy', 'subscription-login'], 'Automatic callback opens the browser; manual fallback explains the conflict before opening and keeps callback text protected', async () => {+ for (const language of (window.cpaCallbackLanguages ?? ['zh', 'en'])) {+ for (const provider of ['codex', 'claude']) {+ for (const manual of [false, true]) {+ let session;+ await fresh(() => {+ session = { provider, login_ref: `login/fixture-${provider}`, status: 'pending',+ authorization_url: 'https://example.invalid/oauth/authorize',+ ...(manual ? { reason_code: 'SUBSCRIPTION_LOGIN_MANUAL_CALLBACK' } : {}) };+ c().handlers.manage_subscription_login = ({ request }) => ({ schema: 'hiroute.subscription-login-result/v1',+ sessions: request.action === 'list' ? [] : [{ ...session, ...(request.action === 'cancel' ? { status: 'cancelled' } : {}) }] });+ c().handlers.open_external_url = () => undefined;+ c().handlers.submit_subscription_login_callback = () => {+ session = { ...session, status: 'authorized', reason_code: undefined,+ candidate: { candidate_ref: 'candidate/cpa/fixture', candidate_revision: 1 } };+ return { schema: 'hiroute.subscription-login-result/v1', sessions: [session] };+ };+ });+ localStorage.setItem('hiroute.language', language); c().remount();+ const label = (zh, en) => language === 'zh' ? zh : en;+ await click(label('模型', 'Models')); await click(label('添加模型', 'Add models'));+ await until(() => all('.add-choice').some(item => item.textContent.includes(label('连接订阅', 'Connect subscription'))), 'subscription sign-in entry');+ all('.add-choice').find(item => item.textContent.includes(label('连接订阅', 'Connect subscription'))).click();+ const name = provider === 'codex' ? 'Codex' : 'Claude Code';+ await until(() => all('.oc-status-row').some(row => row.querySelector('strong')?.textContent === name && !row.querySelector('button')?.disabled), 'ready provider sign-in');+ all('.oc-status-row').find(row => row.querySelector('strong')?.textContent === name).querySelector('button').click();+ await until(() => button(label('手动完成授权', 'Complete authorization manually')), 'pending callback mode');+ assert(calls('open_external_url').length === (manual ? 0 : 1), 'Manual conflict opened a browser before guidance or automatic mode did not open it');+ assert(text().includes(manual ? label('无法自动接收浏览器授权', 'Automatic callback reception is unavailable') : label('HiRoute 会自动接收结果', 'HiRoute will receive the result automatically')), 'Callback mode guidance missing');+ if (manual) { await click(label('打开登录页面', 'Open sign-in page')); assert(calls('open_external_url').length === 1, 'Explicit manual browser action did not dispatch'); }+ await click(label('手动完成授权', 'Complete authorization manually'));+ await until(() => all('input[type="password"]').length === 1, 'protected manual callback form');+ const dialog = all('[role="dialog"]')[0];+ const input = all('input[type="password"]')[0];+ assert(dialog.scrollWidth <= dialog.clientWidth + 1, 'Sign-in dialog overflows horizontally');+ assert(input.getBoundingClientRect().width > 150, 'Callback field is squeezed');+ assert(text().includes(label('返回页面无法打开时', 'even if the return page cannot load')), 'Manual copy lacks the unavailable-page instruction');+ setInput(input, 'synthetic-callback-material');+ await click(label('提交授权', 'Submit authorization'));+ await until(() => button(label('检查并选择模型', 'Check and choose models')), 'confirmed authorized state');+ assert(calls('submit_subscription_login_callback').length === 1 && calls('submit_subscription_login_callback')[0].payload.callback === 'synthetic-callback-material', 'Manual material did not enter the native protected command exactly once');+ assert(!all('input[type="password"]').length, 'Submitted callback form retained its value');+ assert(!JSON.stringify(calls('manage_subscription_login')).includes('synthetic-callback-material'), 'Callback material entered ordinary control requests');+ assert(!calls('check_subscription').length && !calls('apply_compute_save').length, 'Login automatically checked or saved a connection');+ // Leave the empty fallback form visible for production-style screenshots.+ if (provider === 'claude' && manual) {+ session = { ...session, login_ref: `login/fixture-${provider}-next`, status: 'pending', reason_code: 'SUBSCRIPTION_LOGIN_MANUAL_CALLBACK', candidate: undefined };+ all('.oc-status-row').find(row => row.querySelector('strong')?.textContent === name).querySelector('button').click();+ await until(() => button(label('手动完成授权', 'Complete authorization manually')), 'fallback form after status observation');+ await click(label('手动完成授权', 'Complete authorization manually'));+ }+ }+ }+ }+ }),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(() => {@@ -99,7 +154,9 @@ const scenarios = [await click('模型'); await click('向此接入添加模型');await until(() => button('返回') && text().includes('Codex 本机订阅'), 'append subscription detail');await click('返回'); await click('连接订阅(推荐)');- await click('检查并选择模型'); await click('检查订阅');+ await click('检查并选择模型');+ assert(all('[role="dialog"] h2').some(item => item.textContent === '连接订阅') && !document.querySelector('[data-hermes-source-scope]'), 'Independent subscription check leaked the device-scan title or Hermes controls');+ await click('检查订阅');await until(() => button('保存接入'), 'new account checked');await click('保存接入');await until(() => calls('preview_compute_save').length || document.querySelector('[data-error-code]'), 'save outcome');@@ -167,6 +224,7 @@ const scenarios = [assert(!text().includes('订阅连接代理') && calls('subscription_proxy_status').length === 0, 'Settings still owns the proxy entry');await deviceScan();await until(() => button('调整模型'), 'scanned subscription');+ assert(document.querySelector('[data-hermes-source-scope]'), 'Device scan lost its optional Hermes profile entry');const dialog = document.querySelector('[role="dialog"]');const list = document.querySelector('.oc-scan-list');await click('设置订阅连接代理');@@ -193,11 +251,15 @@ const scenarios = [assert(calls('subscription_proxy_apply').length === 0, 'Cancel applied a draft');await click('调整模型');const detail = document.querySelector('.oc-scan-detail');+ assert(all('[role="dialog"] h2').some(item => item.textContent === '连接订阅') && !document.querySelector('[data-hermes-source-scope]'), 'Selected subscription leaked device-scan controls');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');+ await click('返回');+ await until(() => document.querySelector('.oc-scan-list'), 'returned to device scan');+ assert(all('[role="dialog"] h2').some(item => item.textContent === '扫描本机') && document.querySelector('[data-hermes-source-scope]'), 'Returning from a subscription did not restore the device-scan context');}),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;diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex 90db07f7..6a988905 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -51,7 +51,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'],+ 'subscription-proxy': ['desktop.models.subscription-login.callback-modes', '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'],@@ -67,6 +67,7 @@ export const productShellRequired = ['desktop.presentation.control-layout','desktop.routing.two-context-conflict','desktop.routing.additional-budget-consumers',+ 'desktop.models.subscription-login.callback-modes','desktop.models.subscription-scan.recommended-login','desktop.models.subscription-scan.append-to-login','desktop.models.subscription-proxy.inline-cancel',diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex 0f8470bd..2f99b183 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -135,7 +135,8 @@ try {for (const { id } of selected) {const viewport = ['desktop.models.subscription-scan.recommended-login','desktop.models.view-switch', 'desktop.presentation.control-layout',- 'desktop.routing.additional-budget-consumers'].includes(id)+ 'desktop.routing.additional-budget-consumers',+ 'desktop.models.subscription-login.callback-modes'].includes(id)? { 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] })}))`);diff --git a/crates/cpa-bridge/src/lib.rs b/crates/cpa-bridge/src/lib.rsindex ffe6f94f..4d7c0f2e 100644--- a/crates/cpa-bridge/src/lib.rs+++ b/crates/cpa-bridge/src/lib.rs@@ -64,7 +64,7 @@ pub use subscription::{/// Stock CPA release whose CLI/config/management contract this implementation was grounded on.pub const STOCK_CPA_CONTRACT_VERSION: &str = "7.2.140";/// Exact managed binary: upstream protocol contract plus the private parent-pipe bootstrap.-pub const MANAGED_CPA_ARTIFACT_VERSION: &str = "8.0.4-hiroute.4";+pub const MANAGED_CPA_ARTIFACT_VERSION: &str = "8.0.4-hiroute.5";/// The management PATCH synchronously refreshes upstream models before local pin checks./// Its whole-flow budget must leave room beyond CPA's five-second upstream deadline.pub const MANAGED_CPA_CONTROL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);diff --git a/crates/cpa-bridge/src/managed_sessions.rs b/crates/cpa-bridge/src/managed_sessions.rsindex d3f9d497..de217fdf 100644--- a/crates/cpa-bridge/src/managed_sessions.rs+++ b/crates/cpa-bridge/src/managed_sessions.rs@@ -35,6 +35,7 @@ pub struct CpaLoginSession {pub kind: CpaAccountKind,pub state: CpaLoginState,pub account_ref: Option<String>,+ pub manual_callback_required: bool,}impl CpaLoginSession {@@ -67,6 +68,7 @@ impl LoginRecord {kind: self.kind,state: self.state,account_ref: self.account_ref.clone(),+ manual_callback_required: false,}}}@@ -74,6 +76,16 @@ impl LoginRecord {struct Session {record: LoginRecord,runtime: Arc<ManagedCpaRuntime>,+ manual_callback_required: bool,+}++impl Session {+ fn safe(&self) -> CpaLoginSession {+ let mut safe = self.record.safe();+ safe.manual_callback_required =+ safe.state == CpaLoginState::Pending && self.manual_callback_required;+ safe+ }}pub(crate) struct ManagedLoginRegistry {@@ -161,7 +173,11 @@ impl ManagedLoginRegistry {return Err(CpaLifecycleError::OwnerState);}let runtime = self.make_runtime(templates, &record)?;- let mut session = Session { record, runtime };+ let mut session = Session {+ record,+ runtime,+ manual_callback_required: false,+ };if session.record.state == CpaLoginState::Pending {// Stop only an authenticated existing owner. Recovery cannot start a new// refresh writer before saved management has granted execution.@@ -249,14 +265,26 @@ impl ManagedLoginRegistry {let _ = runtime.shutdown();record.state = CpaLoginState::Failed;self.save(&record)?;- sessions.insert(id, Session { record, runtime });+ sessions.insert(+ id,+ Session {+ record,+ runtime,+ manual_callback_required: false,+ },+ );return Err(error);}};record.oauth_state = Some(login.state);self.save(&record)?;- let safe = record.safe();- sessions.insert(id, Session { record, runtime });+ let session = Session {+ record,+ runtime,+ manual_callback_required: login.manual_callback_required,+ };+ let safe = session.safe();+ sessions.insert(id, session);Ok((safe, login.authorization_url))}@@ -265,7 +293,7 @@ impl ManagedLoginRegistry {.lock().values().filter(|s| s.record.kind == kind)- .map(|s| s.record.safe())+ .map(|s| s.safe()).collect()}@@ -275,11 +303,11 @@ impl ManagedLoginRegistry {.get_mut(id).ok_or(CpaLifecycleError::InvalidSourceManagement)?;if session.record.state != CpaLoginState::Pending {- return Ok(session.record.safe());+ return Ok(session.safe());}if now()? >= session.record.expires_at {self.stop_session(session, CpaLoginState::Expired)?;- return Ok(session.record.safe());+ return Ok(session.safe());}let oauth_state = session.record@@ -306,7 +334,7 @@ impl ManagedLoginRegistry {}crate::CpaOAuthStatus::Failed => self.stop_session(session, CpaLoginState::Failed)?,}- Ok(session.record.safe())+ Ok(session.safe())}/// Daemon-owned housekeeping continues even when the login client has disconnected.@@ -364,7 +392,7 @@ impl ManagedLoginRegistry {CpaLoginState::Cancelled},)?;- Ok(session.record.safe())+ Ok(session.safe())}pub(crate) fn for_candidate(&self, candidate: &str) -> Option<Arc<ManagedCpaRuntime>> {@@ -373,13 +401,13 @@ impl ManagedLoginRegistry {.values().find(|session| {session.record.state == CpaLoginState::Authorized- && session.record.safe().candidate_ref() == candidate+ && session.safe().candidate_ref() == candidate}).map(|session| session.runtime.clone())}pub(crate) fn session(&self, id: &str) -> Option<CpaLoginSession> {- self.sessions.lock().get(id).map(|s| s.record.safe())+ self.sessions.lock().get(id).map(|s| s.safe())}pub(crate) fn all_runtimes(&self) -> Vec<Arc<ManagedCpaRuntime>> {diff --git a/crates/cpa-bridge/src/managed_sessions/cpa_oauth_fixture.py b/crates/cpa-bridge/src/managed_sessions/cpa_oauth_fixture.pyindex b4a60426..62fd8310 100644--- a/crates/cpa-bridge/src/managed_sessions/cpa_oauth_fixture.py+++ b/crates/cpa-bridge/src/managed_sessions/cpa_oauth_fixture.py@@ -114,11 +114,12 @@ class Handler(http.server.BaseHTTPRequestHandler):if not self.authorized(secret):returnif parsed.path == '/v8/management/oauth/auth-url':- assert query.get('is_webui') == ['false']+ assert query.get('is_webui') == ['true']provider = query['provider'][0]assert provider in ('codex', 'claude')host = 'auth.openai.com' if provider == 'codex' else 'claude.ai'return self.send({'status': 'ok', 'state': state,+ 'hiroute_callback_mode': 'manual' if (controls / 'manual-callback').exists() else 'automatic','url': 'https://' + host + '/oauth/authorize?state=' + state+ '&code_challenge_method=S256'},version=None if (controls / 'missing-auth-url-version').exists()diff --git a/crates/cpa-bridge/src/managed_sessions/tests.rs b/crates/cpa-bridge/src/managed_sessions/tests.rsindex c378ab2e..b1d6bf15 100644--- a/crates/cpa-bridge/src/managed_sessions/tests.rs+++ b/crates/cpa-bridge/src/managed_sessions/tests.rs@@ -124,6 +124,39 @@ impl Fixture {}}+#[test]+fn manual_callback_fallback_survives_listing_and_clears_after_authorization() {+ let fixture = Fixture::new();+ fs::write(fixture.root.path().join("manual-callback"), b"").unwrap();+ let registry = fixture.registry();+ let (session, url) = registry+ .start(&fixture.templates, CpaAccountKind::Codex)+ .unwrap();+ assert!(session.manual_callback_required);+ assert!(registry.list(CpaAccountKind::Codex)[0].manual_callback_required);+ assert!(+ registry+ .status(&session.login_ref)+ .unwrap()+ .manual_callback_required+ );+ assert!(matches!(+ registry.start(&fixture.templates, CpaAccountKind::Codex),+ Err(CpaLifecycleError::AlreadyOwned)+ ));+ fixture.callback(®istry, &session, &url);+ let authorized = registry.status(&session.login_ref).unwrap();+ assert_eq!(authorized.state, CpaLoginState::Authorized);+ assert!(!authorized.manual_callback_required);+ // A retained account does not prevent the next account from signing in.+ let (next, _) = registry+ .start(&fixture.templates, CpaAccountKind::Codex)+ .unwrap();+ assert_ne!(next.login_ref, session.login_ref);+ assert_eq!(registry.list(CpaAccountKind::Codex).len(), 2);+ registry.cancel(&next.login_ref, false).unwrap();+}+#[test]fn callback_version_mismatch_fails_closed_and_never_resubmits_the_code() {let fixture = Fixture::new();diff --git a/crates/cpa-bridge/src/runtime/oauth.rs b/crates/cpa-bridge/src/runtime/oauth.rsindex 006ef444..b63f9f58 100644--- a/crates/cpa-bridge/src/runtime/oauth.rs+++ b/crates/cpa-bridge/src/runtime/oauth.rs@@ -15,6 +15,7 @@ use super::{ManagedCpaRuntime, RuntimeInner};pub struct CpaOAuthLogin {pub authorization_url: String,pub state: String,+ pub manual_callback_required: bool,}impl std::fmt::Debug for CpaOAuthLogin {@@ -195,10 +196,10 @@ impl ManagedCpaRuntime {{return Err(CpaLifecycleError::InvalidOAuthSession);}- // Stock CPA's web UI forwarder binds all interfaces. The protected HiRoute callback- // input is used instead; this request must never opt into that forwarder.+ // The pinned adapter receives browser callbacks only on loopback. If a+ // callback port is unavailable it keeps this session for protected manual input.let path = format!(- "/v8/management/oauth/auth-url?provider={}&is_webui=false",+ "/v8/management/oauth/auth-url?provider={}&is_webui=true",kind.stock_provider());let value = self.oauth_request_locked(@@ -495,6 +496,11 @@ fn parse_login(kind: CpaAccountKind, value: &Value) -> Result<CpaOAuthLogin, CpaOk(CpaOAuthLogin {authorization_url: raw_url.to_owned(),state: state.to_owned(),+ manual_callback_required: match value.get("hiroute_callback_mode").and_then(Value::as_str) {+ Some("automatic") => false,+ Some("manual") => true,+ _ => return Err(invalid()),+ },})}diff --git a/crates/cpa-bridge/src/runtime/oauth/tests.rs b/crates/cpa-bridge/src/runtime/oauth/tests.rsindex e2c78cfd..9ff876ef 100644--- a/crates/cpa-bridge/src/runtime/oauth/tests.rs+++ b/crates/cpa-bridge/src/runtime/oauth/tests.rs@@ -8,6 +8,7 @@ fn login(kind: CpaAccountKind) -> Value {serde_json::json!({"status": "ok","state": "fixture_state",+ "hiroute_callback_mode": "automatic","url": format!("https://{host}/oauth/authorize?state=fixture_state&code_challenge_method=S256"),// Even if upstream adds sensitive metadata, the public DTO is an explicit allowlist."refresh_token": "must-not-be-returned",@@ -19,6 +20,7 @@ fn oauth_login_projection_returns_only_bound_provider_url_and_state() {for kind in [CpaAccountKind::Codex, CpaAccountKind::Claude] {let parsed = parse_login(kind, &login(kind)).unwrap();assert_eq!(parsed.state, "fixture_state");+ assert!(!parsed.manual_callback_required);assert!(!format!("{parsed:?}").contains("fixture_state"));assert!(!parsed.authorization_url.contains("must-not-be-returned"));let other = match kind {@@ -29,6 +31,21 @@ fn oauth_login_projection_returns_only_bound_provider_url_and_state() {}}+#[test]+fn oauth_callback_mode_is_explicit_and_closed() {+ let mut value = login(CpaAccountKind::Codex);+ value["hiroute_callback_mode"] = "manual".into();+ assert!(+ parse_login(CpaAccountKind::Codex, &value)+ .unwrap()+ .manual_callback_required+ );+ for invalid in [Value::Null, true.into(), "unknown".into()] {+ value["hiroute_callback_mode"] = invalid;+ assert!(parse_login(CpaAccountKind::Codex, &value).is_err());+ }+}+#[test]fn oauth_login_rejects_foreign_hosts_duplicate_state_and_missing_pkce() {for url in [diff --git a/crates/daemon/src/control/runtime/subscriptions/login.rs b/crates/daemon/src/control/runtime/subscriptions/login.rsindex e0cedf87..6c2171f4 100644--- a/crates/daemon/src/control/runtime/subscriptions/login.rs+++ b/crates/daemon/src/control/runtime/subscriptions/login.rs@@ -295,7 +295,9 @@ impl LocalControlAdapter {callback_input_candidate,account_ref: session.account_ref,candidate,- reason_code: None,+ reason_code: session+ .manual_callback_required+ .then(|| "SUBSCRIPTION_LOGIN_MANUAL_CALLBACK".to_owned()),}}).collect();diff --git a/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs b/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rsindex 81762ded..8cc151db 100644--- a/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs+++ b/crates/daemon/src/control/runtime/subscriptions/login_admission_tests.rs@@ -382,6 +382,52 @@ fn isolated(name: &str) -> bool {))}+#[test]+fn manual_callback_reason_survives_public_list_and_status() {+ if isolated("manual_callback_reason_survives_public_list_and_status") {+ return;+ }+ let fixture = Fixture::new();+ fs::write(fixture.root.path().join("manual-callback"), b"").unwrap();+ for provider in [+ SubscriptionLoginProviderV1::Codex,+ SubscriptionLoginProviderV1::Claude,+ ] {+ let started = fixture+ .adapter()+ .manage_subscription_login(ComputeSubscriptionLoginRequestV1::Start { provider })+ .unwrap();+ let session = &started.sessions[0];+ assert_eq!(+ session.reason_code.as_deref(),+ Some("SUBSCRIPTION_LOGIN_MANUAL_CALLBACK")+ );+ for request in [+ ComputeSubscriptionLoginRequestV1::List { provider },+ ComputeSubscriptionLoginRequestV1::Status {+ login_ref: session.login_ref.clone(),+ },+ ] {+ let result = fixture+ .adapter()+ .manage_subscription_login(request)+ .unwrap();+ assert_eq!(result.sessions[0].reason_code, session.reason_code);+ assert!(result.sessions[0].authorization_url.is_none());+ assert!(result.sessions[0].callback_input_candidate.is_some());+ assert!(result.sessions[0].candidate.is_none());+ }+ let cancelled = fixture+ .adapter()+ .manage_subscription_login(ComputeSubscriptionLoginRequestV1::Cancel {+ login_ref: session.login_ref.clone(),+ })+ .unwrap();+ assert!(cancelled.sessions[0].reason_code.is_none());+ }+ assert!(fixture.snapshot().sources.is_empty());+}+#[test]fn unsaved_prepared_save_cannot_resurrect_forgotten_login() {if isolated("unsaved_prepared_save_cannot_resurrect_forgotten_login") {diff --git a/crates/daemon/src/control/runtime/subscriptions/source.rs b/crates/daemon/src/control/runtime/subscriptions/source.rsindex f3f0a933..3ad5ef50 100644--- a/crates/daemon/src/control/runtime/subscriptions/source.rs+++ b/crates/daemon/src/control/runtime/subscriptions/source.rs@@ -234,6 +234,7 @@ mod tests {kind: CpaAccountKind::Claude,state: CpaLoginState::Authorized,account_ref: Some("account/cpa/opaque".into()),+ manual_callback_required: false,};let candidate_ref = session.candidate_ref();let source = SubscriptionSource::managed(session).unwrap();@@ -262,6 +263,7 @@ mod tests {kind: CpaAccountKind::Codex,state,account_ref: Some("account/cpa/opaque".into()),+ manual_callback_required: false,};assert!(SubscriptionSource::managed(session).is_err());}diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rsindex 3619bef2..3e835ebc 100644--- a/crates/daemon/tests/subscription_management_product.rs+++ b/crates/daemon/tests/subscription_management_product.rs@@ -37,7 +37,7 @@ import reimport sysimport urllib.parse-VERSION = "8.0.4-hiroute.4"+VERSION = "8.0.4-hiroute.5"MANAGED_NAME = "hiroute-managed-codex.json"MODEL_ID = "gpt-5.3-codex-spark"ADDED_MODEL_ID = "gpt-5.5"diff --git a/crates/daemon/tests/support/cpa_upstream.py b/crates/daemon/tests/support/cpa_upstream.pyindex f66c60c8..81219ac7 100644--- a/crates/daemon/tests/support/cpa_upstream.py+++ b/crates/daemon/tests/support/cpa_upstream.py@@ -13,7 +13,7 @@ import threadingimport timefrom urllib.parse import parse_qs, urlparse-VERSION = '8.0.4-hiroute.4'+VERSION = '8.0.4-hiroute.5'controls = Path(__file__).resolve().parentmodel_override = controls / 'model-id'MODEL = (model_override.read_text().strip()diff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.pyindex fb44d5c7..29ddee0a 100644--- a/crates/daemon/tests/support/standalone_headless_product.py+++ b/crates/daemon/tests/support/standalone_headless_product.py@@ -377,7 +377,7 @@ for line in sys.stdin:'--version', '0.1.0-headless-product', '--revision', self.sha,'--hiroute', str(candidate_hiroute),'--hirouted', str(candidate_hirouted),- '--cpa-binary', str(cpa), '--cpa-version', '8.0.4-hiroute.4',+ '--cpa-binary', str(cpa), '--cpa-version', '8.0.4-hiroute.5','--cpa-license', str(license_path),'--notices', str(package_source / 'notices'), '--console-assets', str(staged_console),'--output', str(self.package),diff --git a/crates/product-session/src/session/subscription.rs b/crates/product-session/src/session/subscription.rsindex efaa0af2..83231111 100644--- a/crates/product-session/src/session/subscription.rs+++ b/crates/product-session/src/session/subscription.rs@@ -194,11 +194,9 @@ impl Session {let result = self.subscription_result_for_operation(&operation.operation_id).await?;- if matches!(- result.status,- ComputeSubscriptionCheckStatusV2::Verified- | ComputeSubscriptionCheckStatusV2::Retained- ) {+ // Retained access belongs to a completed save, so it must not+ // reserve the current interaction or block another provider.+ if result.status == ComputeSubscriptionCheckStatusV2::Verified {return Err("SUBSCRIPTION_CHECK_ACTIVE".into());}}@@ -502,6 +500,7 @@ impl Session {| ComputeSubscriptionCheckStatusV2::Unavailable| ComputeSubscriptionCheckStatusV2::Failed| ComputeSubscriptionCheckStatusV2::Released+ | ComputeSubscriptionCheckStatusV2::Retained) {return Ok(());}diff --git a/crates/product-session/src/session/subscription/completion_tests.rs b/crates/product-session/src/session/subscription/completion_tests.rsindex 3da5f12a..e5e58b33 100644--- a/crates/product-session/src/session/subscription/completion_tests.rs+++ b/crates/product-session/src/session/subscription/completion_tests.rs@@ -25,6 +25,11 @@ impl HostAuthority for CompletionAuthority {revisions: &RevisionSetV1,operation: &'static str,) -> Result<Zeroizing<String>, String> {+ if operation == APPLY_SUBSCRIPTION_CHECK_OPERATION_V2 {+ assert_eq!(revisions.target, 2);+ self.0.fetch_add(1, Ordering::SeqCst);+ return Ok(Zeroizing::new("next-check-grant".into()));+ }let validation: ComputeValidationRefV2 =serde_json::from_value(result(false)["validation"].clone()).unwrap();assert_eq!(operation, RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2);@@ -53,6 +58,7 @@ struct Fixture {releases: Arc<AtomicUsize>,registrations: Arc<AtomicUsize>,created: Arc<AtomicBool>,+ check_result: Arc<std::sync::Mutex<Value>>,server: tokio::task::JoinHandle<()>,}impl Fixture {@@ -72,6 +78,8 @@ impl Fixture {let calls = Arc::new(AtomicUsize::new(0));let releases = Arc::new(AtomicUsize::new(0));let created = Arc::new(AtomicBool::new(false));+ let check_result = Arc::new(std::sync::Mutex::new(result(false)));+ let server_result = check_result.clone();let (server_calls, server_releases, server_created) =(calls.clone(), releases.clone(), created.clone());let server = tokio::spawn(async move {@@ -94,7 +102,9 @@ impl Fixture {"FindOperationByIdempotency" => json!({"digest_matches": true,"operation": if server_created.load(Ordering::SeqCst) { Some(json!({- "operation_id": "operation-a", "state": "succeeded", "sequence": 1,+ "operation_id": "operation-a",+ "state": server_result.lock().unwrap()["approval_operation"]["state"],+ "sequence": 1,"cancellable": false, "accepted_digest": CanonicalDigest::of_bytes(b"accepted"),"safe_error_code": null})) } else { None }@@ -102,7 +112,9 @@ impl Fixture {LIST_COMPUTE_SUBSCRIPTIONS_OPERATION_V2 => json!({"candidates": [], "discovery_state": "complete"}),- GET_SUBSCRIPTION_CHECK_RESULT_OPERATION_V2 => result(false),+ GET_SUBSCRIPTION_CHECK_RESULT_OPERATION_V2 => {+ server_result.lock().unwrap().clone()+ }"GetClientServiceStatus" => json!({"schema": "hiroute.client-service-status/v1", "daemon_role": "all","recovery_ready": true, "mutation_available": true, "gateway": "ready",@@ -136,6 +148,7 @@ impl Fixture {releases,registrations: Arc::new(AtomicUsize::new(0)),created,+ check_result,server,}}@@ -145,6 +158,147 @@ impl Fixture {Arc::new(CompletionAuthority(self.registrations.clone())),)}+ fn set_check_result(&self, value: Value) {+ serde_json::from_value::<ComputeSubscriptionCheckResultV2>(value.clone())+ .unwrap()+ .validate_shape()+ .unwrap();+ *self.check_result.lock().unwrap() = value;+ }+}++fn next_check(session: &mut Session) -> SubscriptionCheckConfirmation {+ let candidate = "candidate/cpa/claude/managed/second-login";+ let preview = serde_json::from_value(json!({+ "candidate": {"candidate_ref": candidate, "candidate_revision": 1},+ "display_scope": "Claude Code subscription",+ "spec": {+ "schema_version": {"major": 1, "minor": 0},+ "command_id": "compute.subscription.check.apply",+ "resource_id": candidate,+ "desired_state": {}+ },+ "accept_digest": CanonicalDigest::of_bytes(b"second-check"),+ "expected_revisions": {"target": 2, "dependencies": {}}+ }))+ .unwrap();+ let close_requested = session.resume_subscription_interaction();+ session+ .prepare_subscription_check_confirmation(+ preview,+ "en".into(),+ "b".repeat(64),+ close_requested,+ )+ .unwrap()+}++fn saved_result() -> Value {+ let mut value = result(false);+ value["status"] = json!("retained");+ value["save_operation"] = json!({+ "operation_id": "operation-save", "state": "succeeded", "sequence": 1,+ "cancellable": false+ });+ value+}++fn verified_result() -> Value {+ let mut value = result(false);+ value["status"] = json!("verified");+ value["checked_candidate"] = json!({+ "candidate": {"candidate_ref": "candidate/one", "candidate_revision": 2},+ "correlation": {+ "candidate_ref": "candidate/one", "edit_revision": 1,+ "check_id": "check-a", "input_digest": CanonicalDigest::of_bytes(b"checked")+ },+ "producer": "cpa", "provenance": "connector_owned",+ "display_name": "Codex subscription", "models": [],+ "input_state": "provided", "fact_state": "complete",+ "validation": value["validation"]+ });+ value+}++#[tokio::test]+async fn saved_subscription_check_allows_the_next_provider_without_releasing_saved_access() {+ let fixture = Fixture::new();+ fixture.set_check_result(saved_result());+ fixture.created.store(true, Ordering::SeqCst);+ let mut session = fixture.session();+ let _ = submitted(&mut session);+ let context = next_check(&mut session);+ let pending = session+ .begin_subscription_check_confirmation(context, true)+ .await+ .expect("a saved Codex subscription must not block the next Claude check");+ assert_eq!(+ pending.request.spec.resource_id.as_deref(),+ Some("candidate/cpa/claude/managed/second-login")+ );+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);+ // A late observation of the old saved check must not clear the new identity.+ session+ .finish_subscription_hint(&serde_json::from_value(saved_result()).unwrap())+ .unwrap();+ assert_eq!(+ session.subscription_hint.as_ref().unwrap().idempotency_key,+ "b".repeat(64)+ );+}++#[tokio::test]+async fn observing_a_saved_check_finishes_only_its_interaction_without_releasing_access() {+ let fixture = Fixture::new();+ fixture.set_check_result(saved_result());+ fixture.created.store(true, Ordering::SeqCst);+ let mut session = fixture.session();+ let _ = submitted(&mut session);+ let result = session.recover_subscription_check().await.unwrap().unwrap();+ assert_eq!(result.status, ComputeSubscriptionCheckStatusV2::Retained);+ assert!(session.subscription_hint.is_none());+ session.close_subscription_check().await.unwrap();+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn an_unsaved_verified_check_still_blocks_replacement() {+ let fixture = Fixture::new();+ fixture.set_check_result(verified_result());+ fixture.created.store(true, Ordering::SeqCst);+ let mut session = fixture.session();+ let _ = submitted(&mut session);+ let context = next_check(&mut session);+ let failure = session+ .begin_subscription_check_confirmation(context, true)+ .await;+ assert!(+ matches!(failure, Err(DesktopFailure::Native { code }) if code == "SUBSCRIPTION_CHECK_ACTIVE")+ );+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn an_in_progress_check_still_blocks_replacement() {+ let fixture = Fixture::new();+ let mut checking = result(false);+ checking["status"] = json!("checking");+ checking["validation"] = Value::Null;+ checking["approval_operation"]["state"] = json!("running");+ fixture.set_check_result(checking);+ fixture.created.store(true, Ordering::SeqCst);+ let mut session = fixture.session();+ let _ = submitted(&mut session);+ let context = next_check(&mut session);+ let failure = session+ .begin_subscription_check_confirmation(context, true)+ .await;+ assert!(+ matches!(failure, Err(DesktopFailure::Native { code }) if code == "SUBSCRIPTION_CHECK_ACTIVE")+ );+ assert_eq!(fixture.registrations.load(Ordering::SeqCst), 0);}impl Drop for Fixture {fn drop(&mut self) {diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.mdindex b685c2d3..a026e537 100644--- a/docs/code-map/architecture.md+++ b/docs/code-map/architecture.md@@ -106,7 +106,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi| 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. || Save Key order or use current Keys with an older plan | [Single-save edits](../../apps/desktop/src/features/models/model-draft.ts), [request admission](../../crates/gateway/src/core_runtime/credentials.rs), [current pool authority](../../crates/local-storage/src/control/compute/management/runtime_pool.rs), [safe Key masks](../../crates/daemon/src/control/runtime/model_connections/key_masks.rs) | A request owns its admitted Key IDs and order; later exact leases enforce current source/Key eligibility and generation. Admission retains closed permission denials in the existing request summary. Shared Plan content stays frozen. Masks are a separate authenticated query; saved plaintext never reaches Desktop. || 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) | 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. |+| 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 receives browser callbacks on temporary loopback listeners; an unavailable listener uses explicit protected manual input. 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) owns callback admission, authorization and refresh. || 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. |diff --git a/issue-spec/specs/model-connections/spec.md b/issue-spec/specs/model-connections/spec.mdindex c5b7b51e..60d061e1 100644--- a/issue-spec/specs/model-connections/spec.md+++ b/issue-spec/specs/model-connections/spec.md@@ -235,6 +235,17 @@ Independent CPA sign-in is the default recommendation; NativeBorrowed is an exploption and saved choices do not migrate automatically. Login completion alone doesnot enable routes or import all models.+Desktop subscription checks and model selection SHALL use subscription-specific+titles. Native discovery controls, including Hermes profile scanning, SHALL remain+on the device scan list and stay hidden in subscription details. Returning to the+scan list restores its controls; cancelling proxy editing retains the selected+subscription context.++A successful subscription save ends its Desktop check interaction. A later explicit+check, including another provider or account, MUST proceed without releasing or+invalidating the saved access. Running checks and verified checks that have not+completed saving retain their existing interaction ownership.+| Mode | Credential authority | Repair action || --- | --- | --- || NativeBorrowed | Native client owns login/refresh; CPA receives current access leases only | Update native login and explicitly recheck |@@ -251,6 +262,29 @@ and stops refresh while retaining credentials; remove-login first revokes savedroute access, then stops the exact instance and deletes its owned credentials.Neither claims provider-global OAuth revocation.+### Requirement: Independent sign-in receives browser callbacks locally++CPA owns temporary browser callback listeners for the existing Codex+`http://localhost:1455/auth/callback` and Claude `http://localhost:54545/callback`+redirects. Bind only available IPv4/IPv6 loopback families. Each provider has at+most one pending sign-in; saved accounts do not retain a callback listener.++Browser and protected manual input MUST share atomic, one-use admission for the+exact provider/session/state. Invalid, stale and duplicate input cannot replace+an accepted callback. CPA reception permits retry after failed callback-file+publication. HiRoute does not resend an admitted manual code after a failed or+uncertain submission: observe status, or cancel and start a new sign-in. The browser+acknowledges reception without claiming token exchange or sign-in success.+Release listeners after reception, cancellation, expiry or failure, before slow+token exchange. Do not redirect or reflect callback secrets in browser responses.++A port conflict MUST close partial listeners and retain the same pending session+for manual completion. Desktop explains this mode before the user explicitly opens+the browser, and accepts the full return URL through the existing protected input.+Automatic reception opens the browser normally and retains manual completion as+a fallback. Successful sign-in still requires explicit Check/Save; it does not+change enabled-account or routing limits.+### Requirement: Borrowed subscription refresh cannot enlarge saved membershipOnly approved, saved, enabled NativeBorrowed sources may maintain their associationdiff --git a/scripts/test-package-desktop.py b/scripts/test-package-desktop.pyindex 892cc71e..a67d8c27 100644--- a/scripts/test-package-desktop.py+++ b/scripts/test-package-desktop.py@@ -94,7 +94,7 @@ class BundleIdentityTests(unittest.TestCase):def test_cpa_is_explicitly_signed_before_release_probe(self):events = []- release = ("CLIProxyAPI Version: 8.0.4-hiroute.4, Commit: "+ release = ("CLIProxyAPI Version: 8.0.4-hiroute.5, Commit: ""a270e7b9e57aaecd8f82555f44c2108518ad2330, ""BuiltAt: 2026-09-29T00:00:00Z")with patch.object(package, "sign", side_effect=lambda *_: events.append("sign")), \diff --git a/vendor/cpa/README.md b/vendor/cpa/README.mdindex 62a19c29..19f8a501 100644--- a/vendor/cpa/README.md+++ b/vendor/cpa/README.md@@ -4,6 +4,38 @@`local-management-stdin.patch` includes the parent-pipe management credentialbootstrap and Codex account model discovery. Build with `scripts/build-cpa.py`.+## Browser sign-in callbacks++The pinned browser flow receives Codex and Claude callbacks directly on temporary+loopback listeners at their existing registered addresses. It binds available IPv4+and IPv6 loopback interfaces; an occupied address releases any partial bind and+keeps the same session for protected manual input. The private auth-URL response+projects only `hiroute_callback_mode=automatic|manual`. An old artifact lacking+this handshake must not be used with the current daemon.++Reception checks the method, path, host and exact pending state. Browser callbacks+and the management callback POST share atomic one-use admission, including after+the waiting OAuth worker removes the callback file. CPA reception may retry failed+file publication; HiRoute's manual-input owner does not resend an admitted code+after a failed or uncertain submission. Observe status or cancel and start again.+An accepted authorization code cannot be replaced. The browser response contains no code,+state, provider error or management redirect and acknowledges reception only.+The existing token exchange and credential persistence establish actual login.+Completion, cancellation, timeout and owned-process exit release the listeners.+There is one pending login per provider; saved accounts do not retain these ports.++The patch carries `TestHiRouteBrowserCallbackValidationAndOneUse`, atomic admission,+dual-loopback cleanup, occupied-port fallback, main-route error and actual Codex+browser-to-file-store regressions. Run these on the exact prepared source with:++```sh+go test ./internal/api/handlers/management ./internal/api -run '^TestHiRoute' -count=1+```++The Codex exchange regression supplies synthetic tokens through the pinned OAuth+service test seam. It proves callback reception and persistence, not fresh real-account+authorization. No native credential store or paid model call is used.+Codex OAuth registration queries `https://chatgpt.com/backend-api/codex/models`using the account's access token and account ID over CPA's existing proxy/TLStransport. For native access-only leases, `client_version` comes from the authdiff --git a/vendor/cpa/local-management-stdin.patch b/vendor/cpa/local-management-stdin.patchindex f1b8c9f6..381c06d5 100644--- a/vendor/cpa/local-management-stdin.patch+++ b/vendor/cpa/local-management-stdin.patch@@ -104,6 +104,582 @@ index 2b99077..a661fbb 100644cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...)}}+diff --git a/internal/api/handlers/management/auth_files_oauth_callback.go b/internal/api/handlers/management/auth_files_oauth_callback.go+index f33f82e..3d87ba9 100644+--- a/internal/api/handlers/management/auth_files_oauth_callback.go++++ b/internal/api/handlers/management/auth_files_oauth_callback.go+@@ -8,6 +8,7 @@ import (+ "net/http"+ "net/url"+ "strings"++ "sync"+ "time"++ "github.com/gin-gonic/gin"+@@ -39,23 +40,6 @@ func isWebUIRequest(c *gin.Context) bool {+ }++ func startCallbackForwarder(port int, provider, targetBase string) (*callbackForwarder, error) {+- callbackForwardersMu.Lock()+- prev := callbackForwarders[port]+- if prev != nil {+- delete(callbackForwarders, port)+- }+- callbackForwardersMu.Unlock()+-+- if prev != nil {+- stopForwarderInstance(port, prev)+- }+-+- addr := fmt.Sprintf("0.0.0.0:%d", port)+- ln, err := net.Listen("tcp", addr)+- if err != nil {+- return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)+- }+-+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ target := targetBase+ if raw := r.URL.RawQuery; raw != "" {+@@ -69,6 +53,24 @@ func startCallbackForwarder(port int, provider, targetBase string) (*callbackFor+ http.Redirect(w, r, target, http.StatusFound)+ })+++ return startCallbackServer(port, provider, handler)++}++++func startCallbackServer(port int, provider string, handler http.Handler) (*callbackForwarder, error) {++ callbackForwardersMu.Lock()++ prev := callbackForwarders[port]++ if prev != nil {++ delete(callbackForwarders, port)++ }++ callbackForwardersMu.Unlock()++ if prev != nil {++ stopForwarderInstance(port, prev)++ }++ listeners, err := listenHiRouteCallbackLoopback(port)++ if err != nil {++ return nil, err++ }+++ srv := &http.Server{+ Handler: handler,+ ReadHeaderTimeout: 5 * time.Second,+@@ -76,10 +78,18 @@ func startCallbackForwarder(port int, provider, targetBase string) (*callbackFor+ }+ done := make(chan struct{})+++ var serving sync.WaitGroup++ for _, listener := range listeners {++ serving.Add(1)++ go func(ln net.Listener) {++ defer serving.Done()++ if errServe := srv.Serve(ln); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) {++ log.Warn("local OAuth callback listener stopped unexpectedly")++ }++ }(listener)++ }+ go func() {+- if errServe := srv.Serve(ln); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) {+- log.WithError(errServe).Warnf("callback forwarder for %s stopped unexpectedly", provider)+- }++ serving.Wait()+ close(done)+ }()++@@ -93,7 +103,7 @@ func startCallbackForwarder(port int, provider, targetBase string) (*callbackFor+ callbackForwarders[port] = forwarder+ callbackForwardersMu.Unlock()++- log.Infof("callback forwarder for %s listening on %s", provider, addr)++ log.Infof("callback listener for %s is ready on loopback port %d", provider, port)++ return forwarder, nil+ }+diff --git a/internal/api/handlers/management/auth_files_provider_oauth.go b/internal/api/handlers/management/auth_files_provider_oauth.go+index 48fc4ef..ebacfa4 100644+--- a/internal/api/handlers/management/auth_files_provider_oauth.go++++ b/internal/api/handlers/management/auth_files_provider_oauth.go+@@ -70,19 +70,17 @@ func (h *Handler) RequestAnthropicToken(c *gin.Context) {+ RegisterOAuthSession(state, "anthropic")++ isWebUI := isWebUIRequest(c)++ callbackMode := "manual"+ var forwarder *callbackForwarder+ if isWebUI {+- targetURL, errTarget := h.managementCallbackURL("/anthropic/callback")+- if errTarget != nil {+- log.WithError(errTarget).Error("failed to compute anthropic callback target")+- c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"})+- return+- }+ var errStart error+- if forwarder, errStart = startCallbackForwarder(anthropicCallbackPort, "anthropic", targetURL); errStart != nil {+- log.WithError(errStart).Error("failed to start anthropic callback forwarder")+- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"})+- return++ forwarder, errStart = startHiRouteCallbackReceiver(anthropicCallbackPort, "anthropic", state, h.cfg.AuthDir)++ if errStart == nil {++ callbackMode = "automatic"++ } else {++ // Keep this exact session for protected manual input. Do not disclose++ // host errors or replace an unrelated process owning the callback port.++ log.Warn("local OAuth callback listener unavailable; manual completion required")+ }+ }++@@ -142,6 +140,8 @@ func (h *Handler) RequestAnthropicToken(c *gin.Context) {+ rawCode := resultMap["code"]+ code := strings.Split(rawCode, "#")[0]+++ stopCallbackForwarderInstance(anthropicCallbackPort, forwarder)+++ // Exchange code for tokens using internal auth service+ bundle, errExchange := anthropicAuth.ExchangeCodeForTokens(ctx, code, state, pkceCodes)+ if errExchange != nil {+@@ -192,7 +192,7 @@ func (h *Handler) RequestAnthropicToken(c *gin.Context) {+ CompleteOAuthSession(state)+ }()++- c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})++ c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state, "hiroute_callback_mode": callbackMode})+ }++ func (h *Handler) RequestCodexToken(c *gin.Context) {+@@ -231,19 +231,17 @@ func (h *Handler) RequestCodexToken(c *gin.Context) {+ RegisterOAuthSession(state, "codex")++ isWebUI := isWebUIRequest(c)++ callbackMode := "manual"+ var forwarder *callbackForwarder+ if isWebUI {+- targetURL, errTarget := h.managementCallbackURL("/codex/callback")+- if errTarget != nil {+- log.WithError(errTarget).Error("failed to compute codex callback target")+- c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"})+- return+- }+ var errStart error+- if forwarder, errStart = startCallbackForwarder(codexCallbackPort, "codex", targetURL); errStart != nil {+- log.WithError(errStart).Error("failed to start codex callback forwarder")+- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"})+- return++ forwarder, errStart = startHiRouteCallbackReceiver(codexCallbackPort, "codex", state, h.cfg.AuthDir)++ if errStart == nil {++ callbackMode = "automatic"++ } else {++ // Keep this exact session for protected manual input. Do not disclose++ // host errors or replace an unrelated process owning the callback port.++ log.Warn("local OAuth callback listener unavailable; manual completion required")+ }+ }++@@ -288,6 +286,7 @@ func (h *Handler) RequestCodexToken(c *gin.Context) {+ time.Sleep(500 * time.Millisecond)+ }+++ stopCallbackForwarderInstance(codexCallbackPort, forwarder)+ log.Debug("Authorization code received, exchanging for tokens...")+ // Exchange code for tokens using internal auth service+ bundle, errExchange := openaiAuth.ExchangeCodeForTokens(ctx, code, pkceCodes)+@@ -353,7 +352,7 @@ func (h *Handler) RequestCodexToken(c *gin.Context) {+ CompleteOAuthSession(state)+ }()++- c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})++ c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state, "hiroute_callback_mode": callbackMode})+ }++ func (h *Handler) RequestAntigravityToken(c *gin.Context) {+diff --git a/internal/api/handlers/management/hiroute_oauth_callback.go b/internal/api/handlers/management/hiroute_oauth_callback.go+new file mode 100644+index 0000000..7aac5b4+--- /dev/null++++ b/internal/api/handlers/management/hiroute_oauth_callback.go+@@ -0,0 +1,107 @@++package management++++import (++ "errors"++ "fmt"++ "net"++ "net/http"++ "net/url"++ "strconv"++ "strings"++ "syscall"++++ "github.com/gin-gonic/gin"++)++++// The registered localhost redirect can resolve to either family. Never fall++// back to another interface or retain half a listener when the other is occupied.++func listenHiRouteCallbackLoopback(port int) ([]net.Listener, error) {++ var listeners []net.Listener++ for _, address := range []struct{ network, host string }{{"tcp4", "127.0.0.1"}, {"tcp6", "::1"}} {++ listener, err := net.Listen(address.network, net.JoinHostPort(address.host, strconv.Itoa(port)))++ if err != nil {++ if errors.Is(err, syscall.EAFNOSUPPORT) || errors.Is(err, syscall.EPROTONOSUPPORT) || errors.Is(err, syscall.EADDRNOTAVAIL) {++ continue++ }++ for _, opened := range listeners {++ _ = opened.Close()++ }++ return nil, fmt.Errorf("callback loopback unavailable: %w", err)++ }++ listeners = append(listeners, listener)++ }++ if len(listeners) == 0 {++ return nil, errors.New("callback loopback unavailable")++ }++ return listeners, nil++}++++func startHiRouteCallbackReceiver(port int, provider, state, authDir string) (*callbackForwarder, error) {++ return startCallbackServer(port, provider, hiRouteCallbackHandler(port, provider, state, authDir))++}++++func hiRouteCallbackHandler(port int, provider, state, authDir string) http.Handler {++ path := "/auth/callback"++ if provider == "anthropic" {++ path = "/callback"++ }++ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {++ w.Header().Set("Cache-Control", "no-store")++ w.Header().Set("Referrer-Policy", "no-referrer")++ w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")++ w.Header().Set("X-Content-Type-Options", "nosniff")++ host, requestPort, err := net.SplitHostPort(r.Host)++ if err != nil || requestPort != strconv.Itoa(port) || (host != "localhost" && host != "127.0.0.1" && host != "::1") {++ http.Error(w, "Invalid callback address.", http.StatusBadRequest)++ return++ }++ if r.Method != http.MethodGet || r.URL.Path != path || r.URL.RawPath != "" || len(r.RequestURI) > 16384 {++ http.Error(w, "Invalid callback request.", http.StatusBadRequest)++ return++ }++ receiveHiRouteBrowserCallback(w, r, provider, state, authDir)++ })++}++++// The main-server callback paths share the same checked reception and never++// claim login success just because a browser reached the endpoint.++func HiRouteBrowserOAuthCallback(authDir, provider string) gin.HandlerFunc {++ return func(c *gin.Context) {++ c.Header("Cache-Control", "no-store")++ c.Header("Referrer-Policy", "no-referrer")++ c.Header("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")++ c.Header("X-Content-Type-Options", "nosniff")++ receiveHiRouteBrowserCallback(c.Writer, c.Request, provider, "", authDir)++ }++}++++func receiveHiRouteBrowserCallback(w http.ResponseWriter, r *http.Request, provider, expectedState, authDir string) {++ if len(r.RequestURI) > 16384 {++ http.Error(w, "Invalid callback request.", http.StatusBadRequest)++ return++ }++ query, err := url.ParseQuery(r.URL.RawQuery)++ if err != nil || len(query["state"]) != 1 || query.Get("state") == "" || (expectedState != "" && query.Get("state") != expectedState) || len(query["code"]) > 1 || len(query["error"]) > 1 {++ http.Error(w, "Invalid callback. Return to HiRoute to continue signing in.", http.StatusBadRequest)++ return++ }++ code, oauthError := query.Get("code"), query.Get("error")++ if (code == "") == (oauthError == "") || strings.ContainsAny(code+oauthError, "\r\n\x00") {++ http.Error(w, "Invalid callback. Return to HiRoute to continue signing in.", http.StatusBadRequest)++ return++ }++ if _, err := WriteOAuthCallbackFileForPendingSession(authDir, provider, query.Get("state"), code, oauthError); err != nil {++ status := http.StatusInternalServerError++ if errors.Is(err, errOAuthSessionNotPending) {++ status = http.StatusConflict++ }++ http.Error(w, "Callback was not accepted. Return to HiRoute to check the sign-in status.", status)++ return++ }++ w.Header().Set("Content-Type", "text/plain; charset=utf-8")++ if oauthError != "" {++ _, _ = w.Write([]byte("Authorization was not completed. Return to HiRoute to try again.\n授权未完成,请返回 HiRoute 重试。"))++ return++ }++ _, _ = w.Write([]byte("Authorization received. Return to HiRoute to check whether sign-in has completed.\n已收到授权,请返回 HiRoute 查看登录结果。"))++}+diff --git a/internal/api/handlers/management/hiroute_oauth_callback_test.go b/internal/api/handlers/management/hiroute_oauth_callback_test.go+new file mode 100644+index 0000000..fdd19ac+--- /dev/null++++ b/internal/api/handlers/management/hiroute_oauth_callback_test.go+@@ -0,0 +1,270 @@++package management++++import (++ "context"++ "encoding/json"++ "io"++ "net"++ "net/http"++ "net/http/httptest"++ "os"++ "path/filepath"++ "strconv"++ "strings"++ "sync"++ "sync/atomic"++ "testing"++ "time"++++ "github.com/gin-gonic/gin"++ "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex"++ "github.com/router-for-me/CLIProxyAPI/v8/internal/config"++)++++func TestHiRouteBrowserCallbackValidationAndOneUse(t *testing.T) {++ for _, provider := range []string{"codex", "anthropic"} {++ t.Run(provider, func(t *testing.T) {++ dir, state := t.TempDir(), "hiroute-validation-"+provider++ RegisterOAuthSession(state, provider)++ defer CancelOAuthSession(state)++ path := "/auth/callback"++ if provider == "anthropic" {++ path = "/callback"++ }++ handler := hiRouteCallbackHandler(1455, provider, state, dir)++ valid := path + "?state=" + state + "&code=private-test-code"++ for _, input := range []struct{ method, path, host string }{++ {"GET", path + "?state=foreign&code=private-test-code", "localhost:1455"},++ {"GET", valid + "&state=" + state, "localhost:1455"},++ {"GET", valid + "&code=second", "localhost:1455"},++ {"GET", valid + "&error=denied", "localhost:1455"},++ {"GET", path + "?state=" + state, "localhost:1455"},++ {"GET", valid + "&bad=%ZZ", "localhost:1455"},++ {"GET", valid, "foreign.test:1455"},++ {"POST", valid, "localhost:1455"},++ {"GET", "/foreign?state=" + state + "&code=test", "localhost:1455"},++ } {++ r := httptest.NewRequest(input.method, "http://localhost:1455"+input.path, nil)++ r.Host = input.host++ w := httptest.NewRecorder()++ handler.ServeHTTP(w, r)++ if w.Code != http.StatusBadRequest {++ t.Fatalf("invalid callback accepted: %d", w.Code)++ }++ if strings.Contains(w.Body.String(), "private-test-code") || w.Header().Get("Location") != "" {++ t.Fatal("callback escaped through response")++ }++ }++ w := httptest.NewRecorder()++ handler.ServeHTTP(w, httptest.NewRequest("GET", "http://localhost:1455"+valid, nil))++ if w.Code != 200 || !strings.Contains(w.Body.String(), "Authorization received") || strings.Contains(w.Body.String(), "successful") {++ t.Fatal("browser reception claimed login success")++ }++ if w.Header().Get("Referrer-Policy") != "no-referrer" || w.Header().Get("Cache-Control") != "no-store" {++ t.Fatal("callback page did not protect the query")++ }++ file := filepath.Join(dir, ".oauth-"+provider+"-"+state+".oauth")++ if err := os.Remove(file); err != nil {++ t.Fatal(err)++ }++ if _, err := WriteOAuthCallbackFileForPendingSession(dir, provider, state, "replacement", ""); err == nil {++ t.Fatal("manual input overwrote a consumed browser callback")++ }++ w = httptest.NewRecorder()++ handler.ServeHTTP(w, httptest.NewRequest("GET", "http://localhost:1455"+valid, nil))++ if w.Code != http.StatusConflict {++ t.Fatal("repeated browser callback accepted")++ }++ })++ }++}++++func TestHiRouteCallbackAdmissionIsAtomicAndFailedWritesCanRetry(t *testing.T) {++ dir, state := t.TempDir(), "hiroute-concurrent-callback"++ RegisterOAuthSession(state, "codex")++ defer CancelOAuthSession(state)++ badPath := filepath.Join(dir, "not-a-directory")++ if err := os.WriteFile(badPath, []byte("fixture"), 0600); err != nil {++ t.Fatal(err)++ }++ if _, err := WriteOAuthCallbackFileForPendingSession(badPath, "codex", state, "code", ""); err == nil {++ t.Fatal("failed write was accepted")++ }++ var accepted atomic.Int32++ var group sync.WaitGroup++ for i := 0; i < 16; i++ {++ group.Add(1)++ go func() {++ defer group.Done()++ if _, err := WriteOAuthCallbackFileForPendingSession(dir, "codex", state, "code", ""); err == nil {++ accepted.Add(1)++ }++ }()++ }++ group.Wait()++ if accepted.Load() != 1 {++ t.Fatalf("accepted %d callbacks", accepted.Load())++ }++ for _, stale := range []string{"unknown-state", "cancelled-state", "expired-state"} {++ RegisterOAuthSession(stale, "codex")++ if stale == "expired-state" {++ oauthSessions.mu.Lock()++ s := oauthSessions.sessions[stale]++ s.ExpiresAt = time.Now().Add(-time.Second)++ oauthSessions.sessions[stale] = s++ oauthSessions.mu.Unlock()++ } else {++ CancelOAuthSession(stale)++ }++ if _, err := WriteOAuthCallbackFileForPendingSession(dir, "codex", stale, "late-code", ""); err == nil {++ t.Fatal("stale callback accepted")++ }++ }++}++++func TestHiRouteLoopbackListenersReleaseTogether(t *testing.T) {++ reservation, err := net.Listen("tcp4", "127.0.0.1:0")++ if err != nil {++ t.Fatal(err)++ }++ port := reservation.Addr().(*net.TCPAddr).Port++ _ = reservation.Close()++ listeners, err := listenHiRouteCallbackLoopback(port)++ if err != nil {++ t.Fatal(err)++ }++ for _, ln := range listeners {++ if !ln.Addr().(*net.TCPAddr).IP.IsLoopback() {++ t.Fatal("non-loopback callback listener")++ }++ _ = ln.Close()++ }++ forwarder, err := startHiRouteCallbackReceiver(port, "codex", "hiroute-loopback", t.TempDir())++ if err != nil {++ t.Fatal(err)++ }++ stopCallbackForwarderInstance(port, forwarder)++ reopened, err := listenHiRouteCallbackLoopback(port)++ if err != nil {++ t.Fatalf("callback listener leaked: %v", err)++ }++ for _, ln := range reopened {++ _ = ln.Close()++ }++ // An occupied IPv6 endpoint must release the already-opened IPv4 endpoint.++ ipv6, err := net.Listen("tcp6", net.JoinHostPort("::1", strconv.Itoa(port)))++ if err == nil {++ defer ipv6.Close()++ if opened, err := listenHiRouteCallbackLoopback(port); err == nil {++ for _, ln := range opened {++ _ = ln.Close()++ }++ t.Fatal("occupied IPv6 listener was ignored")++ }++ ipv4, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))++ if err != nil {++ t.Fatal("partial IPv4 listener leaked")++ }++ _ = ipv4.Close()++ }++}++++func TestHiRouteOccupiedCallbackPortKeepsManualSession(t *testing.T) {++ for _, provider := range []string{"codex", "anthropic"} {++ port := codexCallbackPort++ if provider == "anthropic" {++ port = anthropicCallbackPort++ }++ occupied, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))++ if err == nil {++ defer occupied.Close()++ }++ h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir(), Port: 47111}, nil)++ w := httptest.NewRecorder()++ c, _ := gin.CreateTestContext(w)++ c.Request = httptest.NewRequest("GET", "/auth-url?is_webui=true", nil)++ if provider == "codex" {++ h.RequestCodexToken(c)++ } else {++ h.RequestAnthropicToken(c)++ }++ var login map[string]string++ if err := json.Unmarshal(w.Body.Bytes(), &login); err != nil {++ t.Fatal(err)++ }++ if w.Code != 200 || login["hiroute_callback_mode"] != "manual" || login["url"] == "" || !IsOAuthSessionPending(login["state"], provider) {++ t.Fatalf("occupied callback port lost the manual session: status %d", w.Code)++ }++ CancelOAuthSession(login["state"])++ }++}++++type hiRouteCountedCodexService struct {++ fakeCodexOAuthService++ exchanges atomic.Int32++}++++func (s *hiRouteCountedCodexService) ExchangeCodeForTokens(ctx context.Context, code string, pkce *codex.PKCECodes) (*codex.CodexAuthBundle, error) {++ s.exchanges.Add(1)++ return s.fakeCodexOAuthService.ExchangeCodeForTokens(ctx, code, pkce)++}++++func TestHiRouteCodexBrowserCompletionAndPortRelease(t *testing.T) {++ service := &hiRouteCountedCodexService{}++ original := newCodexOAuthService++ newCodexOAuthService = func(*config.Config) codexOAuthService { return service }++ defer func() { newCodexOAuthService = original }()++ dir := t.TempDir()++ h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: dir, Port: 47111}, nil)++ w := httptest.NewRecorder()++ c, _ := gin.CreateTestContext(w)++ c.Request = httptest.NewRequest("GET", "/auth-url?is_webui=true", nil)++ h.RequestCodexToken(c)++ var login map[string]string++ if err := json.Unmarshal(w.Body.Bytes(), &login); err != nil {++ t.Fatal(err)++ }++ defer CancelOAuthSession(login["state"])++ if w.Code != 200 || login["hiroute_callback_mode"] != "automatic" {++ t.Fatal("browser callback listener did not start")++ }++ client := &http.Client{Transport: &http.Transport{Proxy: nil}, Timeout: 3 * time.Second}++ defer client.CloseIdleConnections()++ response, err := client.Get("http://localhost:1455/auth/callback?state=" + login["state"] + "&code=hiroute-test-code")++ if err != nil {++ t.Fatal(err)++ }++ body, _ := io.ReadAll(response.Body)++ _ = response.Body.Close()++ if response.StatusCode != 200 || strings.Contains(string(body), "successful") || strings.Contains(string(body), "hiroute-test-code") {++ t.Fatal("incorrect browser callback response")++ }++ waitForOAuthSessionDone(t, login["state"])++ if service.exchanges.Load() != 1 {++ t.Fatal("authorization code exchange was replayed")++ }++ files, _ := filepath.Glob(filepath.Join(dir, "*.json"))++ if len(files) != 1 {++ t.Fatal("browser callback did not persist exactly one credential")++ }++ if _, err := WriteOAuthCallbackFileForPendingSession(dir, "codex", login["state"], "replacement", ""); err == nil {++ t.Fatal("completed login accepted manual input")++ }++ listeners, err := listenHiRouteCallbackLoopback(codexCallbackPort)++ if err != nil {++ t.Fatal("completed login retained its callback port")++ }++ for _, ln := range listeners {++ _ = ln.Close()++ }++}++++func TestHiRouteMainCallbackDoesNotReportFalseSuccess(t *testing.T) {++ router := gin.New()++ router.GET("/codex/callback", HiRouteBrowserOAuthCallback(t.TempDir(), "codex"))++ w := httptest.NewRecorder()++ router.ServeHTTP(w, httptest.NewRequest("GET", "/codex/callback?state=unknown&code=secret", nil))++ if w.Code != http.StatusConflict || strings.Contains(w.Body.String(), "successful") || strings.Contains(w.Body.String(), "secret") {++ t.Fatal("unaccepted callback reported success")++ }++}diff --git a/internal/api/handlers/management/local_machine_password_test.go b/internal/api/handlers/management/local_machine_password_test.gonew file mode 100644index 0000000..74d027d@@ -148,6 +724,99 @@ index 0000000..74d027d+ t.Fatal("old instance credential accepted")+ }+}+diff --git a/internal/api/handlers/management/oauth_sessions.go b/internal/api/handlers/management/oauth_sessions.go+index 336f9bb..9359040 100644+--- a/internal/api/handlers/management/oauth_sessions.go++++ b/internal/api/handlers/management/oauth_sessions.go+@@ -33,13 +33,14 @@ var (+ )++ type oauthSession struct {+- Provider string+- Status string+- Source string+- Metadata map[string]any+- Completed bool+- CreatedAt time.Time+- ExpiresAt time.Time++ Provider string++ Status string++ Source string++ Metadata map[string]any++ Completed bool++ CallbackSubmitted bool++ CreatedAt time.Time++ ExpiresAt time.Time+ }++ type oauthSessionStore struct {+@@ -481,8 +482,24 @@ func WriteOAuthCallbackFileForPendingSession(authDir, provider, state, code, err+ if err != nil {+ return "", err+ }+- if !IsOAuthSessionPending(state, canonicalProvider) {++ // Automatic browser callbacks and protected manual input share one admission.++ // Hold it through atomic file publication; the consumer can remove that file,++ // so its presence alone cannot prevent a second submission.++ oauthSessions.mu.Lock()++ defer oauthSessions.mu.Unlock()++ oauthSessions.purgeExpiredLocked(time.Now())++ session, ok := oauthSessions.sessions[state]++ if !ok || session.Provider != canonicalProvider || session.Completed || session.Status != "" || session.CallbackSubmitted {+ return "", errOAuthSessionNotPending+ }+- return writeOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)++ if strings.TrimSpace(code) == "" && strings.TrimSpace(errorMessage) == "" {++ return "", errInvalidOAuthState++ }++ path, err := writeOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)++ if err != nil {++ return "", err++ }++ session.CallbackSubmitted = true++ oauthSessions.sessions[state] = session++ return path, nil+ }+diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go+index 546ca73..a878459 100644+--- a/internal/api/server_routes.go++++ b/internal/api/server_routes.go+@@ -143,33 +143,9 @@ func (s *Server) setupRoutes() {+ // OAuth callback endpoints (reuse main server port)+ // These endpoints receive provider redirects and persist+ // the short-lived code/state for the waiting goroutine.+- s.engine.GET("/anthropic/callback", func(c *gin.Context) {+- code := c.Query("code")+- state := c.Query("state")+- errStr := c.Query("error")+- if errStr == "" {+- errStr = c.Query("error_description")+- }+- if state != "" {+- _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "anthropic", state, code, errStr)+- }+- c.Header("Content-Type", "text/html; charset=utf-8")+- c.String(http.StatusOK, oauthCallbackSuccessHTML)+- })++ s.engine.GET("/anthropic/callback", managementHandlers.HiRouteBrowserOAuthCallback(s.cfg.AuthDir, "anthropic"))++- s.engine.GET("/codex/callback", func(c *gin.Context) {+- code := c.Query("code")+- state := c.Query("state")+- errStr := c.Query("error")+- if errStr == "" {+- errStr = c.Query("error_description")+- }+- if state != "" {+- _, _ = managementHandlers.WriteOAuthCallbackFileForPendingSession(s.cfg.AuthDir, "codex", state, code, errStr)+- }+- c.Header("Content-Type", "text/html; charset=utf-8")+- c.String(http.StatusOK, oauthCallbackSuccessHTML)+- })++ s.engine.GET("/codex/callback", managementHandlers.HiRouteBrowserOAuthCallback(s.cfg.AuthDir, "codex"))++ s.engine.GET("/antigravity/callback", func(c *gin.Context) {+ code := c.Query("code")diff --git a/internal/auth/claude/hiroute_environment_proxy_test.go b/internal/auth/claude/hiroute_environment_proxy_test.gonew file mode 100644index 0000000..3869b7ediff --git a/vendor/cpa/source.json b/vendor/cpa/source.jsonindex 884f48e4..674f65a4 100644--- a/vendor/cpa/source.json+++ b/vendor/cpa/source.json@@ -1,8 +1,8 @@{"repository": "https://github.com/router-for-me/CLIProxyAPI","commit": "a270e7b9e57aaecd8f82555f44c2108518ad2330",- "version": "8.0.4-hiroute.4",+ "version": "8.0.4-hiroute.5","built_at": "2026-09-29T00:00:00Z","patch": "local-management-stdin.patch",- "patch_sha256": "d10bd3ad221c6d2d4811cb4321c931f0f20c70afbc6af55c449a27bac873c768"+ "patch_sha256": "3d871605b9f8bbb7ec25b1f3ecfc86c80f0d77e77bf10584cb82bf8766249d7f"}