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
feat: add Codex profiles and unified agent model setup (#39)
澄潭27f69429f7ab
diff --git a/Cargo.lock b/Cargo.lockindex 772b2b36..f0f5ba3c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -208,6 +208,27 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]+name = "arboard"+version = "3.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"+dependencies = [+ "clipboard-win",+ "image",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "parking_lot",+ "percent-encoding",+ "windows-sys 0.60.2",+ "wl-clipboard-rs",+ "x11rb",+]+[[package]]name = "arc-swap"version = "1.9.2"@@ -253,7 +274,7 @@ dependencies = ["asn1-rs-derive","asn1-rs-impl","displaydoc",- "nom",+ "nom 7.1.3","num-traits","rusticata-macros","thiserror 1.0.69",@@ -806,6 +827,15 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"+[[package]]+name = "clipboard-win"+version = "5.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"+dependencies = [+ "error-code",+]+[[package]]name = "cmake"version = "0.1.58"@@ -1061,7 +1091,7 @@ version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "70def8d72740e44d9f676d8dab2c933a236663d86dd24319b57a2bed4d694774"dependencies = [- "petgraph",+ "petgraph 0.7.1",][[package]]@@ -1167,7 +1197,7 @@ checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553"dependencies = ["asn1-rs","displaydoc",- "nom",+ "nom 7.1.3","num-bigint","num-traits","rusticata-macros",@@ -1311,7 +1341,7 @@ checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"dependencies = ["bit-set","cssparser",- "foldhash",+ "foldhash 0.2.0","html5ever","precomputed-hash","selectors",@@ -1458,6 +1488,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "error-code"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"+[[package]]name = "event-listener"version = "5.4.2"@@ -1496,6 +1532,12 @@ version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"+[[package]]+name = "fax"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"+[[package]]name = "fdeflate"version = "0.3.7"@@ -1557,6 +1599,12 @@ version = "1.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+[[package]]name = "foldhash"version = "0.2.0"@@ -1838,6 +1886,16 @@ dependencies = ["version_check",]+[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix",+ "windows-link 0.2.1",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -2053,6 +2111,17 @@ dependencies = ["tracing",]+[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "zerocopy",+]+[[package]]name = "hashbrown"version = "0.12.3"@@ -2068,6 +2137,15 @@ dependencies = ["ahash",]+[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash 0.1.5",+]+[[package]]name = "hashbrown"version = "0.16.1"@@ -2076,7 +2154,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"dependencies = ["allocator-api2","equivalent",- "foldhash",+ "foldhash 0.2.0",][[package]]@@ -2258,6 +2336,7 @@ dependencies = ["sha2","tauri","tauri-build",+ "tauri-plugin-clipboard-manager","tauri-plugin-dialog","tauri-plugin-pilot","tempfile",@@ -2772,6 +2851,7 @@ dependencies = ["moxcms","num-traits","png 0.18.1",+ "tiff",][[package]]@@ -3293,6 +3373,15 @@ dependencies = ["minimal-lexical",]+[[package]]+name = "nom"+version = "8.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"+dependencies = [+ "memchr",+]+[[package]]name = "num-bigint"version = "0.4.8"@@ -3379,6 +3468,7 @@ dependencies = ["block2","objc2","objc2-core-foundation",+ "objc2-core-graphics","objc2-foundation",]@@ -3634,6 +3724,16 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "ouroboros"version = "0.18.5"@@ -3738,6 +3838,17 @@ dependencies = ["indexmap 2.14.1",]+[[package]]+name = "petgraph"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"+dependencies = [+ "fixedbitset",+ "hashbrown 0.15.5",+ "indexmap 2.14.1",+]+[[package]]name = "phf"version = "0.13.1"@@ -4186,6 +4297,12 @@ version = "1.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"+[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"+[[package]]name = "quick-xml"version = "0.41.0"@@ -4248,7 +4365,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.59.0",+ "windows-sys 0.60.2",][[package]]@@ -4555,7 +4672,7 @@ version = "4.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"dependencies = [- "nom",+ "nom 7.1.3",][[package]]@@ -4683,7 +4800,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"dependencies = ["fnv",- "quick-error",+ "quick-error 1.2.3","tempfile","wait-timeout",]@@ -5541,6 +5658,21 @@ dependencies = ["walkdir",]+[[package]]+name = "tauri-plugin-clipboard-manager"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "206dc20af4ed210748ba945c2774e60fd0acd52b9a73a028402caf809e9b6ecf"+dependencies = [+ "arboard",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.20",+]+[[package]]name = "tauri-plugin-dialog"version = "2.7.3"@@ -5773,6 +5905,20 @@ dependencies = ["cfg-if",]+[[package]]+name = "tiff"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"+dependencies = [+ "fax",+ "flate2",+ "half",+ "quick-error 2.0.1",+ "weezl",+ "zune-jpeg",+]+[[package]]name = "time"version = "0.3.55"@@ -6131,6 +6277,17 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "tree_magic_mini"+version = "3.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"+dependencies = [+ "memchr",+ "nom 8.0.0",+ "petgraph 0.8.3",+]+[[package]]name = "try-lock"version = "0.2.5"@@ -6157,7 +6314,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"dependencies = ["memoffset","tempfile",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6504,6 +6661,19 @@ dependencies = ["wayland-scanner",]+[[package]]+name = "wayland-protocols-wlr"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"+dependencies = [+ "bitflags 2.13.1",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]+[[package]]name = "wayland-scanner"version = "0.31.11"@@ -6647,6 +6817,12 @@ dependencies = ["windows-core 0.61.2",]+[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"+[[package]]name = "winapi"version = "0.3.9"@@ -7183,6 +7359,24 @@ version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "wl-clipboard-rs"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"+dependencies = [+ "libc",+ "log",+ "os_pipe",+ "rustix",+ "thiserror 2.0.20",+ "tree_magic_mini",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-wlr",+]+[[package]]name = "writeable"version = "0.6.4"@@ -7254,6 +7448,23 @@ dependencies = ["pkg-config",]+[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "gethostname",+ "rustix",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]name = "x509-parser"version = "0.16.0"@@ -7264,7 +7475,7 @@ dependencies = ["data-encoding","der-parser","lazy_static",- "nom",+ "nom 7.1.3","oid-registry","rusticata-macros","thiserror 1.0.69",@@ -7494,6 +7705,21 @@ dependencies = ["pkg-config",]+[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]+[[package]]name = "zvariant"version = "5.15.0"diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.jsonindex 4222d3a2..f29afa3d 100644--- a/apps/desktop/package-lock.json+++ b/apps/desktop/package-lock.json@@ -9,6 +9,7 @@"version": "0.2.0","dependencies": {"@tauri-apps/api": "2.11.1",+ "@tauri-apps/plugin-clipboard-manager": "2.3.2","react": "19.2.8","react-dom": "19.2.8"},@@ -301,6 +302,25 @@"url": "https://opencollective.com/tauri"}},+ "node_modules/@tauri-apps/plugin-clipboard-manager": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-clipboard-manager/-/plugin-clipboard-manager-2.3.2.tgz",+ "integrity": "sha512-CUlb5Hqi2oZbcZf4VUyUH53XWPPdtpw43EUpCza5HWZJwxEoDowFzNUDt1tRUXA8Uq+XPn17Ysfptip33sG4eQ==",+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@tauri-apps/api": "^2.8.0"+ }+ },+ "node_modules/@tauri-apps/plugin-clipboard-manager/node_modules/@tauri-apps/api": {+ "version": "2.12.1",+ "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.1.tgz",+ "integrity": "sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==",+ "license": "Apache-2.0 OR MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/tauri"+ }+ },"node_modules/@types/react": {"version": "19.2.14","resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 36675dc6..ca68b157 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -13,13 +13,14 @@},"dependencies": {"@tauri-apps/api": "2.11.1",+ "@tauri-apps/plugin-clipboard-manager": "2.3.2","react": "19.2.8","react-dom": "19.2.8"},"devDependencies": {- "typescript": "7.0.2",- "vite": "8.2.2","@types/react": "19.2.14",- "@types/react-dom": "19.2.3"+ "@types/react-dom": "19.2.3",+ "typescript": "7.0.2",+ "vite": "8.2.2"}}diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 4dd9db5b..8940d43b 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -7,7 +7,7 @@ rust-version.workspace = true[features]default = []-desktop-runtime = ["dep:tauri", "dep:tauri-build", "dep:tauri-plugin-dialog"]+desktop-runtime = ["dep:tauri", "dep:tauri-build", "dep:tauri-plugin-dialog", "dep:tauri-plugin-clipboard-manager"]desktop-pilot = ["desktop-runtime", "dep:tauri-plugin-pilot"][dependencies]@@ -26,6 +26,7 @@ reqwest = { version = "=0.13.4" }sha2.workspace = truetauri = { version = "2.11.1", optional = true }tauri-plugin-dialog = { version = "2.7.3", default-features = false, features = ["xdg-portal"], optional = true }+tauri-plugin-clipboard-manager = { version = "=2.3.2", optional = true }tauri-plugin-pilot = { git = "https://github.com/mpiton/tauri-pilot", rev = "ed31926726b4cd7b3ffbc11f188e046f2b5e0faa", default-features = false, optional = true }[target.'cfg(unix)'.dependencies]diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rsindex bc498b90..4bd9b275 100644--- a/apps/desktop/src-tauri/build.rs+++ b/apps/desktop/src-tauri/build.rs@@ -3,6 +3,9 @@ fn main() {let manifest = match std::env::var_os("HIROUTE_CPA_MANIFEST") {Some(path) => std::path::PathBuf::from(path),None if std::env::var("PROFILE").as_deref() == Ok("debug") => {+ println!(+ "cargo:warning=The default development CPA pin is historical. For current subscriptions, generate CPA and cpa-artifacts.json with scripts/package-desktop.py, then set HIROUTE_CPA_MANIFEST to that manifest and stage its matching binary. See vendor/cpa/README.md."+ );std::path::PathBuf::from("development-cpa-artifacts.v1.json")}None => panic!("release Desktop requires HIROUTE_CPA_MANIFEST from package-desktop.py"),@@ -50,6 +53,7 @@ fn main() {"resolve_web_confirmation","agent_snapshot","preview_agent_settings",+ "retry_agent_settings","check_agent_authentication","worker_settings_get","worker_settings_set",diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.jsonindex 3a56e168..d98eb222 100644--- a/apps/desktop/src-tauri/capabilities/main.json+++ b/apps/desktop/src-tauri/capabilities/main.json@@ -9,6 +9,7 @@"permissions": ["core:window:allow-set-theme","core:window:allow-start-dragging",+ "clipboard-manager:allow-write-text","allow-desktop-snapshot","allow-preview-rename","allow-preview-restore-name",@@ -48,6 +49,7 @@"allow-save-classifier-openapi","allow-agent-snapshot","allow-preview-agent-settings",+ "allow-retry-agent-settings","allow-check-agent-authentication","allow-worker-settings-get","allow-worker-settings-set",diff --git a/apps/desktop/src-tauri/examples/acl_probe.rs b/apps/desktop/src-tauri/examples/acl_probe.rsindex 51bcaebb..d3ecd3f0 100644--- a/apps/desktop/src-tauri/examples/acl_probe.rs+++ b/apps/desktop/src-tauri/examples/acl_probe.rs@@ -13,7 +13,7 @@ use std::{use tauri::Manager;fn main() {- assert!(cfg!(debug_assertions), "development acceptance only");+ const { assert!(cfg!(debug_assertions), "development acceptance only") };let root = std::path::PathBuf::from(std::env::var_os("HIROUTE_DESKTOP_TEST_ROOT").expect("isolated root required"),);diff --git a/apps/desktop/src-tauri/permissions/autogenerated/retry_agent_settings.toml b/apps/desktop/src-tauri/permissions/autogenerated/retry_agent_settings.tomlnew file mode 100644index 00000000..b0758d90--- /dev/null+++ b/apps/desktop/src-tauri/permissions/autogenerated/retry_agent_settings.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-retry-agent-settings"+description = "Enables the retry_agent_settings command without any pre-configured scope."+commands.allow = ["retry_agent_settings"]++[[permission]]+identifier = "deny-retry-agent-settings"+description = "Denies the retry_agent_settings command without any pre-configured scope."+commands.deny = ["retry_agent_settings"]diff --git a/apps/desktop/src-tauri/src/agent_check_session.rs b/apps/desktop/src-tauri/src/agent_check_session.rsindex 4e0d16ee..c117e0f3 100644--- a/apps/desktop/src-tauri/src/agent_check_session.rs+++ b/apps/desktop/src-tauri/src/agent_check_session.rs@@ -274,7 +274,7 @@ impl Session {})}- pub fn begin_agent_check(+ pub(crate) fn begin_agent_check(&mut self,context: AgentCheckConfirmation,accepted: bool,diff --git a/apps/desktop/src-tauri/src/agent_session.rs b/apps/desktop/src-tauri/src/agent_session.rsindex 6b8770de..169ef15b 100644--- a/apps/desktop/src-tauri/src/agent_session.rs+++ b/apps/desktop/src-tauri/src/agent_session.rs@@ -11,6 +11,8 @@ pub struct AgentSettingsInput {}#[derive(Deserialize, Serialize)]pub struct AgentEntry {+ #[serde(default)]+ pub codex_access: Option<Value>,pub agent_id: String,pub version: String,pub configuration_state: String,@@ -303,6 +305,12 @@ impl AgentConfirmation {}}impl Session {+ pub async fn retry_agent_settings(+ &mut self,+ input: hiroute_application_api::AgentSettingsRetryV1,+ ) -> Result<Value, DesktopFailure> {+ query(&self.client, "ApplyAgentConnectionChange", &input).await+ }pub async fn agent_snapshot(&mut self) -> Result<AgentSnapshot, DesktopFailure> {#[derive(Deserialize)]struct Scan {@@ -333,7 +341,8 @@ impl Session {Ok(AgentSnapshot {agents: scan.agents,plans: snapshot.catalog,- trusted_authority: snapshot.trusted_authority && snapshot.service.mutation_available,+ // Peer authority also permits same-operation recovery while new writes are closed.+ trusted_authority: snapshot.trusted_authority,})}@@ -374,10 +383,10 @@ impl Session {.preview_agent_settings_registered(input, candidate.clone()).await;#[cfg(unix)]- if !matches!(&result, Ok(AgentPreparation::Ready(_))) {- if let Some(candidate) = &candidate {- let _ = self.resident.release_model_input(candidate);- }+ if !matches!(&result, Ok(AgentPreparation::Ready(_)))+ && let Some(candidate) = &candidate+ {+ let _ = self.resident.release_model_input(candidate);}result}@@ -599,11 +608,9 @@ impl Session {.as_ref().is_some_and(|view| view.state == "rolled_back"),};- if definitively_failed {- if declaration.removes_resident_service() {- // The rolled-back connection still needs its owned item at the next login.- crate::login_item::compensate_resident_login_item_removal();- }+ if definitively_failed && declaration.removes_resident_service() {+ // The rolled-back connection still needs its owned item at the next login.+ crate::login_item::compensate_resident_login_item_removal();}}let mutation = mutation?;diff --git a/apps/desktop/src-tauri/src/bootstrap.rs b/apps/desktop/src-tauri/src/bootstrap.rsindex 1f465616..ef0a0c14 100644--- a/apps/desktop/src-tauri/src/bootstrap.rs+++ b/apps/desktop/src-tauri/src/bootstrap.rs@@ -148,13 +148,12 @@ impl Resident {.is_none();// A timed-out orderly stop is still in progress. Retrying waits for that child;// its protected channel is no longer usable after shutdown was requested.- if !shutdown_requested {- if !self+ if !shutdown_requested+ && !self.upgrade_status(hiroute_host_runtime::UpgradeAction::Status)?.drained()- {- return Err("UPGRADE_WORK_ACTIVE".into());- }+ {+ return Err("UPGRADE_WORK_ACTIVE".into());}let owned = self.owned.as_mut().ok_or("UPGRADE_RESIDENT_NOT_OWNED")?;drop(owned.shutdown.take());diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rsindex eb63836b..c06c1ebb 100644--- a/apps/desktop/src-tauri/src/bridge.rs+++ b/apps/desktop/src-tauri/src/bridge.rs@@ -18,6 +18,7 @@ use hiroute_diagnostics::event::{ConfirmationPhase, DiagnosticEvent, PreviewEvent, PreviewPhase,};use hiroute_diagnostics::identity::CorrelationToken;+use serde_json::Value;use std::sync::{Arc,atomic::{AtomicU64, Ordering},@@ -352,7 +353,7 @@ enum NativeOutcome {Agent(Box<AgentOutcome>),Check(AgentCheckCompletion),ModelSave(ModelSaveAccepted),- SubscriptionCheck(hiroute_application_api::ComputeSubscriptionCheckResultV2),+ SubscriptionCheck(Box<hiroute_application_api::ComputeSubscriptionCheckResultV2>),}impl NativeOutcome {fn mutation(self) -> Result<MutationOutcome, DesktopFailure> {@@ -477,6 +478,22 @@ pub async fn agent_snapshot(.await}#[tauri::command]+pub async fn retry_agent_settings(+ window: WebviewWindow,+ state: State<'_, DesktopState>,+ input: hiroute_application_api::AgentSettingsRetryV1,+) -> Result<Value, DesktopFailure> {+ main_window(&window)?;+ state+ .0+ .lock()+ .await+ .as_mut()+ .ok_or("RESIDENT_UNAVAILABLE")?+ .retry_agent_settings(input)+ .await+}+#[tauri::command]pub async fn preview_agent_settings(window: WebviewWindow,state: State<'_, DesktopState>,@@ -705,6 +722,7 @@ async fn confirm(.ok_or("RESIDENT_UNAVAILABLE")?.finish_subscription_check_confirmation(completion).await+ .map(Box::new).map(NativeOutcome::SubscriptionCheck)} else if let NativeConfirmation::Check(context) = context {let dispatch = {@@ -821,7 +839,9 @@ pub fn run() {// An explicit background start runs the same Resident initialization and recovery chain;// only the window presentation differs.let background = std::env::args().any(|argument| argument == "--background");- let builder = tauri::Builder::default().plugin(tauri_plugin_dialog::init());+ let builder = tauri::Builder::default()+ .plugin(tauri_plugin_dialog::init())+ .plugin(tauri_plugin_clipboard_manager::init());#[cfg(all(feature = "desktop-pilot", debug_assertions))]let builder = builder.plugin(tauri_plugin_pilot::init());let app = builder@@ -993,6 +1013,7 @@ pub fn run() {resolve_web_confirmation,agent_snapshot,preview_agent_settings,+ retry_agent_settings,check_agent_authentication,check_agent_live,worker_settings_get,diff --git a/apps/desktop/src-tauri/src/bridge/model_connections.rs b/apps/desktop/src-tauri/src/bridge/model_connections.rsindex 8ba4acf1..f5f812ce 100644--- a/apps/desktop/src-tauri/src/bridge/model_connections.rs+++ b/apps/desktop/src-tauri/src/bridge/model_connections.rs@@ -103,7 +103,7 @@ pub async fn check_subscription().await?{- NativeOutcome::SubscriptionCheck(result) => Ok(result.into()),+ NativeOutcome::SubscriptionCheck(result) => Ok((*result).into()),_ => unreachable!(),}}diff --git a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rsindex 5184364d..2c857eab 100644--- a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs+++ b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs@@ -61,6 +61,23 @@ const HOST_SETTINGS_COMMANDS: &[&str] = &["gateway_listener_recover",];+#[test]+fn native_clipboard_exposes_only_text_writes_in_the_local_main_window() {+ let capability: serde_json::Value =+ serde_json::from_str(include_str!("../capabilities/main.json")).unwrap();+ assert_eq!(capability["local"], true);+ assert_eq!(capability["windows"], serde_json::json!(["main"]));+ assert!(capability.get("remote").is_none());+ let clipboard: Vec<_> = capability["permissions"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|value| value.as_str())+ .filter(|permission| permission.starts_with("clipboard-manager:"))+ .collect();+ assert_eq!(clipboard, ["clipboard-manager:allow-write-text"]);+}+#[test]fn action_results_and_failures_classify_without_business_text() {use crate::failure::DesktopFailure;@@ -196,3 +213,8 @@ fn worker_task_commands_are_exposed_to_the_main_window() {fn the_explicit_quit_command_is_exposed_to_the_main_window() {assert_commands(&["quit_desktop"]);}++#[test]+fn profile_restore_retry_is_limited_to_the_main_window_capability() {+ assert_commands(&["retry_agent_settings"]);+}diff --git a/apps/desktop/src-tauri/src/duplicate_host.rs b/apps/desktop/src-tauri/src/duplicate_host.rsindex c17aa3a4..d8fa5ae0 100644--- a/apps/desktop/src-tauri/src/duplicate_host.rs+++ b/apps/desktop/src-tauri/src/duplicate_host.rs@@ -6,9 +6,7 @@ use tauri::AppHandle;/// formal bundle hands the reopen to the operating system; every other duplicate just/// reports the existing instance without claiming anything about its service health.pub(crate) fn duplicate_exit(background: bool, formal_bundle: bool, handed_off: bool) -> i32 {- if background {- 0- } else if formal_bundle && handed_off {+ if background || (formal_bundle && handed_off) {0} else {1diff --git a/apps/desktop/src-tauri/src/gateway_address.rs b/apps/desktop/src-tauri/src/gateway_address.rsindex cba83b82..dd27eb3d 100644--- a/apps/desktop/src-tauri/src/gateway_address.rs+++ b/apps/desktop/src-tauri/src/gateway_address.rs@@ -3,11 +3,12 @@use std::net::SocketAddr;use std::path::{Path, PathBuf};-pub(crate) use hiroute_host_runtime::{- GatewayListenerConfigV1, GatewayListenerDesiredV1, GatewayPortModeV1,-};+#[cfg(test)]+pub(crate) use hiroute_host_runtime::GatewayPortModeV1;+pub(crate) use hiroute_host_runtime::{GatewayListenerConfigV1, GatewayListenerDesiredV1};use hiroute_host_runtime::{GatewayListenerReservation, GatewayListenerStore};+#[cfg(test)]pub(crate) fn path(root: &Path) -> PathBuf {GatewayListenerStore::new(root).path()}diff --git a/apps/desktop/src-tauri/src/login_item.rs b/apps/desktop/src-tauri/src/login_item.rsindex 42a264ff..dc259940 100644--- a/apps/desktop/src-tauri/src/login_item.rs+++ b/apps/desktop/src-tauri/src/login_item.rs@@ -4,9 +4,6 @@//! journaled ownership evidence; a pre-existing user login item is never touched.use hiroute_application_api::AgentLoginItemDeclarationV2;-#[cfg(target_os = "macos")]-use hiroute_application_api::AgentLoginItemStatusV2;-const SERVICE_UNAVAILABLE: &str = "SERVICE_UNAVAILABLE";/// Unregisters the login item this feature owns when the last managed connection is restored.diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rsindex 60c1fc44..cd0aca95 100644--- a/apps/desktop/src-tauri/src/updates.rs+++ b/apps/desktop/src-tauri/src/updates.rs@@ -20,7 +20,6 @@ struct PreparedUpdate {release: DesktopRelease,current: PathBuf,staged: PathBuf,- stage_root: PathBuf,download_root: PathBuf,old_identity: DesktopPackageIdentity,new_identity: DesktopPackageIdentity,diff --git a/apps/desktop/src-tauri/src/updates/download.rs b/apps/desktop/src-tauri/src/updates/download.rsindex d60ef7ad..1d714069 100644--- a/apps/desktop/src-tauri/src/updates/download.rs+++ b/apps/desktop/src-tauri/src/updates/download.rs@@ -4,14 +4,7 @@ use hiroute_host_runtime::{DesktopRelease, MAX_RELEASE_FEED_BYTES, RELEASE_FEED, WebsiteReleasesV2, verify_desktop_app,};use sha2::{Digest, Sha256};-use std::{- fs,- io::Write,- path::{Path, PathBuf},- process::Command,- sync::atomic::Ordering,- time::Duration,-};+use std::{fs, io::Write, path::Path, process::Command, sync::atomic::Ordering, time::Duration};fn url(production: &str) -> Result<String, String> {#[cfg(all(feature = "desktop-pilot", debug_assertions))]@@ -163,7 +156,6 @@ pub(super) async fn prepare(release,current: app,staged,- stage_root: stage_root.clone(),download_root: download_root.clone(),old_identity,new_identity,@@ -222,7 +214,7 @@ fn stage_dmg(.into_iter().collect()|| fs::read_link(mount.join("Applications")).map_err(|_| "UPGRADE_DMG_INVALID")?- != PathBuf::from("/Applications")+ != Path::new("/Applications"){return Err("UPGRADE_DMG_INVALID".into());}diff --git a/apps/desktop/src/agent-capability-preview.tsx b/apps/desktop/src/agent-capability-preview.tsxdeleted file mode 100644index 2efb9f54..00000000--- a/apps/desktop/src/agent-capability-preview.tsx+++ /dev/null@@ -1,28 +0,0 @@-import React, { useEffect, useState } from 'react';-import { invoke } from '@tauri-apps/api/core';-import { type Plan, type Options } from './plan-editor';--/** Read-only projection; saving still rechecks the exact publication and native configuration. */-export function AgentCapabilityPreview({ agent, plans, language }: { agent: 'codex' | 'claude'; plans: Plan[]; language: 'zh' | 'en' }) {- const [result, setResult] = useState<Options[] | null>(null);- const [failed, setFailed] = useState(false);- const fingerprint = JSON.stringify(plans);- useEffect(() => {- let current = true;- setResult(null); setFailed(false);- const selected = JSON.parse(fingerprint) as Plan[];- void Promise.all(selected.map(plan => invoke<Options>('plan_editor_options', { input: { published_plan: { plan_id: plan.agent_plan_id, revision: plan.agent_plan_revision } } }))).then(value => { if (current) setResult(value); }).catch(() => { if (current) setFailed(true); });- return () => { current = false; };- }, [fingerprint]);- if (!plans.length) return null;- const text = (zh: string, en: string) => language === 'zh' ? zh : en;- const windows = result?.map(option => agent === 'codex' ? option.codex_capabilities?.state === 'available' ? option.codex_capabilities.context_window : null : option.claude_capabilities?.state === 'available' ? option.claude_capabilities.context_window : null);- return <div className="option-panel" data-agent-capability-preview={agent} aria-live="polite">- <strong>{agent === 'codex' ? 'Codex' : 'Claude Code'} · {text('能力预览', 'Capability preview')}</strong>- {failed ? <p>{text('暂时无法获取能力预览;请重新打开配置重试。', 'Capability preview is unavailable. Reopen settings to retry.')}</p> : !result ? <p>{text('正在核对所选计划…', 'Checking selected plans…')}</p> : <>- {plans.map((plan, index) => <p key={plan.agent_plan_id}>{plan.desired.display_name} · {windows?.[index] != null ? `${windows[index]!.toLocaleString()} tokens` : text('当前不可用,请检查计划的入口能力和窗口', 'Unavailable; check plan ingress capabilities and window')}</p>)}- {agent === 'claude' && windows?.every(value => value != null) && <p>{text('进程共同自动压缩窗口', 'Shared process auto-compact window')} · {Math.min(...windows as number[]).toLocaleString()} tokens</p>}- </>}- <p className="field-help">{agent === 'claude' ? text('三个预设共享最小窗口(100K–1M);保留的原生模型可能更早压缩。', 'The three presets share the smallest window (100K–1M); preserved native models may compact earlier.') : text('各计划分别使用自己的窗口。', 'Each plan uses its own window.')}{text('保存时重新核对;重新启动客户端后加载,当前会话不会立即改变。', 'Rechecked on save and loaded after restarting the client; current sessions do not change immediately.')}</p>- </div>;-}diff --git a/apps/desktop/src/agent-editor-state.ts b/apps/desktop/src/agent-editor-state.tsindex 29a5fedf..d7e5db4b 100644--- a/apps/desktop/src/agent-editor-state.ts+++ b/apps/desktop/src/agent-editor-state.ts@@ -53,6 +53,7 @@ export function codexDefaultChoiceValid(export function agentEditorSeed(agent: Agent,facet: 'model' | 'collaboration',+ availablePlanIds: string[] = [],): AgentEditorValues & { known: boolean } {const status = facet === 'model' ? agent.settings : agent.settings?.collaboration;const selection = status?.current_selection;@@ -66,19 +67,35 @@ export function agentEditorSeed(&& 'trigger_mode' in selection? selection: undefined;+ const initialPlan = facet === 'model' && initial && known && !currentModel && availablePlanIds.length === 1+ ? availablePlanIds[0] : undefined;return {known: facet === 'model'? known && (initial || (agent.agent_id === 'agent_codex_default' ? !!codex : !!claude)): known,fixedModels: currentModel?.fixed_models ?? [],nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',- allowedPlanIds: codex?.allowed_plan_ids ?? [],- defaultChoice: codex?.default_selection ?? { kind: 'preserve_native' },+ allowedPlanIds: codex?.allowed_plan_ids ?? (initialPlan && agent.agent_id === 'agent_codex_default' ? [initialPlan] : []),+ defaultChoice: codex?.default_selection ?? (initialPlan && agent.agent_id === 'agent_codex_default'+ ? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),claudePresets: claude?.preset_mappings ?? {- opus: preserve(),- sonnet: preserve(),- haiku: preserve(),+ opus: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),+ sonnet: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),+ haiku: initialPlan && agent.agent_id === 'agent_claude_default' ? { kind: 'plan', plan_id: initialPlan } : preserve(),},triggerMode: collaboration?.trigger_mode ?? 'explicit',};}++export function commonClaudePlan(mappings: AgentClaudePresetMappings): string | null {+ const ids = Object.values(mappings).map(choice => choice.kind === 'plan' ? choice.plan_id : '');+ return ids.every(id => id === ids[0]) ? ids[0] : null;+}++export function sharedClaudePlan(planId: string): AgentClaudePresetMappings {+ return {+ opus: { kind: 'plan', plan_id: planId },+ sonnet: { kind: 'plan', plan_id: planId },+ haiku: { kind: 'plan', plan_id: planId },+ };+}diff --git a/apps/desktop/src/agent-mutation-feedback.ts b/apps/desktop/src/agent-mutation-feedback.tsindex ab8713d1..5eb4c8a7 100644--- a/apps/desktop/src/agent-mutation-feedback.ts+++ b/apps/desktop/src/agent-mutation-feedback.ts@@ -20,6 +20,20 @@ export function classifyAgentMutation(return 'unverified';}+export function agentDisableMessage(state: string, language: 'zh' | 'en'): string {+ const zh = language === 'zh';+ if (state === 'succeeded') return zh+ ? '模型配置已恢复,连接已停用。'+ : 'Model settings restored; the connection is disabled.';+ if (state === 'rolled_back') return zh+ ? '停用未完成,本次变更已回滚,原连接仍有效。请处理冲突或失败原因后重新点击“停用”。'+ : 'Disable did not complete. This change was rolled back; the original connection remains active. Resolve the conflict or failure, then click Disable again.';+ if (state === 'needs_attention') return zh+ ? '停用未完成,回滚尚未确认。请查看操作状态并处理恢复问题。'+ : 'Disable did not complete and rollback is unconfirmed. Check the operation status and resolve the recovery issue.';+ return zh ? '正在恢复模型配置并停用连接…' : 'Restoring model settings and disabling the connection…';+}+export function agentActionErrorMessage(code: string, language: 'zh' | 'en'): string {const zh = language === 'zh';if (code === 'AGENT_TOKEN_INVALID') return zhdiff --git a/apps/desktop/src/agents.tsx b/apps/desktop/src/agents.tsxindex e9c177b1..3e5a4266 100644--- a/apps/desktop/src/agents.tsx+++ b/apps/desktop/src/agents.tsx@@ -1,10 +1,14 @@-import { AgentCapabilityPreview } from './agent-capability-preview';-import { BrandIcon, Dialog, Disclosure, ProductPage, UiIcon } from './ui';+import { CodexAccessPanel, CodexAccessSettings, type CodexAccess } from './features/agents/CodexAccessPanel';+import { confirmedCodexLaunchCommand, type PendingCodexLaunchCopy } from './features/agents/codex-launch';+import { codexSurfaceFacts } from './features/agents/codex-surfaces';+import { BrandIcon, Dialog, Disclosure, ProductPage, UiIcon, copyText } from './ui';import { confirmDiscard, useDiscardGuard } from './ui/discard-guard';import React, { useEffect, useRef, useState } from 'react';import { invoke } from '@tauri-apps/api/core';import {agentEditorSeed,+ commonClaudePlan,+ sharedClaudePlan,codexDefaultChoiceValid,editorFingerprint,type AgentClaudePresetMappings,@@ -19,6 +23,7 @@ import type { OperationReference } from './features/model-connections/types';import { safeDiagnosticCode } from './error-code';import {agentActionErrorMessage,+ agentDisableMessage,classifyAgentMutation,type AgentMutationOutcome,} from './agent-mutation-feedback';@@ -98,6 +103,7 @@ export type ModelStatus = {collaboration?: CollaborationStatus | null;};export type Agent = {+ codex_access?: CodexAccess | null;agent_id: string;version: string;context_id: string | null;@@ -157,6 +163,7 @@ export function Agents({language,onMutation,onOperation,+ operation = null,onUnverifiedOperation,initialAgentId = null,initialFacet = 'model',@@ -177,6 +184,7 @@ export function Agents({language: 'zh' | 'en';onMutation: () => void;onOperation?: (operation: OperationReference, presentation: { kind: 'agent-settings'; target: string }) => void;+ operation?: OperationReference | null;onUnverifiedOperation?: (presentation: { kind: 'agent-settings'; target: string }) => void;initialAgentId?: string | null;initialFacet?: Facet;@@ -205,6 +213,7 @@ export function Agents({const [tokenEditing, setTokenEditing] = useState(false);const [tokenDraft, setTokenDraft] = useState('');const [selectedAgent, setSelectedAgent] = useState<string | null>(initialAgentId);+ const [codexMode, setCodexMode] = useState<'profile' | 'root'>('profile');const [showAgentList, setShowAgentList] = useState(false);const [tab, setTab] = useState<'configuration' | 'tasks'>(initialTab);const agentName = (agent: Agent) => agent.agent_id === 'agent_codex_default'@@ -218,11 +227,12 @@ export function Agents({const [editorValues, setEditorValues] = useState<AgentEditorValues>(EMPTY_EDITOR_VALUES);const [restoreNativeModel, setRestoreNativeModel] = useState('');const [selectionKnown, setSelectionKnown] = useState(false);- const [facetEnabled, setFacetEnabled] = useState(false);- const [baselineEnabled, setBaselineEnabled] = useState(false);+ const [baselineCodexMode, setBaselineCodexMode] = useState<'profile' | 'root'>('profile');+ const [pendingLaunchCopy, setPendingLaunchCopy] = useState<PendingCodexLaunchCopy | null>(null);+ const [pendingDisable, setPendingDisable] = useState<string | null>(null);const [baseline, setBaseline] = useState('');const fingerprint = editorFingerprint(editorValues);- const dirty = !!editor && (fingerprint !== baseline || facetEnabled !== baselineEnabled);+ const dirty = !!editor && (fingerprint !== baseline || codexMode !== baselineCodexMode);useDiscardGuard('agents', dirty, language, confirmEditorReplacement);const queryGeneration = useRef(0);const [preview, setPreview] = useState<Preview | null>(null);@@ -245,6 +255,35 @@ export function Agents({useEffect(() => {void refresh();}, [refreshVersion]);+ useEffect(() => {+ if (!pendingLaunchCopy || operation?.operation_id !== pendingLaunchCopy.operationId) return;+ if (['failed', 'cancelled', 'compensated'].includes(operation.state)) { setPendingLaunchCopy(null); return; }+ if (operation.state !== 'succeeded') return;+ let cancelled = false;+ const target = pendingLaunchCopy;+ void (async () => {+ try {+ const current = await invoke<AgentSnapshot>('agent_snapshot');+ if (cancelled) return;+ const command = confirmedCodexLaunchCommand(target, operation, current.agents.find(agent => agent.agent_id === 'agent_codex_default'), navigator.platform);+ if (!command) { setPendingLaunchCopy(null); setNotice(text('保存已完成,请在启动区域重新读取并复制命令。', 'Save completed. Read and copy the command in the launch section.')); return; }+ await copyText(command);+ if (!cancelled) { setPendingLaunchCopy(null); setNotice(text('启动命令已复制,粘贴到终端即可使用。', 'Launch command copied. Paste it into a terminal to start.')); }+ } catch {+ if (!cancelled) {+ setPendingLaunchCopy(null);+ setNotice(text('保存已完成,自动复制失败。请使用“复制启动命令”或手动复制。', 'Save completed, but automatic copy failed. Use Copy launch command or copy it manually.'));+ }+ }+ })();+ return () => { cancelled = true; };+ }, [pendingLaunchCopy, operation]);+ useEffect(() => {+ if (pendingDisable && operation?.operation_id === pendingDisable) {+ setNotice(agentDisableMessage(operation.state, language));+ if (['succeeded', 'rolled_back', 'needs_attention'].includes(operation.state)) setPendingDisable(null);+ }+ }, [pendingDisable, operation, language]);useEffect(() => {if (editor) firstField.current?.focus();}, [editor]);@@ -295,12 +334,13 @@ export function Agents({setTokenDraft('');setSelectedAgent(agent.agent_id);setEditor({ context: agent.context_id, facet });- const { known, ...seed } = agentEditorSeed(agent, facet);+ const { known, ...seed } = agentEditorSeed(agent, facet, enabledPlans.map(plan => plan.agent_plan_id));setSelectionKnown(known);setEditorValues(seed);- const enabled = facet === 'model' ? Boolean(agent.settings?.current_selection) : Boolean(agent.settings?.collaboration?.current_selection);- setFacetEnabled(enabled);- setBaselineEnabled(enabled);+ const mode = agent.codex_access?.slot_occupied ? agent.codex_access.selected_mode : 'profile';+ setCodexMode(mode);+ setBaselineCodexMode(mode);+ setPendingLaunchCopy(null);setBaseline(editorFingerprint(seed));}function spec(agent: Agent, facet: Facet, restore: boolean) {@@ -323,8 +363,10 @@ export function Agents({};return {schema_version: { major: 2, minor: 0 },- context_id: agent.context_id,- restore_native_model: restore && agent.agent_id === 'agent_codex_default' && restoreNativeModel+ context_id: agent.codex_access && !agent.codex_access.slot_occupied+ ? (codexMode === 'root' ? agent.codex_access.root_context_id : agent.codex_access.profile_context_id)+ : agent.context_id,+ restore_native_model: restore && agent.agent_id === 'agent_codex_default' && agent.codex_access?.selected_mode !== 'profile' && restoreNativeModel? restoreNativeModel : undefined,model: restore? { intent: 'restore', restore_point_ref: agent.settings?.restore_point_ref }@@ -335,7 +377,7 @@ export function Agents({return {schema_version: { major: 2, minor: 0 },- context_id: agent.context_id,+ context_id: agent.codex_access?.root_context_id ?? agent.context_id,model: keep,collaboration: restore? {@@ -388,13 +430,19 @@ export function Agents({? text('已取消,未提交变更。', 'Cancelled before submission.'): '');if (result.mutation.operation) {+ if (restore && facet === 'model') {+ setNotice(agentDisableMessage(result.mutation.operation.state, language));+ if (!['succeeded', 'rolled_back', 'needs_attention'].includes(result.mutation.operation.state)) setPendingDisable(result.mutation.operation.operation_id);+ }+ if (!restore && facet === 'model' && agent.codex_access && activeCodexMode === 'profile' && !agent.settings?.current_selection) {+ setPendingLaunchCopy({ operationId: result.mutation.operation.operation_id, contextId: input.spec.context_id });+ }onOperation?.(result.mutation.operation, presentation);} else if (disposition === 'unverified') {onUnverifiedOperation?.(presentation);}if (disposition === 'submitted') {setBaseline(fingerprint);- setBaselineEnabled(facetEnabled);setEditor(null);}onMutation();@@ -653,13 +701,14 @@ export function Agents({const selectedExecutableDiagnostic = selected? executableDiagnostic(selected.configuration_state): null;- const disableRestoreAvailable = editor?.facet === 'model'- ? Boolean(selected?.settings?.restore_point_ref)- : Boolean(selected?.settings?.collaboration?.restore_point_ref);const selectedPlansEnabled = editorValues.allowedPlanIds.every(id => enabledPlans.some(plan => plan.agent_plan_id === id));const defaultChoice = editorValues.defaultChoice;- const detectedCodexSurfaces = new Set<AgentModelSurface>((selected?.available_surfaces ?? [])- .filter(surface => surface === 'codex_cli' || surface === 'codex_desktop'));+ const activeCodexMode = selected?.codex_access?.slot_occupied+ ? selected.codex_access.selected_mode : codexMode;+ const codexSurfaces = codexSurfaceFacts(activeCodexMode, selected?.available_surfaces ?? []);+ const verificationSurfaces = (selected?.available_surfaces ?? []).filter(surface =>+ selected?.agent_id !== 'agent_codex_default'+ || codexSurfaces.some(fact => fact.surface === surface && fact.applicable));const catalogModels = (selected?.native_model_catalog?.models ?? []).map(model => ({ ...model, source_options: model.source_options ?? [] }));const nativeRestoreOptions = catalogModels.filter(model =>@@ -704,9 +753,17 @@ export function Agents({|| !codexDefaultValid: claudePlanIds.length + editorValues.fixedModels.length === 0|| claudePlanIds.some(id => !enabledPlans.some(plan => plan.agent_plan_id === id));- const formInvalid = facetEnabled- ? !selectionKnown || (editor?.facet === 'model' && modelFormInvalid)- : !disableRestoreAvailable;+ const formInvalid = !selectionKnown || (editor?.facet === 'model' && modelFormInvalid);+ const claudeSharedPlan = commonClaudePlan(editorValues.claudePresets);+ const creatingModelConnection = editor?.facet === 'model' && !modelSelection;+ const showCodexDefault = editorValues.nativeModelMode === 'preserve_available'+ || editorValues.fixedModels.length > 0 || editorValues.allowedPlanIds.length > 1;+ const submitLabel = creatingModelConnection+ ? selected?.agent_id === 'agent_codex_default' && activeCodexMode === 'profile'+ ? text('启用并复制启动命令', 'Enable and copy launch command')+ : text('启用模型路由', 'Enable model routing')+ : editor?.facet === 'collaboration' && !taskSelection+ ? text('启用任务路由', 'Enable task routing') : text('保存配置', 'Save settings');const brand = (agent: Agent) => agent.agent_id === 'agent_codex_default' ? 'codex' : agent.agent_id === 'agent_claude_default' ? 'claude-code' : 'agent';const planName = (id: string) => plans.find(plan => plan.agent_plan_id === id)?.desired.display_name;@@ -743,6 +800,7 @@ export function Agents({}return <label className="field"><span className="field-label">{text('思考预算', 'Reasoning budget')}</span><input className="input" type="number" min={reasoning.minimum_tokens} max={reasoning.maximum_tokens} step={reasoning.step_tokens} value={selection?.kind === 'budget' ? selection.tokens : ''} onChange={event => setFixedReasoning(model.client_model_id, { kind: 'budget', tokens: Number(event.target.value) })} /><span className="field-help">{reasoning.minimum_tokens}–{reasoning.maximum_tokens} tokens</span></label>;};+ const savedClaudeSharedPlan = modelSelection?.mode === 'claude_launcher' ? commonClaudePlan(modelSelection.preset_mappings) : null;const modelSelectionSummary = modelSelection?.mode === 'codex_default'? modelSelection.default_selection.kind === 'plan'? planName(modelSelection.default_selection.plan_id) ?? text('当前路由不可用', 'Current route unavailable')@@ -750,7 +808,9 @@ export function Agents({? modelSelection.default_selection.client_model_id: text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name'): modelSelection- ? text('Opus、Sonnet、Haiku 分别映射', 'Separate Opus, Sonnet, and Haiku mappings')+ ? savedClaudeSharedPlan+ ? text('三个档位共用:', 'All presets use: ') + (planName(savedClaudeSharedPlan) ?? text('当前路由不可用', 'Current route unavailable'))+ : Object.entries(modelSelection.preset_mappings).map(([preset, choice]) => `${preset[0].toUpperCase() + preset.slice(1)}: ${choice.kind === 'plan' ? planName(choice.plan_id) ?? text('当前路由不可用', 'Current route unavailable') : text('保留原生', 'Native')}`).join(' · '): '';const blockedCheckScope = preview && editor && selected? prerequisiteCheck(preview, editor.facet, selected)@@ -847,16 +907,26 @@ export function Agents({<div className="oc-model-back"><button className="btn btn-quiet" type="button" onClick={() => setShowAgentList(true)}><UiIcon name="arrowLeft" />{text('返回 Agent 列表', 'Back to Agents')}</button></div>{selected && snapshot && <div className="detail-inner" data-agent-id={selected.agent_id}><header className="detail-hero"><div className="detail-identity"><BrandIcon kind={brand(selected)} label={`${agentName(selected)} logo`} /><div><h2>{agentName(selected)}</h2><p>{text('选择你需要的路由能力', 'Choose the routing capabilities you need')}</p></div></div></header>- {!mutable && <div className="callout warn"><UiIcon name="warning" /><div><strong>{text('Agent 配置可以查看,暂时不能修改', 'Agent settings are viewable but cannot be changed')}</strong><p>{text('本机服务尚未就绪,连接恢复后即可保存配置。', 'The local service is not ready. Reconnect before saving.')}</p></div></div>}+ {!mutable && !selected.codex_access?.pending_operation && <div className="callout warn"><UiIcon name="warning" /><div><strong>{text('Agent 配置可以查看,暂时不能修改', 'Agent settings are viewable but cannot be changed')}</strong><p>{text('本机服务尚未就绪,连接恢复后即可保存配置。', 'The local service is not ready. Reconnect before saving.')}</p></div></div>}+ {selected.codex_access && <CodexAccessPanel access={selected.codex_access} language={language} retryDisabled={busy || Boolean(editor) || !snapshot.trusted_authority} onRetry={async () => {+ const access = selected.codex_access;+ if (!access?.pending_operation || !selected.context_id || busy) return;+ setBusy(true); setActionError('');+ try {+ await invoke('retry_agent_settings', { input: { schema: 'hiroute.agent-settings-retry/v1', context_id: selected.context_id, operation_id: access.pending_operation } });+ await refresh();+ } catch (error) { setActionError(desktopErrorCode(error)); }+ finally { onMutation(); setBusy(false); }+ }} />}{selected.status_error && <div className="callout warn" data-error-code={selected.status_error}><UiIcon name="warning" /><div><strong>{text('暂时无法核实 Agent 状态', 'Agent status is temporarily unavailable')}</strong><p>{text('当前仍显示已发现的 Agent;重新读取成功前不会把未知状态当作已接入。', 'The detected Agent remains visible. Unknown status is not treated as connected until it can be read again.')}</p><button className="btn" type="button" onClick={() => void refresh()}>{text('重新读取', 'Try again')}</button></div></div>}{executableStatus}{selectedHasDrift && <div className="callout warn"><UiIcon name="warning" /><div><strong>{text('接入配置已变化', 'Connection settings changed')}</strong><p>{text('HiRoute 不会覆盖已变化的设置。请在“连接详情与恢复”中恢复需要的路由配置。', 'HiRoute will not overwrite changed settings. Restore the required routing configuration under Connection details and recovery.')}</p></div></div>}- {selectedPending && <div className="oc-status-row" role="status"><span className="oc-spinner" /><p>{text('路由配置正在应用,完成后会自动更新。', 'Routing settings are being applied and will update automatically.')}</p></div>}+ {selectedPending && !selected.codex_access?.pending_operation && <div className="oc-status-row" role="status"><span className="oc-spinner" /><p>{text('路由配置正在应用,完成后会自动更新。', 'Routing settings are being applied and will update automatically.')}</p></div>}<section className="detail-section v3-agent-section">- <div className="detail-section-head"><h3>{text('模型路由', 'Model routing')}</h3><button className="btn btn-quiet" data-agent-facet="model" disabled={busy || !selected.context_id || !mutable} onClick={event => open(selected, 'model', event.currentTarget)}>{modelSelection ? text('调整', 'Edit') : text('启用', 'Enable')}</button></div>+ <div className="detail-section-head"><h3>{text('模型路由', 'Model routing')}</h3><button className="btn btn-quiet" data-agent-facet="model" disabled={busy || selectedPending || !selected.context_id || !mutable} onClick={event => open(selected, 'model', event.currentTarget)}>{modelSelection ? text('调整', 'Edit') : text('启用', 'Enable')}</button>{selected.settings?.restore_point_ref && <button className="btn btn-quiet" disabled={busy || selectedPending || !mutable} onClick={event => void change(selected, 'model', true, event.currentTarget)}>{text('停用', 'Disable')}</button>}</div><p>{modelSelection ? <>{text('当前选择:', 'Current selection: ')}<strong>{modelSelectionSummary}</strong></> : text('为此 Agent 配置固定模型,或通过智能路由自动选择模型。', 'Configure a fixed model for this Agent, or use smart routing to choose a model automatically.')}</p>- {modelSelection && (selected.available_surfaces ?? []).length > 0 && <div className="agent-surface-results" aria-label={text('当前客户端验证结果', 'Current client verification results')}>- {selected.available_surfaces?.map(surface => {+ {modelSelection && verificationSurfaces.length > 0 && <div className="agent-surface-results" aria-label={text('当前客户端验证结果', 'Current client verification results')}>+ {verificationSurfaces.map(surface => {const revision = selected.settings?.applied_revision;const result = selected.settings?.surface_results?.find(item => item.surface === surface && item.applied_revision === revision);const state = selected.settings?.state === 'configured' && !selected.status_error && revision != null@@ -883,26 +953,34 @@ export function Agents({: text('让此 Agent 将任务交给合适的执行 Agent,并获取结果。', 'Let this Agent delegate work to a suitable execution Agent and retrieve the results.')}</p><p className="field-help">{text('启用后,可在对话中说:“使用 HiRoute,将当前任务委派给【路由名称】执行。”路由名称见“智能路由”,也可让 Agent 选择合适的路由。', 'After enabling, ask in conversation: “Use HiRoute to delegate this task to [route name].” Find route names under Smart routing, or ask the Agent to choose a suitable route.')}</p></section>- <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selected.settings?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selected.settings?.restore_point_ref && selected.agent_id === 'agent_codex_default' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selected.settings?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selected.settings?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selected.settings?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'model', true, event.currentTarget)}>{text('恢复模型设置', 'Restore model settings')}</button>}{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>+ <Disclosure className="native-details" label={text('连接详情与恢复', 'Connection details and recovery')} language={language}><dl>{selected.version && <div><dt>{text('版本', 'Version')}</dt><dd>{selected.version}</dd></div>}{selected.settings?.state === 'configured' && modelSelection && <div><dt>{text('本机接入令牌', 'Local access token')}</dt><dd><input className="input" type="password" value="••••••••••••••••" readOnly aria-label={text('当前令牌已隐藏', 'Current token hidden')} /></dd></div>}</dl>{selected.settings?.restore_point_ref && selected.agent_id === 'agent_codex_default' && selected.codex_access?.selected_mode !== 'profile' && <label className="field-label">{text('恢复时选择原生模型(可选)', 'Native model on restore (optional)')}<input list="codex-native-restore-models" value={restoreNativeModel} onChange={event => { setRestoreNativeModel(event.target.value); setPreview(null); }} placeholder={text('保留原设置', 'Keep original setting')} disabled={busy || !mutable} /><datalist id="codex-native-restore-models">{nativeRestoreOptions.map(model => <option key={model.client_model_id} value={model.client_model_id}>{model.display_name}</option>)}</datalist></label>}{selected.settings?.state === 'configured' && modelSelection && <div className="actions" data-agent-token-controls><button className="btn" disabled={busy || !mutable} onClick={() => { setTokenEditing(true); setTokenDraft(''); setActionError(''); }}>{text('修改令牌', 'Change token')}</button><button className="btn" disabled={busy || !mutable} onClick={event => void changeToken(selected, true, event.currentTarget)}>{text('重新生成', 'Regenerate')}</button></div>}{tokenEditing && selected.settings?.state === 'configured' && modelSelection && <form className="agent-token-form" onSubmit={event => { event.preventDefault(); void changeToken(selected, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><label className="field"><span className="field-label">{text('新令牌', 'New token')}</span><input className="input" type="password" autoComplete="new-password" value={tokenDraft} onChange={event => setTokenDraft(event.target.value)} minLength={16} maxLength={128} pattern="[A-Za-z0-9._~\\-]{16,128}" required disabled={busy} /><span className="field-help">{text('16–128 位英文字母、数字及 . _ ~ -;保存后原令牌立即失效,无需重新接入。', 'Use 16–128 letters, numbers, or . _ ~ -. The old token stops working after save; reconnecting is unnecessary.')}</span></label><div className="actions"><button className="btn btn-primary" type="submit" disabled={busy || !mutable}>{text('保存令牌', 'Save token')}</button><button className="btn" type="button" disabled={busy} onClick={() => { setTokenEditing(false); setTokenDraft(''); }}>{text('取消', 'Cancel')}</button></div></form>}<div className="actions">{selectedCollaboration?.restore_point_ref && <button className="btn" disabled={busy || !mutable} onClick={event => void change(selected, 'collaboration', true, event.currentTarget)}>{text('停用任务路由', 'Disable task routing')}</button>}</div></Disclosure>{!editor && loadError && <div className="callout warn agent-feedback agent-inline-feedback" role="alert" data-error-code={loadError}><UiIcon name="warning" /><div><strong>{text('状态刷新失败', 'Status refresh failed')}</strong><p>{text('当前仍显示上次读取的结果。', 'The last loaded result is still shown.')}</p><button className="btn" type="button" onClick={() => void refresh()}>{text('重试', 'Retry')}</button></div></div>}{!editor && blockedPreview}{!editor && notice && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{notice}</span></div></div>}{!editor && actionError && <div className="callout bad agent-feedback agent-inline-feedback" role="alert" data-error-code={actionError}><UiIcon name="warning" /><span>{agentActionErrorMessage(actionError, language)}</span></div>}{!selected.context_id && <div className="callout"><UiIcon name="info" /><span>{text('此 Agent 的设置入口尚不可用。', 'Settings for this Agent are not available yet.')}</span></div>}- {editor?.context === selected.context_id && selected.context_id && <Dialog open title={`${agentName(selected)} · ${editor.facet === 'model' ? text('模型路由', 'Model routing') : text('任务路由', 'Task routing')}`} closeLabel={text('关闭配置', 'Close settings')} closeDisabled={busy} onClose={() => { if (!busy) close(); }} footer={<><button className="btn" type="button" disabled={busy} onClick={close}>{text('取消', 'Cancel')}</button><button className="btn btn-primary" type="submit" form="hr-agent-settings" disabled={busy || !mutable || Boolean(formInvalid)}>{busy ? busyText || text('正在保存…', 'Saving…') : text('保存配置', 'Save settings')}</button></>}>- <form id="hr-agent-settings" className="agent-form" onSubmit={event => { event.preventDefault(); void change(selected, editor.facet, !facetEnabled, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}>+ {editor?.context === selected.context_id && selected.context_id && <Dialog open title={`${agentName(selected)} · ${editor.facet === 'model' ? text('模型路由', 'Model routing') : text('任务路由', 'Task routing')}`} closeLabel={text('关闭配置', 'Close settings')} closeDisabled={busy} onClose={() => { if (!busy) close(); }} footer={<><button className="btn" type="button" disabled={busy} onClick={close}>{text('取消', 'Cancel')}</button><button className="btn btn-primary" type="submit" form="hr-agent-settings" disabled={busy || !mutable || Boolean(formInvalid)}>{busy ? busyText || text('正在保存…', 'Saving…') : submitLabel}</button></>}>+ <form id="hr-agent-settings" className="agent-form" ref={node => { firstField.current = node?.querySelector<HTMLElement>('input:not([disabled]), select:not([disabled]), button:not([disabled])') ?? null; }} onSubmit={event => { event.preventDefault(); void change(selected, editor.facet, false, (event.nativeEvent as SubmitEvent).submitter as HTMLElement | null); }}><fieldset disabled={busy || !mutable}>- <div className="option-row agent-facet-toggle"><div><strong>{editor.facet === 'model' ? text('使用 HiRoute 模型路由', 'Use HiRoute model routing') : text('启用任务路由', 'Enable task routing')}</strong><span>{editor.facet === 'model' ? text('关闭后使用原有模型接入', 'Use the original model connection when disabled') : text('允许当前 Agent 将任务交给执行 Agent,并获取结果', 'Allow this Agent to delegate work to an execution Agent and retrieve the results')}</span></div><button ref={node => { firstField.current = node; }} className={`switch${facetEnabled ? ' on' : ''}`} type="button" role="switch" aria-checked={facetEnabled} aria-label={editor.facet === 'model' ? text('模型路由', 'Model routing') : text('任务路由', 'Task routing')} onClick={() => { setFacetEnabled(value => !value); setPreview(null); setActionError(''); setNotice(''); }} /></div>- {facetEnabled && editor.facet === 'model' && <p className="field-help" data-agent-service-responsibility>{text('保存不会设置登录项或保证 HiRoute 服务以后持续在线;需要路由时请保持本机服务运行。', 'Saving does not configure a login item or guarantee that the HiRoute service stays online; keep the local service running when you need routing.')}</p>}- {facetEnabled && editor.facet === 'model' && selected.agent_id === 'agent_codex_default' && <div className="worker-choices">- <fieldset data-agent-native-mode><legend className="field-label">{text('Codex 可用模型', 'Models available in Codex')}</legend>- <label className="check-row"><input type="radio" name="codex-native-mode" value="hiroute_only" checked={editorValues.nativeModelMode === 'hiroute_only'} onChange={() => selectNativeModelMode('hiroute_only')} /><div><strong>{text('只使用已配置的 HiRoute 模型', 'Use configured HiRoute models only')}</strong><small>{text('无需接入原 Codex 账号;关闭时恢复原配置。', 'No original Codex account connection required; disabling restores the original configuration.')}</small></div></label>- <label className="check-row"><input type="radio" name="codex-native-mode" value="preserve_available" checked={editorValues.nativeModelMode === 'preserve_available'} onChange={() => selectNativeModelMode('preserve_available')} /><div><strong>{text('同时保留 Codex 原有模型', 'Also keep native Codex models')}</strong><small>{text('先在“模型”接入原订阅账号或 API 来源;只保留能证明同账号可调用的模型。缓存目录不是账号权限。', 'Connect the original subscription account or API source under Models first. Only proven same-account models are kept; the cache is not entitlement.')}</small></div></label>+ {editor.facet === 'model' && <p className="field-help" data-agent-service-responsibility>{text('使用路由时请保持 HiRoute 运行。启用不会自动设置开机启动。', 'Keep HiRoute running when using routing. Enabling does not set up automatic startup.')}</p>}+ {editor.facet === 'model' && selected.agent_id === 'agent_codex_default' && <div className="worker-choices">+ <p className="field-help" data-codex-shared-scope>{activeCodexMode === 'profile'+ ? text('按需使用 · 仅 Codex CLI。启用后将启动命令粘贴到终端,开启新会话。普通 Codex 和 Desktop 保持原配置。', 'On demand · Codex CLI only. After enabling, paste the launch command into a terminal to start a new session. Ordinary Codex and Desktop keep their settings.')+ : text('设为默认 · 修改同一配置目录下 Codex CLI 和 Desktop 的模型接入。保存后重新启动对应客户端即可生效。', 'Use by default · changes model access for Codex CLI and Desktop sharing this directory. Restart the client after saving to apply the settings.')}</p>+ <fieldset><legend className="field-label">{text('允许的智能路由', 'Allowed smart routes')}</legend>+ {enabledPlans.length === 1 && creatingModelConnection && <p className="field-help">{text('唯一可用路由已选为默认,可直接启用。', 'The only available route is selected as the default. Enable to continue.')}</p>}+ {enabledPlans.map(plan => <label className="check-row agent-route-choice" data-agent-plan-id={plan.agent_plan_id} key={plan.agent_plan_id}><input type="checkbox" checked={editorValues.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggleAllowedPlan(plan.agent_plan_id)} /><div><strong>{plan.desired.display_name}</strong></div></label>)}+ {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}+ {editorValues.allowedPlanIds.filter(id => !planEnabled(id)).map(id => <label className="check-row agent-route-choice" key={id}><input type="checkbox" checked onChange={() => toggleAllowedPlan(id)} /><span>{planName(id) ?? id} · {text('当前不可用', 'Currently unavailable')}</span></label>)}+ {editorValues.allowedPlanIds.some(id => !planEnabled(id)) && <span className="oc-inline-error">{text('已有路由已停用或不存在,请取消选择后再保存。', 'A previously allowed route is disabled or missing. Remove it before saving.')}</span>}</fieldset>- <div className="callout" data-codex-shared-scope><UiIcon name="info" /><div><strong>{text('一套共享配置', 'One shared configuration')}</strong><p>{text('保存一次即作用于共享此配置作用域与 CODEX_HOME 的 Codex CLI 和 Desktop。下面的发现结果是当前事实,不是配置范围开关。', 'One save applies to Codex CLI and Desktop when they share this configuration scope and CODEX_HOME. Detection below is a current fact, not a configuration-scope switch.')}</p>{(['codex_desktop', 'codex_cli'] as const).map(surface => {- const detected = detectedCodexSurfaces.has(surface);- return <span className="field-help" key={surface} data-agent-surface-fact={surface} data-agent-surface-detected={detected ? 'true' : 'false'}>{surfaceName(surface)} · {detected ? text('当前已发现可执行入口', 'currently detected as runnable') : text('当前未发现可执行入口;不影响保存', 'not currently detected as runnable; saving is unaffected')}</span>;- })}</div></div>+ {showCodexDefault && <>+ <label className="field"><span className="field-label">{text('默认选择', 'Default selection')}</span><select className="select" data-agent-default value={defaultChoiceValue(editorValues.defaultChoice)} onChange={event => selectDefaultChoice(event.target.value)}>{editorValues.nativeModelMode === 'preserve_available' && <option value="native">{text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name')}</option>}{editorValues.fixedModels.map(model => <option key={model.client_model_id} value={`fixed:${model.client_model_id}`}>{model.client_model_id}</option>)}{editorValues.allowedPlanIds.filter(planEnabled).map(id => <option key={id} value={`plan:${id}`}>{planName(id)}</option>)}</select><span className="field-help">{defaultChoice.kind === 'preserve_native'+ ? text('保留当前默认模型名称;请求仍经过 HiRoute。该名称须对应已勾选的路由或已绑定的固定模型。', 'Keep the current default model name; requests still pass through HiRoute. The name must match an enabled route or a bound fixed model.')+ : defaultChoice.kind === 'plan'+ ? editorValues.nativeModelMode === 'preserve_available' ? text('Codex 将默认使用所选智能路由;已证明可用的原生模型名称会继续自动保留。', 'Codex will use the selected smart route by default; proven native model names remain available automatically.') : text('Codex 将默认使用所选智能路由。', 'Codex will use the selected smart route by default.')+ : text('Codex 将默认使用所选固定模型来源。', 'Codex will use the selected fixed model source by default.')}</span>{editorValues.nativeModelMode === 'preserve_available' && defaultChoice.kind === 'preserve_native' && !codexDefaultValid && <span className="oc-inline-error">{text('当前无法读取 Codex 原生默认模型;请修复当前配置后重试。', 'The native Codex default model cannot be read. Repair the current configuration and try again.')}</span>}</label>+ </>}{fixedModelRows.length > 0 && <fieldset data-agent-fixed-models><legend className="field-label">{text('已配置的原生模型固定来源', 'Configured native model sources')}</legend>{fixedModelRows.map(model => {const fixed = editorValues.fixedModels.find(item => item.client_model_id === model.client_model_id);@@ -912,31 +990,39 @@ export function Agents({</div>;})}</fieldset>}- <fieldset><legend className="field-label">{text('允许的智能路由', 'Allowed smart routes')}</legend>- <p className="field-help" data-agent-plan-compatibility>{text('Codex 使用 Codex Responses 入口。上游来源名称不决定路由能否接入;保存时会按当前发布核对所选路由。', 'Codex uses the Codex Responses ingress. An upstream source name does not determine route compatibility; saving checks selected routes against the current publication.')}</p>- {enabledPlans.map(plan => <label className="check-row" data-agent-plan-id={plan.agent_plan_id} key={plan.agent_plan_id}><input type="checkbox" checked={editorValues.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggleAllowedPlan(plan.agent_plan_id)} /><div><strong>{plan.desired.display_name}</strong></div></label>)}- {!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}- {editorValues.allowedPlanIds.some(id => !planEnabled(id)) && <span className="oc-inline-error">{text('已有路由已停用或不存在,请取消选择后再保存。', 'A previously allowed route is disabled or missing. Remove it before saving.')}</span>}+ <Disclosure label={text('高级设置', 'Advanced settings')} language={language}>+ {selected.codex_access && <CodexAccessSettings access={selected.codex_access} mode={activeCodexMode} language={language} disabled={busy || !mutable} onMode={mode => { setCodexMode(mode); setPreview(null); setActionError(''); }} />}+ <fieldset data-agent-native-mode><legend className="field-label">{text('Codex 可用模型', 'Models available in Codex')}</legend>+ <label className="check-row"><input type="radio" name="codex-native-mode" value="hiroute_only" checked={editorValues.nativeModelMode === 'hiroute_only'} onChange={() => selectNativeModelMode('hiroute_only')} /><div><strong>{text('只使用已配置的 HiRoute 模型', 'Use configured HiRoute models only')}</strong><small>{text('无需接入原 Codex 账号;关闭时恢复原配置。', 'No original Codex account connection required; disabling restores the original configuration.')}</small></div></label>+ <label className="check-row"><input type="radio" name="codex-native-mode" value="preserve_available" checked={editorValues.nativeModelMode === 'preserve_available'} onChange={() => selectNativeModelMode('preserve_available')} /><div><strong>{text('同时保留 Codex 原有模型', 'Also keep native Codex models')}</strong><small>{text('先在“模型”接入原订阅账号或 API 来源;只保留能证明同账号可调用的模型。缓存目录不是账号权限。', 'Connect the original subscription account or API source under Models first. Only proven same-account models are kept; the cache is not entitlement.')}</small></div></label></fieldset>- <label className="field"><span className="field-label">{text('默认选择', 'Default selection')}</span><select className="select" data-agent-default value={defaultChoiceValue(editorValues.defaultChoice)} onChange={event => selectDefaultChoice(event.target.value)}>{editorValues.nativeModelMode === 'preserve_available' && <option value="native">{text('使用 Codex 当前默认模型名称', 'Use the current Codex default model name')}</option>}{editorValues.fixedModels.map(model => <option key={model.client_model_id} value={`fixed:${model.client_model_id}`}>{model.client_model_id}</option>)}{editorValues.allowedPlanIds.filter(planEnabled).map(id => <option key={id} value={`plan:${id}`}>{planName(id)}</option>)}</select><span className="field-help">{defaultChoice.kind === 'preserve_native'- ? text('保留当前默认模型名称;请求仍经过 HiRoute。该名称须对应已勾选的路由或已绑定的固定模型。', 'Keep the current default model name; requests still pass through HiRoute. The name must match an enabled route or a bound fixed model.')- : defaultChoice.kind === 'plan'- ? editorValues.nativeModelMode === 'preserve_available' ? text('Codex 将默认使用所选智能路由;已证明可用的原生模型名称会继续自动保留。', 'Codex will use the selected smart route by default; proven native model names remain available automatically.') : text('Codex 将默认使用所选智能路由。', 'Codex will use the selected smart route by default.')- : text('Codex 将默认使用所选固定模型来源。', 'Codex will use the selected fixed model source by default.')}</span>{defaultChoice.kind === 'preserve_native' && !codexDefaultValid && <span className="oc-inline-error">{text('当前无法读取 Codex 原生默认模型;请修复当前配置后重试。', 'The native Codex default model cannot be read. Repair the current configuration and try again.')}</span>}</label>- {modelFormInvalid && <span className="oc-inline-error">{text('至少选择一项固定模型或智能路由,并修正不可用项。', 'Choose at least one fixed model or smart route and resolve unavailable selections.')}</span>}+ <div className="callout" data-codex-shared-scope><UiIcon name="info" /><div><strong>{activeCodexMode === 'profile' ? text('独立 CLI 配置', 'Separate CLI configuration') : text('一套共享配置', 'One shared configuration')}</strong><p>{activeCodexMode === 'profile'+ ? text('本次保存只作用于指定 profile 的 Codex CLI。Desktop 继续使用原来的默认配置。', 'This save applies only to Codex CLI using the selected profile. Desktop keeps its original default configuration.')+ : text('保存一次即作用于共享此配置作用域与 CODEX_HOME 的 Codex CLI 和 Desktop。', 'One save applies to Codex CLI and Desktop when they share this configuration scope and CODEX_HOME.')}</p>{codexSurfaces.map(({surface, detected, applicable}) => {+ return <span className="field-help" key={surface} data-agent-surface-fact={surface} data-agent-surface-detected={detected ? 'true' : 'false'} data-agent-surface-applicable={applicable ? 'true' : 'false'}>{surfaceName(surface)} · {detected ? text('当前已发现可执行入口', 'currently detected as runnable') : text('当前未发现可执行入口', 'not currently detected as runnable')} · {applicable ? text('适用当前模式', 'applies to this mode') : text('不适用当前模式', 'does not apply to this mode')}</span>;+ })}</div></div>+ <p className="field-help" data-agent-plan-compatibility>{text('保存时会核对路由的 Codex Responses 能力。不同入口的会话历史可能不同。', 'Saving checks the routes’ Codex Responses capabilities. History may differ between entry points.')}</p>+ </Disclosure>+ {modelFormInvalid && <span className="oc-inline-error">{text('请选择可用路由或固定模型,并修正不可用项。', 'Choose an available route or fixed model and resolve unavailable selections.')}</span>}</div>}- {facetEnabled && editor.facet === 'model' && selected.agent_id === 'agent_claude_default' && <div className="worker-choices">- <p className="field-help">{text('普通 claude 入口会读取保存的三个原生预设映射;可重复选择同一路由。若未显式设置当前模型,账号 Default 仍未知;保存不会验证它,请选择已映射预设并做真实调用。', 'The normal claude entry reads the three saved native preset mappings, and routes may be reused. Without an explicit current model, the account Default remains unknown; saving does not verify it. Select a mapped preset and make a live call.')}</p>+ {editor.facet === 'model' && selected.agent_id === 'agent_claude_default' && <div className="worker-choices">+ <label className="field"><span className="field-label">{claudeSharedPlan === null ? text('模型档位路由', 'Preset routes') : text('共用一条路由', 'Use one route for all presets')}</span><select className="select" aria-label={text('Claude Code 路由', 'Claude Code route')} value={claudeSharedPlan ?? ''} onChange={event => { setEditorValues(value => ({ ...value, claudePresets: sharedClaudePlan(event.target.value) })); setPreview(null); setActionError(''); }}><option value="" disabled>{claudeSharedPlan === null ? text('已分别配置模型档位', 'Presets configured separately') : text('选择路由', 'Choose a route')}</option>{claudeSharedPlan && !planEnabled(claudeSharedPlan) && <option value={claudeSharedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select><span className="field-help">{claudeSharedPlan === null+ ? text('当前按档位分别配置。选择同一条路由可统一 Opus、Sonnet、Haiku;不会修改 Claude 当前默认模型。', 'Presets are configured separately. Choose one route to unify Opus, Sonnet and Haiku; the current Claude default model is unchanged.')+ : text('应用于 Opus、Sonnet、Haiku;高级设置可分别配置。不会修改 Claude 当前默认模型。', 'Applies to Opus, Sonnet and Haiku; configure them separately under Advanced settings. The current Claude default model is unchanged.')}</span></label>+ {editorValues.fixedModels.length > 0 && <p className="field-help">{text('保留已有固定模型:', 'Existing fixed models retained: ')}{editorValues.fixedModels.map(model => model.client_model_id).join(' · ')}</p>}+ <p className="field-help" data-agent-activation>{text('保存后,重新启动 Claude Code 即可加载配置。', 'Restart Claude Code after saving to load the settings.')}</p>+ <Disclosure label={text('高级设置', 'Advanced settings')} language={language} defaultOpen={claudeSharedPlan === null || claudePlanIds.some(id => !planEnabled(id))}>+ <p className="field-help">{text('普通 claude 入口使用这些映射。账号 Default 仍需真实调用验证,可显式选择已映射的模型档位。', 'The ordinary claude entry uses these mappings. Account Default needs a live call to verify; explicitly choose a mapped preset.')}</p>{(['opus', 'sonnet', 'haiku'] as const).map(preset => {const choice = editorValues.claudePresets[preset];const selectedPlan = choice.kind === 'plan' ? choice.plan_id : '';return <label className="field" key={preset}><span className="field-label">{preset[0].toUpperCase() + preset.slice(1)}</span><select className="select" value={selectedPlan} onChange={event => selectClaudePreset(preset, event.target.value)}><option value="">{text('保留原生值或缺省关系', 'Preserve native value or default relationship')}</option>{selectedPlan && !planEnabled(selectedPlan) && <option value={selectedPlan} disabled>{text('原有路由当前不可用', 'Previous route unavailable')}</option>}{enabledPlans.map(plan => <option key={plan.agent_plan_id} value={plan.agent_plan_id}>{plan.desired.display_name}</option>)}</select></label>;})}+ </Disclosure>{modelFormInvalid && <span className="oc-inline-error">{text('至少将一个预设映射到可用智能路由,或保留已有固定模型。', 'Map at least one preset to an enabled smart route, or retain an existing fixed model.')}</span>}{!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}</div>}- {facetEnabled && editor.facet === 'model' && <AgentCapabilityPreview agent={selected.agent_id === 'agent_claude_default' ? 'claude' : 'codex'} language={language} plans={enabledPlans.filter(plan => selected.agent_id === 'agent_claude_default' ? Object.values(editorValues.claudePresets).some(choice => choice.kind === 'plan' && choice.plan_id === plan.agent_plan_id) : editorValues.allowedPlanIds.includes(plan.agent_plan_id))} />}- {facetEnabled && editor.facet === 'collaboration' && <fieldset className="worker-choices"><legend className="field-label">{text('委派时机', 'When to delegate')}</legend><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="explicit" checked={editorValues.triggerMode === 'explicit'} onChange={() => setTriggerMode('explicit')} /><div><strong>{text('仅在明确要求时', 'Only when explicitly requested')}</strong><span>{text('只有当你要求执行、委派或交给 Worker 时,Agent 才会启动任务。', 'The Agent starts a task only when you ask it to execute, delegate, or hand work to a Worker.')}</span></div></label><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="delegate_by_default" checked={editorValues.triggerMode === 'delegate_by_default'} onChange={() => setTriggerMode('delegate_by_default')} /><div><strong>{text('默认由 Agent 判断', 'Let the Agent decide by default')}</strong><span>{text('Agent 可以主动委派适合执行的任务;明确要求只回答时不会启动任务。', 'The Agent may proactively delegate suitable work, but will not start a task when you explicitly ask for an answer only.')}</span></div></label><p className="field-help">{text('可委派的任务路由在“智能路由”中管理。', 'Manage routes available for task delegation under Smart routing.')}</p></fieldset>}+ {editor.facet === 'collaboration' && <fieldset className="worker-choices"><legend className="field-label">{text('委派时机', 'When to delegate')}</legend><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="explicit" checked={editorValues.triggerMode === 'explicit'} onChange={() => setTriggerMode('explicit')} /><div><strong>{text('仅在明确要求时', 'Only when explicitly requested')}</strong><span>{text('只有当你要求执行、委派或交给 Worker 时,Agent 才会启动任务。', 'The Agent starts a task only when you ask it to execute, delegate, or hand work to a Worker.')}</span></div></label><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="delegate_by_default" checked={editorValues.triggerMode === 'delegate_by_default'} onChange={() => setTriggerMode('delegate_by_default')} /><div><strong>{text('默认由 Agent 判断', 'Let the Agent decide by default')}</strong><span>{text('Agent 可以主动委派适合执行的任务;明确要求只回答时不会启动任务。', 'The Agent may proactively delegate suitable work, but will not start a task when you explicitly ask for an answer only.')}</span></div></label><p className="field-help">{text('可委派的任务路由在“智能路由”中管理。', 'Manage routes available for task delegation under Smart routing.')}</p></fieldset>}{!selectionKnown && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{text('当前配置状态无法核实,不能覆盖保存。请刷新或处理配置变化。', 'The current setting cannot be verified. Refresh or resolve configuration changes before saving.')}</span></div>}</fieldset></form>diff --git a/apps/desktop/src/features/agents/CodexAccessPanel.tsx b/apps/desktop/src/features/agents/CodexAccessPanel.tsxnew file mode 100644index 00000000..c2931c2c--- /dev/null+++ b/apps/desktop/src/features/agents/CodexAccessPanel.tsx@@ -0,0 +1,85 @@+import React, { useState } from 'react';+import { Disclosure, UiIcon, copyText } from '../../ui';+import { preferredCodexShell } from './codex-launch';++export type CodexAccess = {+ codex_home: string;+ slot_id: string;+ profile_context_id: string;+ root_context_id: string;+ selected_mode: 'profile' | 'root';+ slot_occupied: boolean;+ target_file: string;+ profile_name: string;+ commands: Record<string, string>;+ pending_operation: string | null;+ access_revoked: boolean;+ conflict_fields: string[];+};++export function CodexAccessSettings({ access, mode, language, disabled, onMode }: {+ access: CodexAccess; mode: 'profile' | 'root'; language: 'zh' | 'en'; disabled: boolean;+ onMode: (mode: 'profile' | 'root') => void;+}) {+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ return <div data-codex-access-mode={mode}>+ <label className="field"><span className="field-label">{text('接入方式', 'Connection mode')}</span>+ <select className="select" aria-label={text('Codex 接入方式', 'Codex connection mode')} value={mode} disabled={disabled || access.slot_occupied} onChange={e => onMode(e.target.value as 'profile' | 'root')}>+ <option value="profile">{text('按需使用 · 仅 CLI(推荐)', 'On demand · CLI only (recommended)')}</option>+ <option value="root">{text('设为默认 · CLI 和 Desktop(高级)', 'Use by default · CLI and Desktop (advanced)')}</option>+ </select>+ </label>+ {access.slot_occupied && <p className="field-help">{text('切换接入方式前,请先停用并完成配置恢复。', 'Disable and finish restoring the configuration before switching modes.')}</p>}+ <Disclosure label={text('配置位置与会话历史', 'Configuration location and history')} language={language}>+ <dl><div><dt>CODEX_HOME</dt><dd><code>{access.codex_home}</code></dd></div>+ {access.slot_occupied && <div><dt>{text('目标文件', 'Target file')}</dt><dd><code>{access.target_file}</code></dd></div>}+ </dl>+ <p className="field-help">{text('不同入口的会话历史可能不同;不提供跨 provider 历史恢复。独立 profile 不支持启动 Desktop。', 'History may differ between entry points; cross-provider recovery is not provided. The separate profile cannot launch Desktop.')}</p>+ </Disclosure>+ </div>;+}++export function CodexAccessPanel({ access, language, retryDisabled, onRetry }: {+ access: CodexAccess; language: 'zh' | 'en'; retryDisabled: boolean; onRetry: () => Promise<void>;+}) {+ const [shell, setShell] = useState(() => preferredCodexShell(typeof navigator === 'undefined' ? '' : navigator.platform, access.commands));+ const [copyState, setCopyState] = useState('');+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ if (!access.slot_occupied && !access.pending_operation) return null;+ const mode = access.selected_mode;+ const command = access.commands[shell];+ return <section className="fact-section" data-codex-access-mode={mode}>+ <p className="field-help">{mode === 'profile'+ ? text('按需使用 · Codex CLI:复制命令到终端启动。普通 Codex 与 Desktop 保持原配置。', 'On demand · Codex CLI: copy the command to start in a terminal. Ordinary Codex and Desktop keep their settings.')+ : text('默认接入 · Codex CLI 和 Desktop:共享此配置目录的入口使用 HiRoute。', 'Default connection · Codex CLI and Desktop: entry points sharing this directory use HiRoute.')}</p>+ {mode === 'profile' && access.slot_occupied && !access.pending_operation && !access.access_revoked && <div>+ <div className="detail-section-head"><strong>{text('启动 Codex', 'Start Codex')}</strong><label className="field-label agent-launch-shell">Shell <select className="select" value={shell} onChange={e => { setShell(e.target.value); setCopyState(''); }}>{Object.keys(access.commands).map(name => <option key={name}>{name}</option>)}</select></label></div>+ <pre className="agent-launch-command"><code>{command}</code></pre>+ <button className="btn" disabled={!command} onClick={async () => {+ try { await copyText(command); setCopyState(text('已复制', 'Copied')); }+ catch { setCopyState(text('复制失败,请手动选择命令复制', 'Copy failed; select and copy the command manually')); }+ }}>{text('复制启动命令', 'Copy launch command')}</button><span role="status">{copyState}</span>+ </div>}+ {!access.pending_operation && !access.access_revoked && access.conflict_fields.length > 0 && <div className="callout warn" role="alert" data-codex-restore-conflict>+ <UiIcon name="warning" /><div>+ <strong>{text('配置文件存在冲突', 'Configuration file conflict')}</strong>+ <p>{text('文件冲突解决前无法完成停用,原连接仍有效。HiRoute 会保留你的修改;请处理以下字段后重新点击“停用”。其他配置仍可修改。', 'Disable cannot complete until the conflict is resolved; the original connection remains active. HiRoute preserves your edits. Resolve these fields, then click Disable again. Other settings remain editable.')}</p>+ <p><code>{access.target_file}</code></p>+ <ul>{access.conflict_fields.map(field => <li key={field}><code>{field}</code></li>)}</ul>+ </div>+ </div>}+ {access.pending_operation && <div className="callout warn" role="alert">+ <UiIcon name="warning" /><div>+ <p>{access.access_revoked+ ? text('已停用,配置文件待清理。旧令牌已失效。', 'Disabled; configuration cleanup is pending. The old token is invalid.')+ : text('当前操作尚未完成,不能切换接入模式。', 'The current operation is incomplete; mode switching is blocked.')}</p>+ <p><code>{access.target_file}</code></p>+ {access.conflict_fields.length > 0 && <ul>{access.conflict_fields.map(field => <li key={field}><code>{field}</code></li>)}</ul>}+ <p>{access.access_revoked+ ? text('请修复所列冲突,或自行清理 HiRoute 受管字段后重新检查。无关设置和注释可以保留。清理完成前,新的配置保存会暂停。', 'Resolve the listed conflicts, or remove the HiRoute-managed fields and recheck. Unrelated settings and comments can remain. New configuration saves wait until cleanup finishes.')+ : text('请先保存自己的编辑,恢复操作开始后发生的文件改动,再重新检查。完成前新的配置保存会暂停。HiRoute 不会强制覆盖文件。', 'Save your edits, undo file changes made since this operation started, then recheck. New configuration saves wait until it finishes. HiRoute will not force an overwrite.')}</p>+ <button className="btn" disabled={retryDisabled} onClick={() => void onRetry()}>{text('重新检查并继续原操作', 'Recheck and resume operation')}</button>+ </div>+ </div>}+ </section>;+}diff --git a/apps/desktop/src/features/agents/codex-launch.ts b/apps/desktop/src/features/agents/codex-launch.tsnew file mode 100644index 00000000..df324949--- /dev/null+++ b/apps/desktop/src/features/agents/codex-launch.ts@@ -0,0 +1,24 @@+import type { Agent } from '../../agents';+import type { OperationReference } from '../model-connections/types';++export type PendingCodexLaunchCopy = { operationId: string; contextId: string };++export function preferredCodexShell(platform: string, commands: Record<string, string>): string {+ const preferred = /win/i.test(platform) ? 'powershell' : 'bash/zsh';+ return commands[preferred] ? preferred : Object.keys(commands).find(shell => Boolean(commands[shell])) ?? preferred;+}++/** A successful submission is insufficient: copy only a fresh, confirmed target. */+export function confirmedCodexLaunchCommand(+ target: PendingCodexLaunchCopy,+ operation: OperationReference | null | undefined,+ agent: Agent | undefined,+ platform: string,+): string | null {+ const access = agent?.codex_access;+ if (operation?.operation_id !== target.operationId || operation.state !== 'succeeded'+ || agent?.status_error || agent?.settings?.state !== 'configured'+ || !access?.slot_occupied || access.selected_mode !== 'profile'+ || access.profile_context_id !== target.contextId || access.pending_operation || access.access_revoked) return null;+ return access.commands[preferredCodexShell(platform, access.commands)] || null;+}diff --git a/apps/desktop/src/features/agents/codex-surfaces.ts b/apps/desktop/src/features/agents/codex-surfaces.tsnew file mode 100644index 00000000..8d7ac9ea--- /dev/null+++ b/apps/desktop/src/features/agents/codex-surfaces.ts@@ -0,0 +1,11 @@+export type CodexMode = 'profile' | 'root';+export type CodexSurface = 'codex_cli' | 'codex_desktop';++/** Discovery facts remain stable when the user changes the connection mode. */+export function codexSurfaceFacts(mode: CodexMode, detected: readonly string[]) {+ return (['codex_desktop', 'codex_cli'] as const).map(surface => ({+ surface,+ detected: detected.includes(surface),+ applicable: mode === 'root' || surface === 'codex_cli',+ }));+}diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.cssindex 15e4e09f..a52ebafd 100644--- a/apps/desktop/src/occami/styles.css+++ b/apps/desktop/src/occami/styles.css@@ -50,7 +50,13 @@.route-avatar[data-mode='smart_saving'] {background:#6676ed;}.route-avatar[data-mode='free_first'] {background:#218a6d;}.route-avatar[data-mode='fixed_model'] {background:#8c66c8;}-.agent-form .worker-choices {margin:0;padding:0;border:0;}+.agent-form .worker-choices {display:grid;gap:16px;margin:0;padding:0;border:0;}+.agent-form .worker-choices fieldset {display:grid;gap:10px;}+.agent-form .agent-route-choice {padding:12px 14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-soft);}+.agent-form .agent-route-choice:has(input:checked) {border-color:var(--accent);background:var(--accent-soft);}+.agent-launch-command {white-space:pre-wrap;overflow-wrap:anywhere;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-soft);font-size:calc(12px * var(--hr-text-scale));}+.agent-launch-shell {display:flex;align-items:center;gap:8px;}+.agent-launch-shell .select {width:auto;max-width:160px;}.agent-form .worker-choices>.field-label {margin-bottom:10px;color:var(--text);font-size:calc(14px * var(--hr-text-scale));font-weight:620;}.agent-surface-results {display:grid;gap:8px;margin-top:12px;}.agent-surface-result {display:flex;align-items:center;justify-content:space-between;gap:12px;color:var(--text-muted);font-size:calc(12px * var(--hr-text-scale));}diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsxindex dbc7e811..66864718 100644--- a/apps/desktop/src/product/DesktopApp.tsx+++ b/apps/desktop/src/product/DesktopApp.tsx@@ -646,6 +646,7 @@ export function DesktopApp() {key={agentIntent.key}language={language}active={page === 'agents'}+ operation={operation}initialAgentId={agentIntent.agentId}initialFacet={agentIntent.facet}initialTab={agentIntent.tab}diff --git a/apps/desktop/src/ui/Toast.tsx b/apps/desktop/src/ui/Toast.tsxindex 3ae5f999..d8b24a35 100644--- a/apps/desktop/src/ui/Toast.tsx+++ b/apps/desktop/src/ui/Toast.tsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useRef, useState } from 'react';import { UiIcon } from './UiIcon';+export { copyText } from './clipboard';export type ToastNotice = {key: number;@@ -38,20 +39,3 @@ export function Toast({ notice }: { notice: ToastNotice | null }) {</div></div>;}--export async function copyText(value: string): Promise<void> {- if (navigator.clipboard?.writeText) {- await navigator.clipboard.writeText(value);- return;- }- const input = document.createElement('textarea');- input.value = value;- input.setAttribute('readonly', '');- input.style.position = 'fixed';- input.style.opacity = '0';- document.body.append(input);- input.select();- const copied = document.execCommand('copy');- input.remove();- if (!copied) throw new Error('CLIPBOARD_UNAVAILABLE');-}diff --git a/apps/desktop/src/ui/clipboard.ts b/apps/desktop/src/ui/clipboard.tsnew file mode 100644index 00000000..e9801ab5--- /dev/null+++ b/apps/desktop/src/ui/clipboard.ts@@ -0,0 +1,31 @@+import { isTauri } from '@tauri-apps/api/core';+import { writeText } from '@tauri-apps/plugin-clipboard-manager';++export async function copyText(value: string): Promise<void> {+ if (isTauri()) {+ await writeText(value);+ return;+ }+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(value);+ return;+ }+ } catch {+ // Some native WebViews expose this API but cannot use it after an async save.+ }+ const previousFocus = document.activeElement as HTMLElement | null;+ const input = document.createElement('textarea');+ input.value = value;+ input.setAttribute('readonly', '');+ input.style.position = 'fixed';+ input.style.opacity = '0';+ document.body.append(input);+ try {+ input.select();+ if (!document.execCommand('copy')) throw new Error('CLIPBOARD_UNAVAILABLE');+ } finally {+ input.remove();+ previousFocus?.focus();+ }+}diff --git a/apps/desktop/tests/agent-editor-state.test.mjs b/apps/desktop/tests/agent-editor-state.test.mjsindex 291b726a..38192292 100644--- a/apps/desktop/tests/agent-editor-state.test.mjs+++ b/apps/desktop/tests/agent-editor-state.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { agentEditorSeed, codexDefaultChoiceValid, editorFingerprint } from '../src/agent-editor-state.ts';+import { agentEditorSeed, codexDefaultChoiceValid, commonClaudePlan, sharedClaudePlan, editorFingerprint } from '../src/agent-editor-state.ts';const codexSelection = {mode: 'codex_default',@@ -106,3 +106,53 @@ test('all model and collaboration choices participate in dirty tracking', () =>editorFingerprint({ ...values, allowedPlanIds: [...values.allowedPlanIds].reverse() }),);});++test('first enable selects the sole route and a valid Codex default without changing the Agent', () => {+ const fresh = { ...codex, settings: { state: 'not_configured', current_selection: null } };+ const before = structuredClone(fresh);+ const seed = agentEditorSeed(fresh, 'model', ['only-route']);+ assert.deepEqual(seed.allowedPlanIds, ['only-route']);+ assert.deepEqual(seed.defaultChoice, { kind: 'plan', plan_id: 'only-route' });+ assert.equal(codexDefaultChoiceValid(seed.defaultChoice, seed.nativeModelMode, undefined, [], seed.allowedPlanIds), true);+ assert.deepEqual(fresh, before);+});++test('first Claude enable maps the sole route to all three presets without setting a native default', () => {+ const fresh = { ...claude, settings: { state: 'restored', current_selection: null } };+ const seed = agentEditorSeed(fresh, 'model', ['only-route']);+ assert.deepEqual(seed.claudePresets, sharedClaudePlan('only-route'));+ assert.equal(commonClaudePlan(seed.claudePresets), 'only-route');+ assert.deepEqual(seed.defaultChoice, { kind: 'preserve_native' });+});++test('zero or multiple routes require selection and do not silently authorize a route', () => {+ for (const agent of [codex, claude]) {+ const fresh = { ...agent, settings: { state: 'not_configured', current_selection: null } };+ for (const choices of [[], ['a', 'b']]) {+ const seed = agentEditorSeed(fresh, 'model', choices);+ assert.deepEqual(seed.allowedPlanIds, []);+ assert.equal(commonClaudePlan(seed.claudePresets), '');+ assert.deepEqual(seed.defaultChoice, { kind: 'preserve_native' });+ }+ }+});++test('editing existing, unavailable or split mappings never applies first-enable shortcuts', () => {+ assert.deepEqual(agentEditorSeed(codex, 'model', ['replacement']).allowedPlanIds, ['a', 'b']);+ const oldClaude = agentEditorSeed(claude, 'model', ['replacement']);+ assert.deepEqual(oldClaude.claudePresets, claude.settings.current_selection.preset_mappings);+ assert.equal(commonClaudePlan(oldClaude.claudePresets), null);+ assert.equal(commonClaudePlan(sharedClaudePlan('missing-route')), 'missing-route');+ for (const state of ['drift', 'pending', 'needs_attention']) {+ const seed = agentEditorSeed({ ...codex, settings: { state, current_selection: null } }, 'model', ['replacement']);+ assert.equal(seed.known, false);+ assert.deepEqual(seed.allowedPlanIds, []);+ }+});++test('collaboration and unreadable initial settings do not pick model routes', () => {+ assert.deepEqual(agentEditorSeed(codex, 'collaboration', ['only-route']).allowedPlanIds, []);+ const seed = agentEditorSeed({ ...codex, status_error: 'UNAVAILABLE', settings: { state: 'not_configured' } }, 'model', ['only-route']);+ assert.equal(seed.known, false);+ assert.deepEqual(seed.allowedPlanIds, []);+});diff --git a/apps/desktop/tests/agent-mutation-feedback.test.mjs b/apps/desktop/tests/agent-mutation-feedback.test.mjsindex 5c874155..40a4afd5 100644--- a/apps/desktop/tests/agent-mutation-feedback.test.mjs+++ b/apps/desktop/tests/agent-mutation-feedback.test.mjs@@ -1,6 +1,6 @@import assert from 'node:assert/strict';import test from 'node:test';-import { agentActionErrorMessage, classifyAgentMutation } from '../src/agent-mutation-feedback.ts';+import { agentActionErrorMessage, agentDisableMessage, classifyAgentMutation } from '../src/agent-mutation-feedback.ts';const operation = {operation_id: 'operation/agent-settings',@@ -30,3 +30,12 @@ test('a pre-admission Agent conflict tells the user no save occurred and offersassert.match(agentActionErrorMessage('SERVICE_UNAVAILABLE', 'en'), /local service is unavailable/);assert.doesNotMatch(agentActionErrorMessage('SERVICE_UNAVAILABLE', 'en'), /enabled in Login Items/);});++test('disable feedback reports success, verified rollback and uncertain recovery separately', () => {+ assert.match(agentDisableMessage('succeeded', 'zh'), /连接已停用/);+ assert.match(agentDisableMessage('rolled_back', 'zh'), /原连接仍有效/);+ assert.match(agentDisableMessage('rolled_back', 'en'), /rolled back/);+ assert.match(agentDisableMessage('needs_attention', 'zh'), /回滚尚未确认/);+ assert.doesNotMatch(agentDisableMessage('needs_attention', 'zh'), /原连接仍有效|连接已停用/);+ assert.doesNotMatch(agentDisableMessage('activating', 'en'), /is disabled|remains active/);+});diff --git a/apps/desktop/tests/clipboard.test.mjs b/apps/desktop/tests/clipboard.test.mjsnew file mode 100644index 00000000..306ddbb2--- /dev/null+++ b/apps/desktop/tests/clipboard.test.mjs@@ -0,0 +1,66 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { copyText } from '../src/ui/clipboard.ts';++function webview(t, clipboard, copied = true) {+ const calls = [];+ const input = { style: {}, value: '', setAttribute() {}, select() { calls.push(['select', this.value]); }, remove() { calls.push(['remove']); } };+ t.mock.getter(globalThis, 'navigator', () => ({ clipboard }));+ const previousDocument = Object.getOwnPropertyDescriptor(globalThis, 'document');+ Object.defineProperty(globalThis, 'document', { configurable: true, value: {+ activeElement: { focus() { calls.push(['focus']); } },+ createElement() { return input; }, body: { append() {} },+ execCommand(command) { calls.push([command, input.value]); return copied; },+ } });+ t.after(() => {+ if (previousDocument) Object.defineProperty(globalThis, 'document', previousDocument);+ else delete globalThis.document;+ });+ return calls;+}++function nativeClipboard(t, invoke) {+ for (const [key, value] of [['isTauri', true], ['window', { __TAURI_INTERNALS__: { invoke } }]]) {+ const original = Object.getOwnPropertyDescriptor(globalThis, key);+ Object.defineProperty(globalThis, key, { configurable: true, value });+ t.after(() => { if (original) Object.defineProperty(globalThis, key, original); else delete globalThis[key]; });+ }+}++test('native copying uses IPC with the exact text and does not require browser clipboard permission', async t => {+ const calls = [];+ nativeClipboard(t, async (command, args) => { calls.push({ command, text: args.text }); });+ const value = `CODEX_HOME='/path with spaces' codex --profile hiroute`;+ await copyText(value);+ assert.deepEqual(calls, [{ command: 'plugin:clipboard-manager|write_text', text: value }]);+});++test('native clipboard failure propagates to the caller for a manual-copy fallback', async t => {+ nativeClipboard(t, async () => { throw new Error('CLIPBOARD_BUSY'); });+ await assert.rejects(copyText('launch command'), /CLIPBOARD_BUSY/);+});++test('copy succeeds through the clipboard API without changing focus', async t => {+ let actual;+ const calls = webview(t, { async writeText(value) { actual = value; } });+ await copyText('launch command');+ assert.equal(actual, 'launch command');+ assert.deepEqual(calls, []);+});++test('native WebViews with a missing or rejected clipboard API still copy the exact command', async t => {+ for (const clipboard of [undefined, { async writeText() { throw new Error('NotAllowedError'); } }]) {+ await t.test(clipboard ? 'rejected' : 'missing', async sub => {+ const calls = webview(sub, clipboard);+ const command = `CODEX_HOME='/path with spaces' codex --profile hiroute`;+ await copyText(command);+ assert.deepEqual(calls, [['select', command], ['copy', command], ['remove'], ['focus']]);+ });+ }+});++test('failed copying reports failure and removes the temporary field', async t => {+ const calls = webview(t, undefined, false);+ await assert.rejects(copyText('launch command'), /CLIPBOARD_UNAVAILABLE/);+ assert.deepEqual(calls.slice(-2), [['remove'], ['focus']]);+});diff --git a/apps/desktop/tests/codex-launch.test.mjs b/apps/desktop/tests/codex-launch.test.mjsnew file mode 100644index 00000000..82584a3f--- /dev/null+++ b/apps/desktop/tests/codex-launch.test.mjs@@ -0,0 +1,40 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { confirmedCodexLaunchCommand, preferredCodexShell } from '../src/features/agents/codex-launch.ts';++const target = { operationId: 'op/new-profile', contextId: 'context/profile' };+const operation = { operation_id: target.operationId, state: 'succeeded', sequence: 2, cancellable: false };+const agent = {+ agent_id: 'agent_codex_default', status_error: null,+ settings: { state: 'configured' },+ codex_access: {+ slot_occupied: true, selected_mode: 'profile', profile_context_id: target.contextId,+ pending_operation: null, access_revoked: false,+ commands: { 'bash/zsh': "CODEX_HOME='/path with spaces' codex --profile hiroute", powershell: 'powershell-command' },+ },+};++test('copy uses the confirmed target command verbatim and chooses the platform shell', () => {+ assert.equal(confirmedCodexLaunchCommand(target, operation, agent, 'MacIntel'), agent.codex_access.commands['bash/zsh']);+ assert.equal(confirmedCodexLaunchCommand(target, operation, agent, 'Win32'), 'powershell-command');+ assert.equal(preferredCodexShell('Linux', { fish: 'fish-command' }), 'fish');+});++test('accepted, failed, cancelled, missing and unrelated Operations cannot trigger copying', () => {+ for (const state of ['accepted', 'preparing', 'pending', 'failed', 'cancelled']) {+ assert.equal(confirmedCodexLaunchCommand(target, { ...operation, state }, agent, 'MacIntel'), null);+ }+ assert.equal(confirmedCodexLaunchCommand(target, { ...operation, operation_id: 'op/old' }, agent, 'MacIntel'), null);+ assert.equal(confirmedCodexLaunchCommand(target, null, agent, 'MacIntel'), null);+});++test('unconfirmed, replaced, root and revoked targets cannot trigger copying after success', () => {+ for (const patch of [+ { slot_occupied: false }, { selected_mode: 'root' }, { profile_context_id: 'context/other' },+ { pending_operation: 'op/cleanup' }, { access_revoked: true }, { commands: {} },+ ]) {+ assert.equal(confirmedCodexLaunchCommand(target, operation, { ...agent, codex_access: { ...agent.codex_access, ...patch } }, 'MacIntel'), null);+ }+ assert.equal(confirmedCodexLaunchCommand(target, operation, { ...agent, settings: { state: 'pending' } }, 'MacIntel'), null);+ assert.equal(confirmedCodexLaunchCommand(target, operation, { ...agent, status_error: 'UNAVAILABLE' }, 'MacIntel'), null);+});diff --git a/apps/desktop/tests/codex-surfaces.test.mjs b/apps/desktop/tests/codex-surfaces.test.mjsnew file mode 100644index 00000000..8899ab48--- /dev/null+++ b/apps/desktop/tests/codex-surfaces.test.mjs@@ -0,0 +1,20 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { codexSurfaceFacts } from '../src/features/agents/codex-surfaces.ts';++test('Desktop discovery persists while CLI profile applicability changes with the mode', () => {+ const installed = ['codex_desktop', 'codex_cli'];+ const profile = codexSurfaceFacts('profile', installed);+ const root = codexSurfaceFacts('root', installed);+ assert.deepEqual(profile.filter(f => f.detected).map(f => f.surface), installed);+ assert.deepEqual(root.filter(f => f.detected).map(f => f.surface), installed);+ assert.deepEqual(profile.filter(f => f.applicable).map(f => f.surface), ['codex_cli']);+ assert.deepEqual(root.filter(f => f.applicable).map(f => f.surface), installed);+});++test('mode selection never invents an executable and does not remove an installed Desktop', () => {+ assert.deepEqual(codexSurfaceFacts('profile', ['codex_desktop']), [+ { surface: 'codex_desktop', detected: true, applicable: false },+ { surface: 'codex_cli', detected: false, applicable: true },+ ]);+});diff --git a/apps/desktop/tests/ui-consistency.test.mjs b/apps/desktop/tests/ui-consistency.test.mjsindex d240abe6..33c253a7 100644--- a/apps/desktop/tests/ui-consistency.test.mjs+++ b/apps/desktop/tests/ui-consistency.test.mjs@@ -186,7 +186,8 @@ test('Codex routing form only shows configured native overrides and explains theassert.match(agents, /defaultChoice\.kind === 'plan'[\s\S]*Codex 将默认使用所选智能路由/);assert.match(agents, /保留当前默认模型名称;请求仍经过 HiRoute/);assert.match(agents, /data-agent-service-responsibility/);- assert.match(agents, /保存不会设置登录项或保证 HiRoute 服务以后持续在线/);+ assert.match(agents, /使用路由时请保持 HiRoute 运行/);+ assert.match(agents, /启用不会自动设置开机启动/);});test('Agent home does not offer duplicate paid per-client live probes', () => {@@ -198,7 +199,7 @@ test('Agent home does not offer duplicate paid per-client live probes', () => {test('Claude routing promises the normal CLI entry and does not ask for a special launcher', () => {const agents = read('src/agents.tsx');assert.match(agents, /直接启动 claude,使用 Opus、Sonnet、Haiku 原生预设/);- assert.match(agents, /账号 Default 仍未知;保存不会验证它/);+ assert.match(agents, /账号 Default 仍需真实调用验证/);assert.match(agents, /路由已配置 · 调用未验证/);assert.doesNotMatch(agents, /hiroute agent launch --agent claude-code/);});diff --git a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjsindex 5f00f191..ab3ad501 100644--- a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs@@ -16,27 +16,30 @@ async function until(predicate, label) {}await tick();}-async function fresh(kind) {+async function fresh(kind, singleRoute = false) {c().reset();c().agents = c()[kind]();+ if (singleRoute) c().agents.plans.plans = c().agents.plans.plans.filter(plan => plan.head.status === 'enabled').slice(0, 1);await tick();await until(() => [...document.querySelectorAll('.native-list .list-row')].some(row => row.textContent.includes('Claude')), 'agents loaded');document.querySelectorAll('.native-list .list-row').forEach(row => { if (row.textContent.includes('Claude')) row.click(); });await until(() => document.querySelector('[data-agent-id="agent_claude_default"] .detail-hero'), 'Claude detail');}-async function freshCodex(kind) {+async function freshCodex(kind, singleRoute = false) {c().reset();c().agents = c()[kind]();+ if (singleRoute) c().agents.plans.plans = c().agents.plans.plans.filter(plan => plan.head.status === 'enabled').slice(0, 1);await tick();await until(() => [...document.querySelectorAll('.native-list .list-row')].some(row => row.textContent.includes('Codex')), 'agents loaded');document.querySelectorAll('.native-list .list-row').forEach(row => { if (row.textContent.includes('Codex')) row.click(); });await until(() => document.querySelector('[data-agent-id="agent_codex_default"] .detail-hero'), 'Codex detail');}-async function openEditor(kind = 'model') {+async function openEditor(kind = 'model', advanced = true) {const trigger = facet(kind);assert(trigger && !trigger.disabled, `Facet button unavailable: ${kind}`);trigger.click();await until(() => visible(dialog()), 'editor open');+ if (advanced) { const details = [...dialog().querySelectorAll('details')].find(node => node.querySelector('summary')?.textContent.includes('高级设置')); if (details) details.open = true; await tick(); }}async function save() {const control = submit();@@ -54,6 +57,84 @@ function changeSelect(select, value) {const configureSpecs = () => calls('preview_agent_settings').map(item => item.payload.input.spec);const scenarios = [+ ['Codex file conflicts preserve active access and allow other settings', async () => {+ await freshCodex('splitCodexStatus');+ const agent = c().agents.agents.find(agent => agent.agent_id === 'agent_codex_default');+ agent.codex_access.conflict_fields = ['model_providers.hiroute.name'];+ c().refresh(); await tick();+ await until(() => document.querySelector('[data-codex-restore-conflict]'), 'file conflict diagnosis');+ const alert = document.querySelector('[data-codex-restore-conflict]');+ assert(alert.textContent.includes('原连接仍有效') && alert.textContent.includes('model_providers.hiroute.name'), 'Conflict hides active access or fields');+ assert(!alert.textContent.includes('旧令牌已失效') && !alert.textContent.includes('新的配置保存会暂停'), 'Ordinary conflict claims revoked access or globally blocked settings');+ assert(!facet('model').disabled, 'Unrelated configuration action is blocked');+ }],+ ['Codex first enable is a ready-to-submit draft and cancel does not apply', async () => {+ await freshCodex('cliOnly', true);+ await openEditor('model', false);+ assert(!dialog().querySelector('[role="switch"]'), 'Redundant enable switch remains');+ const route = dialog().querySelector('[data-agent-plan-id] input');+ assert(route?.checked && !submit().disabled, 'Sole route is not ready to submit');+ assert(!dialog().querySelector('details').open, 'Advanced settings are open on first enable');+ assert(!dialog().querySelector('[data-agent-capability-preview]') && calls('plan_editor_options').length === 0, 'Enable still loads a read-only capacity preview');+ assert(dialog().textContent.includes('开启新会话'), 'Profile activation step is missing');+ const cancel = [...dialog().querySelectorAll('button')].find(button => button.textContent.trim() === '取消');+ cancel.click(); await tick();+ assert(!dialog() && calls('preview_agent_settings').length === 0 && c().operations.length === 0, 'Cancel applied a draft');+ }],+ ['Claude first enable shares one route while retaining independent advanced presets', async () => {+ await fresh('notRunnable', true);+ await openEditor('model', false);+ assert(!dialog().querySelector('[role="switch"]'), 'Redundant enable switch remains');+ const route = dialog().querySelector('select[aria-label="Claude Code 路由"]');+ assert(route?.value && !submit().disabled, 'Sole Claude route is not ready to submit');+ assert(!dialog().querySelector('details').open, 'Advanced presets are open by default');+ assert(!dialog().querySelector('[data-agent-capability-preview]') && calls('plan_editor_options').length === 0, 'Enable still loads a read-only capacity preview');+ assert(dialog().textContent.includes('重新启动 Claude Code'), 'Claude activation step is missing');+ await save();+ const spec = configureSpecs().at(-1).model.settings;+ assert(Object.values(spec.preset_mappings).every(choice => choice.kind === 'plan' && choice.plan_id === route.value), 'Shared route did not cover all three presets');+ assert(!Object.hasOwn(spec, 'model'), 'Shortcut changed the native current model');+ }],+ ['Codex copies the confirmed profile command through native IPC when browser copying rejects', async () => {+ await freshCodex('cliOnly', true);+ const agent = c().agents.agents.find(agent => agent.agent_id === 'agent_codex_default');+ const command = `CODEX_HOME='/path with spaces' codex --profile hiroute`;+ agent.codex_access = {+ codex_home: '/path with spaces', slot_id: 'slot/copy',+ profile_context_id: 'context/copy/profile', root_context_id: agent.context_id,+ selected_mode: 'profile', slot_occupied: false, target_file: '/path with spaces/hiroute.config.toml',+ profile_name: 'hiroute', commands: { 'bash/zsh': command },+ pending_operation: null, access_revoked: false, conflict_fields: [],+ };+ c().refresh(); await tick();+ const previousClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+ const previousCopy = Object.getOwnPropertyDescriptor(document, 'execCommand');+ const previousNative = Object.getOwnPropertyDescriptor(window, 'isTauri');+ const copied = [];+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { async writeText() { throw new Error('NotAllowedError'); } } });+ Object.defineProperty(document, 'execCommand', { configurable: true, value: () => { throw new Error('Browser clipboard is unavailable'); } });+ Object.defineProperty(window, 'isTauri', { configurable: true, value: true });+ try {+ c().handlers['plugin:clipboard-manager|write_text'] = payload => { copied.push(payload.text); };+ c().handlers.preview_agent_settings = payload => {+ agent.context_id = agent.codex_access.profile_context_id;+ agent.codex_access.slot_occupied = true;+ agent.settings.state = 'configured';+ agent.settings.current_selection = payload.input.spec.model.settings;+ return { preview: { applicable: true, blockers: [] }, mutation: { state: 'applied', operation: { operation_id: 'operation/agent-settings-fixture', state: 'succeeded', sequence: 1, cancellable: false } } };+ };+ await openEditor('model', false);+ assert(copied.length === 0, 'Opening the draft copied a command');+ await save();+ await until(() => text().includes('启动命令已复制'), 'copy success after confirmed save');+ assert(copied.length === 1 && copied[0] === command, 'Confirmed command was changed or copied twice');+ assert(!document.querySelector('textarea'), 'Temporary clipboard field remains in the UI');+ } finally {+ if (previousClipboard) Object.defineProperty(navigator, 'clipboard', previousClipboard); else delete navigator.clipboard;+ if (previousCopy) Object.defineProperty(document, 'execCommand', previousCopy); else delete document.execCommand;+ if (previousNative) Object.defineProperty(window, 'isTauri', previousNative); else delete window.isTauri;+ }+ }],['Desktop-only Codex repairs an existing fixed-model binding without a surface selector', async () => {await freshCodex('desktopWithFixed');await openEditor('model');@@ -79,16 +160,16 @@ const scenarios = [['CLI-only Codex saves one shared plan configuration without selecting Desktop', async () => {await freshCodex('cliOnly');await openEditor('model');- document.querySelector('#hr-agent-settings [role="switch"]').click();+ assert(!document.querySelector('#hr-agent-settings [role="switch"]'), 'Enable requires a redundant switch');await tick();assert(!document.querySelector('[data-agent-surface-option]'), 'Legacy surface selector is still rendered');assert(document.querySelector('[data-agent-surface-fact="codex_cli"]').getAttribute('data-agent-surface-detected') === 'true', 'CLI discovery fact missing');assert(document.querySelector('[data-agent-surface-fact="codex_desktop"]').getAttribute('data-agent-surface-detected') === 'false', 'Missing Desktop was not reported as a fact');const plan = document.querySelector('[data-agent-plan-id]');- plan.querySelector('input').click();+ if (!plan.querySelector('input').checked) plan.querySelector('input').click();await tick();const planId = plan.getAttribute('data-agent-plan-id');- changeSelect(document.querySelector('[data-agent-default]'), `plan:${planId}`);+ if (document.querySelector('[data-agent-default]')) changeSelect(document.querySelector('[data-agent-default]'), `plan:${planId}`);await tick();await save();const spec = configureSpecs().at(-1).model.settings;@@ -100,7 +181,7 @@ const scenarios = [await openEditor('model');changeSelect(document.querySelector('[data-client-model-id="gpt-5.6-sol"] select'), 'binding/codex/gpt-5.6-sol');const plan = document.querySelector('[data-agent-plan-id]');- plan.querySelector('input').click();+ if (!plan.querySelector('input').checked) plan.querySelector('input').click();await tick();assert(document.querySelector('[data-agent-default]').value === 'native', 'Native default was changed without user action');await save();@@ -138,7 +219,7 @@ const scenarios = [cancel.click();await tick();assert(!details.querySelector('.agent-token-form'), 'Token edit form did not close');- const restore = [...details.querySelectorAll('button')].find(button => button.textContent.trim() === '恢复模型设置');+ const restore = [...document.querySelectorAll('.detail-section-head button')].find(button => button.textContent.trim() === '停用');assert(restore && !restore.disabled, 'Model recovery became unavailable after token edit');}],['a Codex plan rejected by Preview explains the Responses boundary without applying it', async () => {@@ -148,12 +229,12 @@ const scenarios = [mutation: null,});await openEditor('model');- document.querySelector('#hr-agent-settings [role="switch"]').click();+ assert(!document.querySelector('#hr-agent-settings [role="switch"]'), 'Enable requires a redundant switch');await tick();const plan = document.querySelector('[data-agent-plan-id]');- plan.querySelector('input').click();+ if (!plan.querySelector('input').checked) plan.querySelector('input').click();await tick();- changeSelect(document.querySelector('[data-agent-default]'), `plan:${plan.getAttribute('data-agent-plan-id')}`);+ if (document.querySelector('[data-agent-default]')) changeSelect(document.querySelector('[data-agent-default]'), `plan:${plan.getAttribute('data-agent-plan-id')}`);await tick();assert(text().includes('Codex Responses'), 'The form did not explain the required ingress');submit().click();@@ -200,7 +281,7 @@ const scenarios = [const details = document.querySelector('.native-details');details.querySelector('summary').click();await tick();- const restore = [...details.querySelectorAll('button')].find(item => item.textContent.trim() === '恢复模型设置');+ const restore = [...document.querySelectorAll('.detail-section-head button')].find(item => item.textContent.trim() === '停用');assert(restore && !restore.disabled, 'Managed recovery entry blocked by an executable diagnostic');restore.click();await until(() => calls('preview_agent_settings').length === 1, 'recovery request dispatched');@@ -318,15 +399,17 @@ const scenarios = [await tick();assert(!document.querySelector('[data-client-model-id="gpt-5.6-sol"]'), 'Protected native binding leaked into HiRoute-only selection');const plan = document.querySelector('[data-agent-plan-id]');- plan.querySelector('input').click();+ if (!plan.querySelector('input').checked) plan.querySelector('input').click();await tick();- assert(document.querySelector('[data-agent-default]').value.startsWith('plan:'), 'HiRoute-only default was not selected');+ assert(!document.querySelector('[data-agent-default]') || document.querySelector('[data-agent-default]').value.startsWith('plan:'), 'HiRoute-only default was not selected');await save();const spec = configureSpecs().at(-1).model.settings;assert(spec.native_model_mode === 'hiroute_only' && spec.fixed_models.length === 0, 'Native model leaked into HiRoute-only save');}],];+export const agentTrustScenarioNames = scenarios.map(([name]) => name);+export async function runAgentTrustScenarios(start = 0, end = Infinity) {const results = [];for (const [name, run] of scenarios.slice(start, end)) {diff --git a/apps/desktop/tests/v3/browser/agent-trust.tsx b/apps/desktop/tests/v3/browser/agent-trust.tsxindex 5f5766eb..36b6b4bc 100644--- a/apps/desktop/tests/v3/browser/agent-trust.tsx+++ b/apps/desktop/tests/v3/browser/agent-trust.tsx@@ -2,6 +2,7 @@ import React, { useState } from 'react';import { createRoot } from 'react-dom/client';import { mockIPC } from '@tauri-apps/api/mocks';import { Agents, type AgentSnapshot } from '../../../src/agents';+import type { OperationReference } from '../../../src/features/model-connections/types';import { PresentationRoot } from '../../../src/ui';import { readyAgents } from './product-fixtures';import '../../../src/occami/styles.css';@@ -77,6 +78,12 @@ function protectedCodex(): AgentSnapshot {function splitCodexStatus(): AgentSnapshot {const snapshot = registered();const agent = codexOf(snapshot);+ agent.codex_access = {+ codex_home: '/fixture/codex', slot_id: 'slot/fixture',+ profile_context_id: 'context/fixture/profile', root_context_id: agent.context_id!,+ selected_mode: 'root', slot_occupied: true, target_file: '/fixture/codex/config.toml',+ profile_name: 'hiroute', commands: {}, pending_operation: null, access_revoked: false, conflict_fields: [],+ };agent.settings = {...agent.settings!,model_verified: false,@@ -131,6 +138,7 @@ mockIPC(async (command, payload) => {function Harness() {const [generation, setGeneration] = useState(0);const [refresh, setRefresh] = useState(0);+ const [operation, setOperation] = useState<OperationReference | null>(null);control.refresh = () => setRefresh(value => value + 1);control.reset = () => {control.agents = registered();@@ -138,13 +146,14 @@ function Harness() {control.handlers = {};control.mutations = 0;control.operations = [];+ setOperation(null);setRefresh(0);setGeneration(value => value + 1);};return <PresentationRoot language="zh" theme="dark" textScale={1}><div className="app-window"><main className="main" style={{ marginLeft: 0 }}><div role="note">组件测试:所有 IPC 为 mock;不连接 Tauri、daemon 或真实安装。</div>- <Agents key={generation} language="zh" refreshVersion={refresh} mutationAllowed onMutation={() => { control.mutations += 1; }} onOperation={(operation, presentation) => { control.operations.push({ operation, presentation }); }} />+ <Agents key={generation} language="zh" refreshVersion={refresh} operation={operation} mutationAllowed onMutation={() => { control.mutations += 1; }} onOperation={(operation, presentation) => { control.operations.push({ operation, presentation }); setOperation(operation); }} /></main></div></PresentationRoot>;}diff --git a/apps/desktop/tests/v3/visual/agent-trust-active.mjs b/apps/desktop/tests/v3/visual/agent-trust-active.mjsindex d2bb64e7..6778de2e 100644--- a/apps/desktop/tests/v3/visual/agent-trust-active.mjs+++ b/apps/desktop/tests/v3/visual/agent-trust-active.mjs@@ -20,7 +20,13 @@ try {if (!routeSaveOnly && !workerReplacementOnly) {await navigate(client, new URL('agent-trust.html', baseUrl).href, { width: 1280, height: 900 });await waitFor(client, 'Boolean(window.agentTrust)', { timeout: 7000 });- const batches = claudeCollaborationOnly ? [[11, 14]] : [[0, 5], [5, 10], [10, 17]];+ const names = await evaluate(client, "import('/agent-trust-scenarios.mjs').then(module => module.agentTrustScenarioNames)");+ if (!Array.isArray(names) || names.length === 0) throw new Error('Agent trust scenarios are missing');+ const batches = claudeCollaborationOnly+ ? names.flatMap((name, index) => name.startsWith('Claude collaboration') || name.startsWith('an unrelated Agent preview failure') ? [[index, index + 1]] : [])+ : Array.from({ length: Math.ceil(names.length / 5) }, (_, index) => [index * 5, Math.min((index + 1) * 5, names.length)]);+ if (claudeCollaborationOnly && batches.length !== 3) throw new Error('Required Claude collaboration scenarios are missing');+ const firstCheck = checks.length;for (const [start, end] of batches) {const batch = await evaluate(client, `import('/agent-trust-scenarios.mjs').then(module => module.runAgentTrustScenarios(${start}, ${end}))`);checks.push(...batch.results);@@ -28,6 +34,7 @@ try {process.stdout.write(`${item.state === 'green' ? 'green' : 'red'}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);}}+ if (checks.length - firstCheck !== (claudeCollaborationOnly ? 3 : names.length)) throw new Error('Agent trust scenarios were not all executed');}if (!claudeCollaborationOnly) {await navigate(client, new URL('?page=routing&scenario=ready', baseUrl).href, { width: 1280, height: 900 });diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex 0eb3c72c..8c98326a 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -39,6 +39,7 @@"hiroute.agent-routing-overlay/v1","hiroute.agent-scan-observation/v1","hiroute.agent-settings-preview/v2",+ "hiroute.agent-settings-retry/v1","hiroute.agent-surface-check/v1","hiroute.borrowed-codex-access-lease/v1","hiroute.borrowed-codex-binding-evidence/v1",@@ -217,6 +218,7 @@"hiroute.native-field-restore/v1","hiroute.native-files/v1","hiroute.native-observation/v2",+ "hiroute.native-restoration-ack/v1","hiroute.observation-retention/v1","hiroute.observation.ack/v2","hiroute.observation.conversation-content-envelope/v2",@@ -887,6 +889,19 @@"tools/e2e-harness/tests/p0_gateway_request_authority.rs"],"field_compatibility_support": [+ {+ "contract": "hiroute.settings-service-completion/v2",+ "field": "service-first restore checkpoint with an unstaged client model file",+ "mode": "recovery_read_only",+ "owner": "agent-connections",+ "reason": "Older admitted revokes can have a sealed service receipt before preparing the client file. Retain only their existing same-operation recovery reader and the frozen production-port fixture; current restores stage and switch the file before withdrawing service access.",+ "removal_condition": "Retire only after every retained operation and supported backup has no service-first restore file tail, together with its frozen regression fixture.",+ "allowed_paths": [+ "crates/application/src/operations/execution.rs",+ "crates/daemon/src/control/runtime/settings_profile_legacy_fixture.rs",+ "crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs"+ ]+ },{"contract": "hiroute.settings-claude-model-file/v1","field": "snapshot.context_window_tokens",diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rsindex a69b8535..87756d9c 100644--- a/crates/application-api/src/agent_settings.rs+++ b/crates/application-api/src/agent_settings.rs@@ -370,3 +370,12 @@ mod tests {assert!(request.valid_target());}}++/// Resume the original already-authorized Codex settings Operation; never creates a new intent.+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct AgentSettingsRetryV1 {+ pub schema: String,+ pub context_id: String,+ pub operation_id: hiroute_domain::OperationId,+}diff --git a/crates/application/src/agent_connection/control.rs b/crates/application/src/agent_connection/control.rsindex baf9d64d..06a67d18 100644--- a/crates/application/src/agent_connection/control.rs+++ b/crates/application/src/agent_connection/control.rs@@ -88,6 +88,7 @@ mod tests {impl AgentDiscoveryPort for Discovery {fn discover(&self) -> Result<Vec<DiscoveredAgentV1>, ControlReadError> {Ok(vec![DiscoveredAgentV1 {+ codex_access: None,context_id: Some("agent-context/codex/default".into()),agent_id: "agent_codex_default".into(),profile_id: "codex-responses-v1".into(),diff --git a/crates/application/src/agent_connection/model_journal.rs b/crates/application/src/agent_connection/model_journal.rsindex 14ee6549..a81c3f11 100644--- a/crates/application/src/agent_connection/model_journal.rs+++ b/crates/application/src/agent_connection/model_journal.rs@@ -154,7 +154,10 @@ pub fn decode_settings_codex_catalog(|| intent.desired_mode() != 0o600|| value["transaction"] != "settings"|| value["subject"]["agent_id"] != "agent_codex_default"- || value["subject"]["profile_id"] != "codex-responses-v1"+ || !matches!(+ value["subject"]["profile_id"].as_str(),+ Some("codex-responses-v1" | "codex-standalone-profile-v1")+ )|| value["subject"]["integration_profile_ref"] != "builtin/codex-responses/v1"{return Err(invalid());@@ -201,7 +204,10 @@ pub fn decode_settings_codex_model_file(|| intent.desired_mode() != 0o600|| value["transaction"] != "settings"|| value["subject"]["agent_id"] != "agent_codex_default"- || value["subject"]["profile_id"] != "codex-responses-v1"+ || !matches!(+ value["subject"]["profile_id"].as_str(),+ Some("codex-responses-v1" | "codex-standalone-profile-v1")+ )|| value["subject"]["integration_profile_ref"] != "builtin/codex-responses/v1"{return Err(invalid());diff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rsindex cb1a401a..12470fb4 100644--- a/crates/application/src/agent_connection/settings.rs+++ b/crates/application/src/agent_connection/settings.rs@@ -51,6 +51,8 @@ pub struct AgentSettingsFacts {pub native_default_model: Option<String>,/// Original directory for a Codex restore, never the HiRoute merged catalog.pub restore_native_model_ids: Option<Vec<String>>,+ /// A standalone file restores absence and inherits root; it never validates root's models.+ pub restore_inherits_root: bool,/// Model that an unmodified restore would leave in the native configuration.pub restored_native_model: Option<String>,pub native_claude_presets: Option<hiroute_domain::AgentClaudePresetValuesV2>,@@ -309,7 +311,7 @@ pub fn preview_agent_settings(restore_point_ref,&mut blockers,);- if facts.ingress == AgentIngressProtocolV1::Responses {+ if facts.ingress == AgentIngressProtocolV1::Responses && !facts.restore_inherits_root {let chosen = spec.restore_native_model.as_ref()diff --git a/crates/application/src/agent_connection/settings/tests.rs b/crates/application/src/agent_connection/settings/tests.rsindex 5b554d14..8fa0c744 100644--- a/crates/application/src/agent_connection/settings/tests.rs+++ b/crates/application/src/agent_connection/settings/tests.rs@@ -50,6 +50,7 @@ fn facts() -> AgentSettingsFacts {native_default_must_be_original: false,native_default_model: None,restore_native_model_ids: None,+ restore_inherits_root: false,restored_native_model: None,native_claude_presets: None,collaboration_file_conflict: false,@@ -459,6 +460,7 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {native_default_must_be_original: false,native_default_model: None,restore_native_model_ids: None,+ restore_inherits_root: false,restored_native_model: None,native_claude_presets: None,collaboration_file_conflict: false,@@ -1059,3 +1061,45 @@ fn claude_settings_share_the_smallest_published_window_and_block_overrides() {.any(|block| block.reason == SettingsBlockReason::ClaudePlanCapabilityUnavailable));}++#[test]+fn standalone_profile_restore_inherits_root_without_catalog_or_native_override() {+ let mut facts = facts();+ facts.ingress = AgentIngressProtocolV1::Responses;+ facts.restore_inherits_root = true;+ facts.capabilities = AgentCapabilitySet::new(+ [+ AgentCapability::EffectiveConfiguration,+ AgentCapability::AtomicManagedReplace,+ ]+ .into_iter()+ .map(|capability| CapabilityEvidence {+ capability,+ state: CapabilityState::Proven,+ adapter_contract: "isolated-test/1".into(),+ observed_at_unix_ms: 1,+ dependency_digest: facts.dependency_digest.clone(),+ reason: None,+ }),+ )+ .unwrap();+ facts+ .restore_points+ .insert("restore/owned".into(), AgentSettingsFacet::Model);+ let mut spec: AgentSettingsSpecV2 = serde_json::from_value(json!({+ "schema_version":{"major":2,"minor":0}, "context_id":"agent-context/test",+ "model":{"intent":"restore","restore_point_ref":"restore/owned"}+ }))+ .unwrap();+ assert!(+ preview_agent_settings(spec.clone(), &facts)+ .unwrap()+ .blockers+ .is_empty()+ );+ spec.restore_native_model = Some("gpt-5.6-sol".into());+ assert!(matches!(+ preview_agent_settings(spec, &facts),+ Err(SettingsPlanningError::InvalidSelection)+ ));+}diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rsindex 4b6e957c..0be9b53d 100644--- a/crates/application/src/control/mod.rs+++ b/crates/application/src/control/mod.rs@@ -62,6 +62,8 @@ pub struct ControlStateSnapshotV1 {#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct DiscoveredAgentV1 {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub codex_access: Option<CodexAccessViewV1>,#[serde(default, skip_serializing_if = "Option::is_none")]pub context_id: Option<String>,pub agent_id: String,@@ -85,6 +87,23 @@ pub struct DiscoveredAgentV1 {pub permission_hardening: Option<AgentConfigPermissionFindingV1>,}+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct CodexAccessViewV1 {+ pub codex_home: String,+ pub slot_id: String,+ pub profile_context_id: String,+ pub root_context_id: String,+ pub selected_mode: String,+ pub slot_occupied: bool,+ pub target_file: String,+ pub profile_name: String,+ pub commands: BTreeMap<String, String>,+ pub pending_operation: Option<String>,+ pub access_revoked: bool,+ pub conflict_fields: Vec<String>,+}+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct DiscoveredAgentModelCatalogV1 {@@ -295,6 +314,13 @@ pub trait ApplicationMutationPort: Send + Sync {/// Read-only facts needed by the typed AgentConnection planner and managed-launch endpoint./// The daemon adapter owns filesystem/publication joins; Application owns every product decision.pub trait AgentConnectionControlPort: Send + Sync {+ fn retry_settings_operation(+ &self,+ _request: &hiroute_application_api::AgentSettingsRetryV1,+ ) -> Result<OperationV1, ControlReadError> {+ Err(ControlReadError::Unavailable)+ }+/// Explicit protected Check admission only; never called during discovery.fn check_native_authentication(&self, _agent_id: &str) -> Result<(), ControlReadError> {Err(ControlReadError::Unavailable)diff --git a/crates/application/src/control/tests.rs b/crates/application/src/control/tests.rsindex 8d4acbd0..c0fc2288 100644--- a/crates/application/src/control/tests.rs+++ b/crates/application/src/control/tests.rs@@ -50,6 +50,7 @@ impl AgentDiscoveryPort for MemoryDiscovery {fn agent() -> DiscoveredAgentV1 {DiscoveredAgentV1 {+ codex_access: None,context_id: None,agent_id: "agent_codex_default".to_owned(),profile_id: "codex-responses-v1".to_owned(),diff --git a/crates/application/src/control_plane/agent_connection.rs b/crates/application/src/control_plane/agent_connection.rsindex 376e67e8..d933d63c 100644--- a/crates/application/src/control_plane/agent_connection.rs+++ b/crates/application/src/control_plane/agent_connection.rs@@ -65,7 +65,9 @@ pub(crate) fn dispatch_apply_agent_connection(service: &ApplicationService,request: LocalControlRequestV2,) -> MachineEnvelopeV2<Value> {- if request.payload["spec"]["schema_version"]["major"] == 2 {+ if request.payload["spec"]["schema_version"]["major"] == 2+ || request.payload["schema"] == "hiroute.agent-settings-retry/v1"+ {return super::agent_settings::apply(service, request);}if request.protected_grant.is_some() {diff --git a/crates/application/src/control_plane/agent_settings.rs b/crates/application/src/control_plane/agent_settings.rsindex f5e29bfc..d7e54c60 100644--- a/crates/application/src/control_plane/agent_settings.rs+++ b/crates/application/src/control_plane/agent_settings.rs@@ -100,6 +100,29 @@ pub(crate) fn apply(if request.protected_grant.is_some() {return failed(ErrorCode::CapabilityDenied, request.request_id);}+ if request.operation_id == "ApplyAgentConnectionChange"+ && request.payload.get("schema").is_some()+ {+ let payload: hiroute_application_api::AgentSettingsRetryV1 =+ match serde_json::from_value(request.payload) {+ Ok(value) => value,+ Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),+ };+ if payload.schema != "hiroute.agent-settings-retry/v1" {+ return failed(ErrorCode::InvalidArguments, request.request_id);+ }+ let Some(port) = service+ .ports+ .as_ref()+ .and_then(|p| p.agent_connection.as_ref())+ else {+ return failed(ErrorCode::DaemonUnavailable, request.request_id);+ };+ return match port.retry_settings_operation(&payload) {+ Ok(operation) => super::accepted_apply(operation, request.request_id),+ Err(error) => failed(map_control_error(error), request.request_id),+ };+ }let payload: AgentSettingsApplyV2 = match serde_json::from_value(request.payload) {Ok(payload) => payload,Err(_) => return failed(ErrorCode::InvalidArguments, request.request_id),diff --git a/crates/application/src/lib.rs b/crates/application/src/lib.rsindex 15856649..83c8a2f3 100644--- a/crates/application/src/lib.rs+++ b/crates/application/src/lib.rs@@ -36,7 +36,7 @@ pub use change::{};pub use operations::{AcceptedApply, PreparedTransactionV1, TransactionCoordinator, TransactionError,- TransactionRuntime, VerifiedPrincipal,+ TransactionRuntime, VerifiedPrincipal, settings_service_completion_is_current,};// Typed planners remain private; the coordinator and its narrow ports are exported only so thediff --git a/crates/application/src/operations/execution.rs b/crates/application/src/operations/execution.rsindex df9e97d9..e90f4858 100644--- a/crates/application/src/operations/execution.rs+++ b/crates/application/src/operations/execution.rs@@ -195,6 +195,13 @@ where}fn activate_exact_effects(&self, operation: &mut OperationV1) -> Result<(), TransactionError> {+ // Disable restores the client before withdrawing its service access. A conflict+ // therefore fails with the original connection intact, using ordinary rollback.+ // Configure/edit retain their existing service-first activation contract.+ let restoring_settings = is_settings_restoration(operation);+ if restoring_settings {+ self.activate_settings_file_tail(operation)?;+ }self.external.begin_publication_activation(operation)?;for mutation in operation.plan.secrets().to_vec() {let effect = match self@@ -233,8 +240,8 @@ whereself.record_effect(operation, OperationStepKind::MaterializeSources, control)?;// Agent artifacts must become durable before an executable publication can expose them.- // The settings client model file is deliberately excluded here: it activates only after- // the publication below is serving, so a client file never precedes its own service.+ // Settings files have their own activation boundary: restores ran above; configure/edit+ // run only after the publication below is serving.for intent in operation.plan.external()@@ -310,15 +317,16 @@ whereif revokes_agent_access_grant {self.activate_agent_access_grants(operation)?;}- // The service segment is complete: seal the durable completion receipt before the only- // effects that may follow it, then switch the client file.+ // Seal the completed service segment. Only configure/edit still have a file tail.self.seal_settings_service_completion(operation)?;- self.activate_settings_file_tail(operation)?;+ if !restoring_settings {+ self.activate_settings_file_tail(operation)?;+ }Ok(())}- /// Activates the settings client model file effects, the sole segment that follows the- /// sealed service receipt. A failure here must park the tail instead of rolling back.+ /// Restores settings files before service withdrawal, or completes a configure/edit or+ /// previously sealed legacy file tail. Only a sealed service receipt permits parking.pub(super) fn activate_settings_file_tail(&self,operation: &mut OperationV1,@@ -331,6 +339,20 @@ where.cloned().collect::<Vec<_>>(){+ self.external+ .prepare_agent_artifact_activation(operation, &intent)?;+ // Older builds may have sealed a revoke before preparing its file. Keep that+ // existing recovery reader; new restores always stage and switch the file first.+ if is_settings_restoration(operation)+ && settings_service_receipt(operation).is_some()+ && matches!(+ self.external.observe_external(operation, &intent)?,+ EffectReconciliation::Missing+ )+ {+ let effect = self.external.apply_external(operation, &intent)?;+ self.record_effect(operation, OperationStepKind::ApplyAgentArtifacts, effect)?;+ }let effect = match self.external.observe_external(operation, &intent)? {EffectReconciliation::Staged(effect) => {self.external.activate_external(operation, &effect)?@@ -388,3 +410,16 @@ whereOk(())}}++pub(super) fn is_settings_restoration(operation: &OperationV1) -> bool {+ operation+ .plan+ .external()+ .iter()+ .any(hiroute_domain::is_settings_managed_configuration)+ && operation+ .plan+ .agent_access_grants()+ .iter()+ .any(|mutation| mutation.kind() == AgentAccessGrantMutationKindV1::Revoke)+}diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rsindex 16fa9e60..e349f79c 100644--- a/crates/application/src/operations/mod.rs+++ b/crates/application/src/operations/mod.rs@@ -427,7 +427,15 @@ where.load_operation(&operation.operation_id)?.ok_or(TransactionError::OperationNotFound)?;match self.activate_settings_file_tail(&mut operation) {- Ok(()) => self.finish_success(operation),+ Ok(()) => {+ // The explicit tail retry bypasses run_step; complete its step journal before+ // publishing terminal success so strict history readers can verify the result.+ operation.step_mut(OperationStepKind::Activate).status =+ OperationStepStatus::Applied;+ operation.safe_error_code = None;+ self.control.save_operation(&mut operation)?;+ self.finish_success(operation)+ }Err(error) => {operation.safe_error_code = Some(error.safe_code().to_owned());self.control.save_operation_tail(&mut operation)?;@@ -576,8 +584,23 @@ where// Reconciliation uncertainty must not prevent best-effort compensation of the// other effects that still prove exact Operation ownership.let compensation = self.compensate_step(&operation, kind);+ let restored_stage_discarded = execution::is_settings_restoration(&operation)+ && kind == OperationStepKind::ApplyAgentArtifacts+ && compensation.is_ok()+ && operation+ .plan+ .external()+ .iter()+ .filter(|intent| intent.kind() == OwnedEffectKind::AgentArtifact)+ .all(|intent| {+ matches!(+ self.external.observe_external(&operation, intent),+ Ok(EffectReconciliation::Missing)+ )+ });let outcome = match (reconciliation, compensation) {(Ok(()), Ok(())) => Ok(()),+ (Err(_), Ok(())) if restored_stage_discarded => Ok(()),_ => Err(TransactionError::EffectOwnershipLost),};match outcome {@@ -810,6 +833,34 @@ fn settings_service_receipt(.and_then(hiroute_domain::SettingsServiceCompletionV1::parse)}+/// Read readiness for a parked client-file tail. This does not authorize a new writer+/// or a file retry: the current publication must still match the sealed service proof.+pub fn settings_service_completion_is_current(+ operation: &OperationV1,+ publication_revision: u64,+ publication_digest: &CanonicalDigest,+) -> bool {+ operation.state == OperationState::Activating+ && operation.plan.spec().command_id == "agents.settings.apply"+ && operation+ .plan+ .external()+ .iter()+ .any(hiroute_domain::is_settings_managed_configuration)+ && operation.steps.iter().all(|step| {+ step.kind == OperationStepKind::Activate+ || step.status == OperationStepStatus::Applied+ })+ && settings_service_receipt(operation).is_some_and(|receipt| {+ receipt.publication_revision == publication_revision+ && receipt.publication_digest == *publication_digest+ && matches!(+ settings_service_completion_digest(operation, publication_revision, publication_digest),+ Ok(expected) if expected == receipt.completed_effects_digest+ )+ })+}+fn settings_service_completion_digest(operation: &OperationV1,publication_revision: u64,diff --git a/crates/application/src/operations/tests/settings_tail.rs b/crates/application/src/operations/tests/settings_tail.rsindex 514467fe..83d0d689 100644--- a/crates/application/src/operations/tests/settings_tail.rs+++ b/crates/application/src/operations/tests/settings_tail.rs@@ -44,11 +44,26 @@ fn settings_plan() -> TransactionPlanV1 {}fn settings_plan_with_login_item(host_login_item: bool) -> TransactionPlanV1 {+ settings_plan_for_action(host_login_item, false)+}++fn settings_plan_for_action(host_login_item: bool, restoring: bool) -> TransactionPlanV1 {+ let original = OperationId::derive(+ &WorkspaceId::default(),+ &IdempotencyScopeV1::new("interactive-user", "agents.settings.apply", "original").unwrap(),+ &CanonicalDigest::of_bytes(b"original"),+ );+ let mut settings = settings_spec();+ if restoring {+ settings.model = AgentFacetIntent::Restore {+ restore_point_ref: crate::agent_connection::codex_model_restore_point_ref(&original),+ };+ }let spec = hiroute_domain::ChangeSpecV1 {schema_version: CHANGE_SPEC_SCHEMA_V1,command_id: "agents.settings.apply".to_owned(),resource_id: Some(CONTEXT_ID.to_owned()),- desired_state: serde_json::to_value(settings_spec()).unwrap(),+ desired_state: serde_json::to_value(settings).unwrap(),};let subject = AgentConnectionTransactionSubjectV1::from_registered_profile("agent_codex_default",@@ -78,18 +93,29 @@ fn settings_plan_with_login_item(host_login_item: bool) -> TransactionPlanV1 {.unwrap();let scope =AgentAccessGrantScopeV1::new(format!("agent-connection/{CONTEXT_ID}"), grant).unwrap();- let mutation = AgentAccessGrantMutationV1::ensure(WorkspaceId::DEFAULT, scope, 0).unwrap();+ let mutation = if restoring {+ AgentAccessGrantMutationV1::revoke(WorkspaceId::DEFAULT, scope.connection_id(), 1).unwrap()+ } else {+ AgentAccessGrantMutationV1::ensure(WorkspaceId::DEFAULT, scope, 0).unwrap()+ };let model_file = settings_codex_model_file_intent(&control,CONTEXT_ID,CanonicalDigest::of_bytes(b"model-file-content"),None,- CodexModelFileAction::Configure {- previous_operation: None,- provider_id: "hiroute".to_owned(),- endpoint: "http://127.0.0.1:8787/v1".to_owned(),- model: None,- model_catalog: None,+ if restoring {+ CodexModelFileAction::Restore {+ original_operation: original,+ native_model: None,+ }+ } else {+ CodexModelFileAction::Configure {+ previous_operation: None,+ provider_id: "hiroute".to_owned(),+ endpoint: "http://127.0.0.1:8787/v1".to_owned(),+ model: None,+ model_catalog: None,+ }},).unwrap();@@ -326,10 +352,50 @@ fn client_file_failure_parks_the_tail_without_rollback() {);assert_eq!(ports.state.borrow().writer, None);+ let publication_digest = CanonicalDigest::of_bytes(PUBLICATION_EFFECT.as_bytes());+ assert!(settings_service_completion_is_current(+ &parked,+ 7,+ &publication_digest+ ));+ assert!(!settings_service_completion_is_current(+ &parked,+ 8,+ &publication_digest+ ));+ assert!(!settings_service_completion_is_current(+ &parked,+ 7,+ &CanonicalDigest::of_bytes(b"displaced")+ ));+ let mut tampered = parked.clone();+ tampered.accepted_digest = CanonicalDigest::of_bytes(b"another-accepted-change");+ assert!(!settings_service_completion_is_current(+ &tampered,+ 7,+ &publication_digest+ ));+ let mut incomplete = parked.clone();+ incomplete+ .step_mut(OperationStepKind::CompilePublication)+ .status = OperationStepStatus::Pending;+ assert!(!settings_service_completion_is_current(+ &incomplete,+ 7,+ &publication_digest+ ));+ports.state.borrow_mut().fail_activation = None;let finished = coordinator(&ports, &admission).run(&operation_id).unwrap();assert_eq!(finished.state, OperationState::Succeeded);+ assert!(+ finished+ .steps+ .iter()+ .all(|step| step.status == OperationStepStatus::Applied)+ );+ assert!(finished.safe_error_code.is_none());assert!(effect_applied(&ports, &operation_id, MODEL_FILE_EFFECT));let activations = ports.state@@ -468,3 +534,65 @@ fn settings_receipt_parse_accepts_only_the_registered_schema() {assert_eq!(SettingsServiceCompletionV1::parse("applied"), None);assert_eq!(SettingsServiceCompletionV1::parse("{}"), None);}++#[test]+fn settings_disable_restores_file_before_publication_and_grant() {+ let ports = MemoryPorts::default();+ let admission = TransactionRuntime::default();+ let id = inject_settings_operation_with_plan(&ports, settings_plan_for_action(false, true));+ let finished = coordinator(&ports, &admission).run(&id).unwrap();+ assert_eq!(finished.state, OperationState::Succeeded);+ let log = &ports.state.borrow().activation_log;+ let file = log.iter().position(|e| e == MODEL_FILE_EFFECT).unwrap();+ let publication = log.iter().position(|e| e == PUBLICATION_EFFECT).unwrap();+ let grant = log+ .iter()+ .position(|e| e.starts_with("agent-access-grant:"))+ .unwrap();+ assert!(file < publication && publication < grant, "{log:?}");+}++#[test]+fn settings_disable_failures_roll_back_and_release_writer() {+ for effect in [+ MODEL_FILE_EFFECT.to_owned(),+ PUBLICATION_EFFECT.to_owned(),+ format!("agent-access-grant:agent-connection/{CONTEXT_ID}"),+ ] {+ let ports = MemoryPorts::default();+ let admission = TransactionRuntime::default();+ let id = inject_settings_operation_with_plan(&ports, settings_plan_for_action(false, true));+ ports.state.borrow_mut().fail_activation = Some(effect.clone());+ let failed = coordinator(&ports, &admission).run(&id).unwrap();+ assert_eq!(failed.state, OperationState::RolledBack, "{effect}");+ assert!(failed.safe_error_code.is_some());+ assert!(+ SettingsServiceCompletionV1::parse(+ failed+ .step(OperationStepKind::Activate)+ .terminal_result+ .as_deref()+ .unwrap_or_default()+ )+ .is_none()+ );+ assert!(ports.state.borrow().writer.is_none(), "{effect}");+ assert!(ports.state.borrow().effects.is_empty(), "{effect}");+ if effect == MODEL_FILE_EFFECT {+ assert!(ports.state.borrow().activation_log.is_empty());+ } else {+ assert!(+ ports+ .state+ .borrow()+ .activation_log+ .iter()+ .any(|e| e == MODEL_FILE_EFFECT)+ );+ }+ coordinator(&ports, &admission)+ .reconcile_startup_and_open()+ .unwrap();+ assert!(admission.writes_open.load(Ordering::Acquire));+ }+}diff --git a/crates/cpa-bridge/src/accounts/stock/pin_tests.rs b/crates/cpa-bridge/src/accounts/stock/pin_tests.rsindex 847a815f..986b3433 100644--- a/crates/cpa-bridge/src/accounts/stock/pin_tests.rs+++ b/crates/cpa-bridge/src/accounts/stock/pin_tests.rs@@ -85,7 +85,7 @@ impl Fixture {} else {panic!("unexpected request: {}", header.lines().next().unwrap());};- write!(stream, "HTTP/1.1 {status} OK\r\nX-CPA-Version: 8.0.4-hiroute.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();+ write!(stream, "HTTP/1.1 {status} OK\r\nX-CPA-Version: 8.0.4-hiroute.2\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();}});Self {@@ -109,7 +109,7 @@ impl Fixture {generation: 1,}],&InstanceSecrets::generate().unwrap(),- "8.0.4-hiroute.1",+ "8.0.4-hiroute.2",Duration::from_secs(2),refresh,)diff --git a/crates/cpa-bridge/src/lib.rs b/crates/cpa-bridge/src/lib.rsindex cc5fc0a5..cc1ba141 100644--- a/crates/cpa-bridge/src/lib.rs+++ b/crates/cpa-bridge/src/lib.rs@@ -47,4 +47,4 @@ 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.1";+pub const MANAGED_CPA_ARTIFACT_VERSION: &str = "8.0.4-hiroute.2";diff --git a/crates/cpa-bridge/src/process.rs b/crates/cpa-bridge/src/process.rsindex 3c62ff29..746f139e 100644--- a/crates/cpa-bridge/src/process.rs+++ b/crates/cpa-bridge/src/process.rs@@ -38,6 +38,25 @@ pub trait CpaProcessBackend: Send + Sync {fn pid_is_running(&self, pid: u32) -> Result<bool, CpaProcessError>;}+// Keep private upstream credentials and shell execution hooks out of the child.+fn proxy_environment(+ vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,+) -> impl Iterator<Item = (std::ffi::OsString, std::ffi::OsString)> {+ vars.into_iter().filter(|(key, _)| {+ matches!(+ key.to_str(),+ Some(+ "HTTP_PROXY"+ | "HTTPS_PROXY"+ | "NO_PROXY"+ | "http_proxy"+ | "https_proxy"+ | "no_proxy"+ )+ )+ })+}+#[derive(Clone, Copy, Debug, Default)]pub struct StdCpaProcessBackend;@@ -53,6 +72,7 @@ impl CpaProcessBackend for StdCpaProcessBackend {.arg("--local-model").arg("--local-password-stdin").env_clear()+ .envs(proxy_environment(std::env::vars_os())).current_dir(&launch.work_dir).stdin(Stdio::piped()).stdout(Stdio::null())diff --git a/crates/cpa-bridge/src/process_tests.rs b/crates/cpa-bridge/src/process_tests.rsindex 199b8339..b526f9d2 100644--- a/crates/cpa-bridge/src/process_tests.rs+++ b/crates/cpa-bridge/src/process_tests.rs@@ -66,3 +66,27 @@ printf 'pipe-eof-ok' > resultb"pipe-eof-ok");}++#[test]+fn proxy_environment_preserves_bypass_without_forwarding_credentials_or_hooks() {+ let vars = [+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "NO_PROXY",+ "http_proxy",+ "https_proxy",+ "no_proxy",+ "OPENAI_API_KEY",+ "MANAGEMENT_PASSWORD",+ "LD_PRELOAD",+ "BASH_ENV",+ "HOME",+ ];+ let selected: Vec<_> =+ proxy_environment(vars.map(|key| (key.into(), "sentinel".into()))).collect();+ assert_eq!(selected.len(), 6);+ for (i, (key, value)) in selected.iter().enumerate() {+ assert_eq!(key, vars[i]);+ assert_eq!(value, "sentinel");+ }+}diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rsindex 40e38ea9..3547d7be 100644--- a/crates/daemon/src/control/runtime.rs+++ b/crates/daemon/src/control/runtime.rs@@ -81,6 +81,7 @@ mod protected_inputs;mod publication;mod release_install;mod routing;+mod settings_codex_profile;mod settings_facts;mod settings_status;mod source_authorization;@@ -326,6 +327,15 @@ impl ProductionControlRuntime {let codex_managed_target = AgentConnectionEffectRoleV1::ManagedConfiguration.target_for(&codex_subject).map_err(|error| error.to_string())?;+ let profile_subject = AgentConnectionTransactionSubjectV1::from_registered_profile(+ "agent_codex_default",+ hiroute_integrations::CODEX_STANDALONE_PROFILE_ID,+ CODEX_INTEGRATION_PROFILE_REF_V1,+ )+ .map_err(|error| error.to_string())?;+ let profile_target = AgentConnectionEffectRoleV1::ManagedConfiguration+ .target_for(&profile_subject)+ .map_err(|error| error.to_string())?;let artifacts = stores.open_managed_artifacts_with_external_targets(storage_root.join("managed-artifacts"),@@ -333,6 +343,7 @@ impl ProductionControlRuntime {[(claude_managed_target, scanner.claude_user_settings_target()),(codex_managed_target, scanner.codex_user_config_target()),+ (profile_target, scanner.codex_profile_config_target()),(AgentConnectionEffectRoleV1::RoutingSkill.target_for(&codex_subject)@@ -1111,6 +1122,13 @@ impl AgentDiscoveryPort for LocalControlAdapter {agent.available_surfaces = self.scanner.available_model_surfaces(&agent.agent_id);if agent.agent_id == "agent_codex_default" {agent.native_model_catalog = codex_catalog.clone();+ let access = self.codex_access_view()?;+ agent.context_id = Some(if access.selected_mode == "profile" {+ access.profile_context_id.clone()+ } else {+ access.root_context_id.clone()+ });+ agent.codex_access = Some(access);}Ok(agent)})@@ -1293,6 +1311,7 @@ fn discovered_agent(}).transpose()?;Ok(DiscoveredAgentV1 {+ codex_access: None,context_id: None,agent_id,profile_id,diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rsindex 7bc626a7..2661167a 100644--- a/crates/daemon/src/control/runtime/agent_connection.rs+++ b/crates/daemon/src/control/runtime/agent_connection.rs@@ -390,6 +390,13 @@ impl AgentConnectionControlPort for LocalControlAdapter {self.save_model_live_check_result(record)}+ fn retry_settings_operation(+ &self,+ request: &hiroute_application_api::AgentSettingsRetryV1,+ ) -> Result<hiroute_domain::OperationV1, ControlReadError> {+ self.retry_codex_operation(request)+ }+fn settings_status(&self,request: &hiroute_application_api::AgentSettingsStatusRequestV2,diff --git a/crates/daemon/src/control/runtime/agent_live_check.rs b/crates/daemon/src/control/runtime/agent_live_check.rsindex 9639ce77..9352d236 100644--- a/crates/daemon/src/control/runtime/agent_live_check.rs+++ b/crates/daemon/src/control/runtime/agent_live_check.rs@@ -110,9 +110,14 @@ impl LocalControlAdapter {deadline,)}- AgentModelSurfaceV2::CodexCli | AgentModelSurfaceV2::CodexDesktop => {- self.execute_codex_live_attempt(target.surface, model, trust, deadline)- }+ AgentModelSurfaceV2::CodexCli | AgentModelSurfaceV2::CodexDesktop => self+ .execute_codex_live_attempt(+ &target.context_id,+ target.surface,+ model,+ trust,+ deadline,+ ),};match result {Ok(evidence) => {@@ -224,6 +229,7 @@ impl LocalControlAdapter {fn execute_codex_live_attempt(&self,+ context_id: &str,surface: AgentModelSurfaceV2,model: &str,trust: &FrozenExecutionTrustV1,@@ -241,6 +247,26 @@ impl LocalControlAdapter {reason: CLIENT_FAILED,})?;let mut command = Command::new(executable);+ let root = self.scanner.codex_user_config_target();+ let home = root.parent().ok_or(AttemptFailure {+ executed: false,+ reason: CLIENT_FAILED,+ })?;+ command.env("CODEX_HOME", home);+ if self.settings_agent_for_context(context_id)+ == Some(super::settings_facts::SettingsAgentClass::CodexProfile)+ {+ if surface != AgentModelSurfaceV2::CodexCli {+ return Err(AttemptFailure {+ executed: false,+ reason: CLIENT_FAILED,+ });+ }+ command.args([+ "--profile",+ hiroute_integrations::CODEX_MANAGED_PROFILE_NAME,+ ]);+ }command.current_dir(working.path()).args(["exec","--json",diff --git a/crates/daemon/src/control/runtime/client_access.rs b/crates/daemon/src/control/runtime/client_access.rsindex 7ef301ee..14f4fb9d 100644--- a/crates/daemon/src/control/runtime/client_access.rs+++ b/crates/daemon/src/control/runtime/client_access.rs@@ -43,19 +43,30 @@ impl ClientAccessPort for LocalControlAdapter {let control = stores.control();let revisions = control.current_revisions(&workspace).map_err(map_port)?;let active = control.active_publication(&workspace).map_err(map_port)?;- let recovered = control- .recoverable_operations()+ let pending = control.recoverable_operations().map_err(map_port)?;+ let writer_released = control+ .writer_claim_operation().map_err(map_port)?- .is_empty()- && control- .writer_claim_operation()- .map_err(map_port)?- .is_none();+ .is_none();+ let recovered = pending.is_empty() && writer_released;+ // A verified service segment can be read while its client file awaits cleanup.+ // Ordinary mutations remain closed, and generic or displaced recovery stays blocked.+ let reads_ready = recovered+ || (writer_released+ && active.as_ref().is_some_and(|publication| {+ pending.iter().all(|operation| {+ hiroute_application::settings_service_completion_is_current(+ operation,+ publication.publication_revision.get(),+ &publication.digest,+ )+ })+ }));let composed = target.is_some();let gateway = match target.as_ref() {None => ClientGatewayStateV1::NotComposed,Some(target) => match target.observes_verified(active.as_ref()) {- Ok(true) if recovered => {+ Ok(true) if reads_ready => {if let Some(publication) = active.as_ref().and_then(|p| p.verify().ok())@@ -76,7 +87,7 @@ impl ClientAccessPort for LocalControlAdapter {Ok(ClientServiceStatusV1 {schema: "hiroute.client-service-status/v1".into(),daemon_role: if composed { "all" } else { "control_only" }.into(),- recovery_ready: recovered,+ recovery_ready: reads_ready,mutation_available: recovered&& composed&& gateway != ClientGatewayStateV1::Unavailable,diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rsindex a76dade0..76d99804 100644--- a/crates/daemon/src/control/runtime/collaboration_installation.rs+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs@@ -101,7 +101,9 @@ impl LocalControlAdapter {fn legacy_collaboration_artifact_path(&self, context: &str) -> PortResult<PathBuf> {let class = self.settings_agent_for_context(context).ok_or_else(error)?;let native = match class {- SettingsAgentClass::Codex => self.scanner.codex_user_config_target(),+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {+ self.scanner.codex_user_config_target()+ }SettingsAgentClass::Claude => self.scanner.claude_user_settings_target(),};let home = native@@ -112,7 +114,7 @@ impl LocalControlAdapter {.join(".hiroute").join("credential-artifacts").join(match class {- SettingsAgentClass::Codex => "codex.sealed",+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => "codex.sealed",SettingsAgentClass::Claude => "claude-code.sealed",}))}diff --git a/crates/daemon/src/control/runtime/effects.rs b/crates/daemon/src/control/runtime/effects.rsindex 87312f6a..fcbf2466 100644--- a/crates/daemon/src/control/runtime/effects.rs+++ b/crates/daemon/src/control/runtime/effects.rs@@ -239,6 +239,7 @@ impl ExternalEffectPort for LocalControlAdapter {operation: &hiroute_domain::OperationV1,intent: &ExternalEffectIntentV1,) -> PortResult<()> {+ self.acknowledge_clean_codex_restoration(operation, intent)?;if intent.effect_id() == "agent-connection-routing-skill"&& intent.desired()["transaction"] == "settings"{diff --git a/crates/daemon/src/control/runtime/mutation.rs b/crates/daemon/src/control/runtime/mutation.rsindex 4427d91d..74988bd3 100644--- a/crates/daemon/src/control/runtime/mutation.rs+++ b/crates/daemon/src/control/runtime/mutation.rs@@ -219,6 +219,7 @@ impl ControlRepositoryPort for LocalControlAdapter {}fn begin_local_operation(&self, operation: &OperationV1) -> PortResult<BeginOperationOutcome> {+ self.guard_codex_pending_change(Some(&operation.operation_id))?;self.stores_lock()?.control().begin_local_operation(operation)@@ -248,6 +249,7 @@ impl ControlRepositoryPort for LocalControlAdapter {operation: &OperationV1,authorization: &VerifiedApplyAuthorizationV1,) -> PortResult<BeginOperationOutcome> {+ self.guard_codex_pending_change(Some(&operation.operation_id))?;self.stores_lock()?.control().begin_operation(operation, authorization)diff --git a/crates/daemon/src/control/runtime/native_claude_model.rs b/crates/daemon/src/control/runtime/native_claude_model.rsindex a11bc94c..b781555f 100644--- a/crates/daemon/src/control/runtime/native_claude_model.rs+++ b/crates/daemon/src/control/runtime/native_claude_model.rs@@ -26,10 +26,18 @@ impl LocalControlAdapter {) -> PortResult<OwnedEffectV1> {let stores = self.stores_lock()?;let operation_id = &operation.operation_id;- if operation.state != OperationState::ApplyingAgentArtifacts {+ let payload = settings_claude_model_file_for_operation(operation, intent)?;+ let restoration_tail = operation.state == OperationState::Activating+ && matches!(&payload.change, ClaudeModelFileAction::Restore { .. })+ && operation+ .step(hiroute_domain::OperationStepKind::Activate)+ .terminal_result+ .as_deref()+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)+ .is_some();+ if operation.state != OperationState::ApplyingAgentArtifacts && !restoration_tail {return Err(conflict("claude.settings.phase"));}- let payload = settings_claude_model_file_for_operation(operation, intent)?;match &payload.change {ClaudeModelFileAction::Configure {previous_operation,diff --git a/crates/daemon/src/control/runtime/native_model.rs b/crates/daemon/src/control/runtime/native_model.rsindex e68f27a9..3eeb54f9 100644--- a/crates/daemon/src/control/runtime/native_model.rs+++ b/crates/daemon/src/control/runtime/native_model.rs@@ -125,6 +125,97 @@ pub(super) fn codex_catalog_plan_for(}impl LocalControlAdapter {+ pub(super) fn acknowledge_clean_codex_restoration(+ &self,+ operation: &hiroute_domain::OperationV1,+ intent: &ExternalEffectIntentV1,+ ) -> PortResult<()> {+ if !is_settings_codex_model(intent)+ || operation+ .step(OperationStepKind::Activate)+ .terminal_result+ .as_deref()+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)+ .is_none()+ {+ return Ok(());+ }+ let state = self+ .artifacts+ .observe_artifact(&operation.operation_id, intent)?;+ if !matches!(+ state,+ EffectReconciliation::Missing | EffectReconciliation::OwnershipLost(_)+ ) {+ return Ok(());+ }+ self.require_current_operation(operation)?;+ let payload = settings_codex_model_file_for_operation(operation, intent)?;+ let CodexModelFileAction::Restore {+ original_operation,+ native_model,+ } = payload.change+ else {+ return Ok(());+ };+ let stores = self.stores_lock()?;+ let original = stores+ .control()+ .load_operation(&original_operation)?+ .ok_or_else(|| conflict("codex.restore.ack.original"))?;+ if original.workspace_id != operation.workspace_id+ || original.state != OperationState::Succeeded+ {+ return Err(conflict("codex.restore.ack.owner"));+ }+ let original_intent = original+ .plan+ .external()+ .iter()+ .find(|i| is_settings_codex_model(i) && i.target() == intent.target())+ .ok_or_else(|| conflict("codex.restore.ack.intent"))?;+ let before = settings_codex_model_file_for_operation(&original, original_intent)?;+ if before.context_id != payload.context_id+ || !matches!(before.change, CodexModelFileAction::Configure { .. })+ {+ return Err(conflict("codex.restore.ack.context"));+ }+ drop(stores);+ let record = self+ .artifacts+ .load_native_restore(&original_operation, original_intent)?+ .ok_or_else(|| conflict("codex.restore.ack.record"))?;+ if record.len() < 3 || record[0] != 1 || record[1] > 1 {+ return Err(conflict("codex.restore.ack.schema"));+ }+ let restore = hiroute_integrations::CodexNativeRestore::decode_protected(&record[2..])+ .map_err(|_| conflict("codex.restore.ack.decode"))?;+ let current = self.artifacts.read_native_target(intent.target())?;+ let text = std::str::from_utf8(current.as_deref().map_or(&[], |b| b.as_slice()))+ .map_err(|_| conflict("codex.restore.ack.encoding"))?;+ let restored = hiroute_integrations::restore_codex_native_with_model(+ text,+ &restore,+ native_model.as_deref(),+ )+ .map_err(|_| conflict("codex.restore.ack.fields"))?;+ // Only acknowledge complete cleanup. Remaining owned fields require user repair;+ // neither comments nor unrelated edits are overwritten or rebased by this path.+ if restored.as_str() != text {+ // A first deferred preparation still needs to render and stage restoration.+ if matches!(state, EffectReconciliation::Missing) {+ return Ok(());+ }+ return Err(conflict("codex.restore.ack.incomplete"));+ }+ self.artifacts.acknowledge_native_restoration(+ &operation.operation_id,+ intent,+ current.as_deref().map(|b| b.as_slice()),+ )?;+ Ok(())+ }+pub(super) fn stage_settings_codex_catalog(&self,operation: &hiroute_domain::OperationV1,@@ -177,12 +268,17 @@ impl LocalControlAdapter {.find(|candidate| candidate.kind() == hiroute_domain::OwnedEffectKind::Publication).ok_or_else(|| conflict("codex.catalog.publication.intent"))?.clone();- let baseline = codex_catalog_baseline(+ let mut baseline = codex_catalog_baseline(stores.control(),&self.artifacts,previous_operation.as_ref(),model_intent.target(),)?;+ if self.settings_agent_for_context(&payload.context_id)+ == Some(super::settings_facts::SettingsAgentClass::CodexProfile)+ {+ baseline = CodexCatalogBaseline::Scope;+ }drop(stores);let publication = self.publication_record_from_operation(operation, &publication_intent)?@@ -236,10 +332,18 @@ impl LocalControlAdapter {) -> PortResult<OwnedEffectV1> {let stores = self.stores_lock()?;let operation_id = &operation.operation_id;- if operation.state != OperationState::ApplyingAgentArtifacts {+ let payload = settings_codex_model_file_for_operation(operation, intent)?;+ let restoration_tail = operation.state == OperationState::Activating+ && matches!(&payload.change, CodexModelFileAction::Restore { .. })+ && operation+ .step(OperationStepKind::Activate)+ .terminal_result+ .as_deref()+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)+ .is_some();+ if operation.state != OperationState::ApplyingAgentArtifacts && !restoration_tail {return Err(conflict("codex.settings.phase"));}- let payload = settings_codex_model_file_for_operation(operation, intent)?;match &payload.change {CodexModelFileAction::Configure {previous_operation,diff --git a/crates/daemon/src/control/runtime/native_model_tests.rs b/crates/daemon/src/control/runtime/native_model_tests.rsindex ef6963a3..e96ffa6f 100644--- a/crates/daemon/src/control/runtime/native_model_tests.rs+++ b/crates/daemon/src/control/runtime/native_model_tests.rs@@ -669,7 +669,7 @@ fn open_with_codex_fixture_surfaces(write_codex_fixture(&cli);write_codex_fixture(&desktop);let home = root.join("home");- fs::create_dir(&home).unwrap();+ fs::create_dir_all(&home).unwrap();fs::set_permissions(&home, fs::Permissions::from_mode(0o700)).unwrap();let mut layout = AgentFilesystemLayoutV1::from_process(&home, root);layout.codex_executable = cli.clone();diff --git a/crates/daemon/src/control/runtime/publication/lifecycle.rs b/crates/daemon/src/control/runtime/publication/lifecycle.rsindex 55e1110f..c396c529 100644--- a/crates/daemon/src/control/runtime/publication/lifecycle.rs+++ b/crates/daemon/src/control/runtime/publication/lifecycle.rs@@ -19,6 +19,7 @@ impl LocalControlAdapter {if intent.kind() != OwnedEffectKind::Publication {return Ok(());}+ self.guard_codex_pending_change(None)?;if intent.desired()["transaction"] == "settings" {hiroute_domain::validate_settings_model_publication_intent(intent).map_err(|_| invalid("publication.settings.admission"))?;@@ -71,6 +72,7 @@ impl LocalControlAdapter {operation: &OperationV1,) -> PortResult<()> {self.require_current_operation(operation)?;+ self.guard_codex_pending_change(Some(&operation.operation_id))?;self.begin_plan_content_activation(operation)?;// Settings model publications are hot-swappable: the aggregate ArcSwap cutover keeps// every in-flight pin on its old root, so normal B updates never suspend admission.diff --git a/crates/daemon/src/control/runtime/settings_codex_profile.rs b/crates/daemon/src/control/runtime/settings_codex_profile.rsnew file mode 100644index 00000000..e3053cd3--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_codex_profile.rs@@ -0,0 +1,363 @@+//! One CODEX_HOME slot, two explicit targets. Reuse existing durable Operations and grants.+use super::settings_facts::SettingsAgentClass;+use super::*;+use hiroute_application::control::CodexAccessViewV1;+use hiroute_domain::{+ AgentFacetIntent, AgentSettingsSpecV2, ControlRepositoryPort, SecretStorePort,+};++impl LocalControlAdapter {+ pub(super) fn guard_codex_pending_change(+ &self,+ same_operation: Option<&hiroute_domain::OperationId>,+ ) -> hiroute_domain::PortResult<()> {+ let stores = self.stores_lock()?;+ for op in stores.control().recoverable_operations()? {+ if same_operation == Some(&op.operation_id) {+ continue;+ }+ let has_receipt = op+ .step(hiroute_domain::OperationStepKind::Activate)+ .terminal_result+ .as_deref()+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)+ .is_some();+ if has_receipt+ && op+ .plan+ .external()+ .iter()+ .any(super::native_model::is_settings_codex_model)+ {+ return Err(hiroute_domain::PortError::new(+ hiroute_domain::PortErrorCode::Conflict,+ "codex.pending_file_tail.change",+ ));+ }+ }+ Ok(())+ }++ fn codex_slot_state(+ &self,+ ) -> Result<+ (+ Option<SettingsAgentClass>,+ Option<hiroute_domain::OperationV1>,+ ),+ ControlReadError,+ > {+ let stores = self.stores_lock().map_err(super::map_port)?;+ let root = self.settings_context(SettingsAgentClass::Codex);+ let profile = self.settings_context(SettingsAgentClass::CodexProfile);+ let classify = |context: &str| {+ if context == root {+ Some(SettingsAgentClass::Codex)+ } else if context == profile {+ Some(SettingsAgentClass::CodexProfile)+ } else {+ None+ }+ };+ // A parked file tail releases the global writer but still owns this home slot.+ for op in stores+ .control()+ .recoverable_operations()+ .map_err(super::map_port)?+ {+ if op.plan.spec().command_id == "agents.settings.apply"+ && let Some(context) = op.plan.spec().resource_id.as_deref()+ && let Some(class) = classify(context)+ {+ let spec: AgentSettingsSpecV2 =+ serde_json::from_value(op.plan.spec().desired_state.clone())+ .map_err(|_| ControlReadError::Corrupt)?;+ if !matches!(spec.model, AgentFacetIntent::Keep) {+ return Ok((Some(class), Some(op)));+ }+ }+ }+ let mut active = None;+ for (context, class) in [+ (&root, SettingsAgentClass::Codex),+ (&profile, SettingsAgentClass::CodexProfile),+ ] {+ if stores+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{context}"),+ )+ .map_err(super::map_port)?+ .is_some()+ {+ if active.is_some() {+ return Err(ControlReadError::Corrupt);+ }+ active = Some(class);+ }+ }+ Ok((active, None))+ }++ pub(super) fn check_codex_slot(+ &self,+ spec: &AgentSettingsSpecV2,+ class: SettingsAgentClass,+ ) -> Result<(), ControlReadError> {+ if !class.is_codex() {+ return Ok(());+ }+ if class == SettingsAgentClass::CodexProfile+ && (!matches!(spec.collaboration, AgentFacetIntent::Keep)+ || spec.restore_native_model.is_some())+ {+ return Err(ControlReadError::Denied);+ }+ if matches!(spec.model, AgentFacetIntent::Keep) {+ return Ok(());+ }+ if class == SettingsAgentClass::CodexProfile+ && matches!(spec.model, AgentFacetIntent::Configure { .. })+ && !self+ .scanner+ .available_model_surfaces(class.agent_id())+ .contains(&hiroute_domain::AgentModelSurfaceV2::CodexCli)+ {+ return Err(ControlReadError::Denied);+ }+ let (active, pending) = self.codex_slot_state()?;+ if pending.is_some() || active.is_some_and(|owner| owner != class) {+ return Err(ControlReadError::SnapshotChanged);+ }+ Ok(())+ }++ pub(super) fn codex_profile_dependencies(+ &self,+ class: SettingsAgentClass,+ spec: &AgentSettingsSpecV2,+ owner: Option<&hiroute_domain::OperationId>,+ ) -> Result<Option<CanonicalDigest>, ControlReadError> {+ if class != SettingsAgentClass::CodexProfile+ || !matches!(spec.model, AgentFacetIntent::Configure { .. })+ {+ return Ok(None);+ }+ hiroute_integrations::codex_profile_dependency_digest(+ &self.scanner.codex_user_config_target(),+ owner.is_some(),+ )+ .map(Some)+ .map_err(|_| ControlReadError::SnapshotChanged)+ }++ pub(super) fn codex_access_view(&self) -> Result<CodexAccessViewV1, ControlReadError> {+ let root = self.scanner.codex_user_config_target();+ let home = root.parent().ok_or(ControlReadError::Corrupt)?;+ let (owner, pending) = self.codex_slot_state()?;+ let class = owner.unwrap_or(SettingsAgentClass::CodexProfile);+ let context = self.settings_context(class);+ let grant = self+ .stores_lock()+ .map_err(super::map_port)?+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{context}"),+ )+ .map_err(super::map_port)?;+ let conflict_fields = if let Some(op) = pending.as_ref() {+ self.codex_conflicts(op, true)?+ } else if let Some(grant) = grant.as_ref() {+ self.active_codex_conflicts(&context, grant)?+ } else {+ Vec::new()+ };+ let commands = if class == SettingsAgentClass::CodexProfile {+ hiroute_integrations::codex_profile_commands(home)+ .map_err(|_| ControlReadError::Corrupt)?+ } else {+ Default::default()+ };+ Ok(CodexAccessViewV1 {+ codex_home: home.to_string_lossy().into_owned(),+ slot_id: format!(+ "codex-home/{}",+ CanonicalDigest::of_bytes(home.as_os_str().as_encoded_bytes()).as_str()+ ),+ profile_context_id: self.settings_context(SettingsAgentClass::CodexProfile),+ root_context_id: self.settings_context(SettingsAgentClass::Codex),+ selected_mode: if class == SettingsAgentClass::CodexProfile {+ "profile"+ } else {+ "root"+ }+ .into(),+ slot_occupied: owner.is_some(),+ target_file: class+ .native_path(&self.scanner)+ .to_string_lossy()+ .into_owned(),+ profile_name: hiroute_integrations::CODEX_MANAGED_PROFILE_NAME.into(),+ commands,+ pending_operation: pending.as_ref().map(|op| op.operation_id.to_string()),+ access_revoked: grant.is_none(),+ conflict_fields,+ })+ }+}++impl LocalControlAdapter {+ fn active_codex_conflicts(+ &self,+ context: &str,+ grant: &hiroute_domain::AgentAccessGrantRefV1,+ ) -> Result<Vec<String>, ControlReadError> {+ let stores = self.stores_lock().map_err(super::map_port)?;+ for original in stores+ .control()+ .succeeded_agent_operations_for_kind(+ &WorkspaceId::default(),+ "ApplyAgentConnectionChange",+ )+ .map_err(super::map_port)?+ {+ if original.plan.spec().resource_id.as_deref() != Some(context) {+ continue;+ }+ let [mutation] = original.plan.agent_access_grants() else {+ continue;+ };+ let Some(effect) = original+ .step(hiroute_domain::OperationStepKind::ApplySecrets)+ .effects+ .iter()+ .find(|effect| hiroute_domain::is_agent_access_grant_effect(effect))+ else {+ continue;+ };+ let reference =+ hiroute_domain::AgentAccessGrantRefV1::from_ensure_effect(effect, mutation)+ .map_err(|_| ControlReadError::Corrupt)?;+ if &reference == grant {+ let op = stores+ .control()+ .load_operation(&original.operation_id)+ .map_err(super::map_port)?+ .ok_or(ControlReadError::Corrupt)?;+ drop(stores);+ return self.codex_conflicts(&op, false);+ }+ }+ Ok(Vec::new())+ }++ fn codex_conflicts(+ &self,+ op: &hiroute_domain::OperationV1,+ pending: bool,+ ) -> Result<Vec<String>, ControlReadError> {+ use hiroute_application::agent_connection::{+ CodexModelFileAction, settings_codex_model_file_for_operation,+ };+ use hiroute_domain::NativeAgentArtifactPort;+ let intent = op+ .plan+ .external()+ .iter()+ .find(|i| super::native_model::is_settings_codex_model(i))+ .ok_or(ControlReadError::Corrupt)?;+ let payload =+ settings_codex_model_file_for_operation(op, intent).map_err(super::map_port)?;+ let restoring = matches!(&payload.change, CodexModelFileAction::Restore { .. });+ let original_id = match payload.change {+ CodexModelFileAction::Restore {+ original_operation, ..+ } => original_operation,+ CodexModelFileAction::Configure { .. } => op.operation_id.clone(),+ };+ let stores = self.stores_lock().map_err(super::map_port)?;+ let original = stores+ .control()+ .load_operation(&original_id)+ .map_err(super::map_port)?+ .ok_or(ControlReadError::Corrupt)?;+ let original_intent = original+ .plan+ .external()+ .iter()+ .find(|i| i.target() == intent.target())+ .ok_or(ControlReadError::Corrupt)?;+ // Diagnose the live path first: restore AAD validation also rejects unsafe targets.+ let current = match self.artifacts.read_native_target(intent.target()) {+ Ok(current) => current,+ Err(_) => return Ok(vec!["configuration_unreadable".into()]),+ };+ let Ok(text) = std::str::from_utf8(current.as_deref().map_or(&[], |v| v.as_slice())) else {+ return Ok(vec!["configuration_encoding".into()]);+ };+ let record = self+ .artifacts+ .load_native_restore(&original_id, original_intent)+ .map_err(super::map_port)?;+ let Some(record) = record else {+ return Ok(vec!["configuration_snapshot".into()]);+ };+ if record.len() < 3 || record[0] != 1 || record[1] > 1 {+ return Err(ControlReadError::Corrupt);+ }+ let restore = hiroute_integrations::CodexNativeRestore::decode_protected(&record[2..])+ .map_err(|_| ControlReadError::Corrupt)?;+ if restoring {+ return Ok(restore.pending_restoration_fields(text));+ }+ let mut fields = restore.conflicting_fields(text);+ if pending && fields.is_empty() {+ fields.push("configuration_snapshot".into());+ }+ Ok(fields)+ }++ pub(super) fn retry_codex_operation(+ &self,+ request: &hiroute_application_api::AgentSettingsRetryV1,+ ) -> Result<hiroute_domain::OperationV1, ControlReadError> {+ if request.schema != "hiroute.agent-settings-retry/v1"+ || self+ .settings_agent_for_context(&request.context_id)+ .is_none_or(|class| !class.is_codex())+ {+ return Err(ControlReadError::Denied);+ }+ let stores = self.stores_lock().map_err(super::map_port)?;+ let op = stores+ .control()+ .load_operation(&request.operation_id)+ .map_err(super::map_port)?+ .ok_or(ControlReadError::NotFound)?;+ if op.workspace_id != WorkspaceId::default()+ || op.plan.spec().command_id != "agents.settings.apply"+ || op.plan.spec().resource_id.as_deref() != Some(&request.context_id)+ {+ return Err(ControlReadError::Denied);+ }+ let spec: AgentSettingsSpecV2 =+ serde_json::from_value(op.plan.spec().desired_state.clone())+ .map_err(|_| ControlReadError::Corrupt)?;+ if matches!(spec.model, AgentFacetIntent::Keep) {+ return Err(ControlReadError::Denied);+ }+ drop(stores);+ hiroute_application::TransactionCoordinator::new(+ self,+ self,+ self,+ self,+ self,+ &self.admission,+ )+ .run(&request.operation_id)+ .map_err(|_| ControlReadError::Unavailable)+ }+}diff --git a/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs b/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rsindex 03bf3171..3d67be26 100644--- a/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs@@ -48,7 +48,7 @@ fn v2_settings_skill_only_enable_change_and_disable_keep_model_untouched() {.unwrap().iter().find(|agent| agent["agent_id"] == "agent_codex_default")- .unwrap()["context_id"]+ .unwrap()["codex_access"]["root_context_id"].as_str().unwrap().to_owned();@@ -242,7 +242,7 @@ fn v2_settings_releases_borrowed_skill_after_user_file_drift() {.unwrap().iter().find(|agent| agent["agent_id"] == "agent_codex_default")- .unwrap()["context_id"]+ .unwrap()["codex_access"]["root_context_id"].as_str().unwrap().to_owned();diff --git a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rsindex 97b3cdbc..65963235 100644--- a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs@@ -68,7 +68,7 @@ fn v2_settings_skill_only_works_before_the_first_publication() {.unwrap().iter().find(|agent| agent["agent_id"] == "agent_codex_default")- .unwrap()["context_id"]+ .unwrap()["codex_access"]["root_context_id"].as_str().unwrap().to_owned();diff --git a/crates/daemon/src/control/runtime/settings_entry_tests.rs b/crates/daemon/src/control/runtime/settings_entry_tests.rsindex e1fa74f4..86e4b7da 100644--- a/crates/daemon/src/control/runtime/settings_entry_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_tests.rs@@ -70,7 +70,10 @@ fn v2_settings_first_save_without_native_probe_and_reenable_identical_catalog()codex["supported"], true,"the V2 settings entry treats an executable version as diagnostic, not an allowlist");- let context = codex["context_id"].as_str().unwrap().to_owned();+ let context = codex["codex_access"]["root_context_id"]+ .as_str()+ .unwrap()+ .to_owned();let plans = runtime.adapter.stores_lock()@@ -295,7 +298,7 @@ fn v2_settings_first_save_without_native_probe_and_reenable_identical_catalog()1);let configured = fs::read_to_string(&path).unwrap();- fs::write(&path, format!("{configured}unrelated_native = true\n")).unwrap();+ fs::write(&path, format!("unrelated_native = true\n{configured}")).unwrap();apply(&ordinary,&runtime,@@ -532,7 +535,10 @@ fn exercise_settings_entry() {codex["supported"], true,"the V2 settings entry treats an executable version as diagnostic, not an allowlist");- let context = codex["context_id"].as_str().unwrap().to_owned();+ let context = codex["codex_access"]["root_context_id"]+ .as_str()+ .unwrap()+ .to_owned();let plans = runtime.adapter.stores_lock()@@ -1002,3 +1008,6 @@ impl AgentConnectionControlPort for FixtureFacts {#[path = "settings_entry_facets_tests.rs"]mod facets;++#[path = "settings_profile_tests.rs"]+mod settings_profile_tests;diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rsindex d415b945..b05dad9a 100644--- a/crates/daemon/src/control/runtime/settings_facts.rs+++ b/crates/daemon/src/control/runtime/settings_facts.rs@@ -49,41 +49,47 @@ struct CodexRestoreModelFacts {#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(super) enum SettingsAgentClass {Codex,+ CodexProfile,Claude,}impl SettingsAgentClass {+ pub(super) fn is_codex(self) -> bool {+ self != Self::Claude+ }+pub(super) fn agent_id(self) -> &'static str {match self {- Self::Codex => "agent_codex_default",+ Self::Codex | Self::CodexProfile => "agent_codex_default",Self::Claude => "agent_claude_default",}}fn context_segment(self) -> &'static str {match self {- Self::Codex => "codex",+ Self::Codex | Self::CodexProfile => "codex",Self::Claude => "claude",}}- fn native_path(self, scanner: &FilesystemAgentScannerV1) -> std::path::PathBuf {+ pub(super) fn native_path(self, scanner: &FilesystemAgentScannerV1) -> std::path::PathBuf {match self {Self::Codex => scanner.codex_user_config_target(),+ Self::CodexProfile => scanner.codex_profile_config_target(),Self::Claude => scanner.claude_user_settings_target(),}}pub(super) fn skill_root_ref(self) -> &'static str {match self {- Self::Codex => "skill-root/agent_codex_default",+ Self::Codex | Self::CodexProfile => "skill-root/agent_codex_default",Self::Claude => "skill-root/agent_claude_default",}}pub(super) fn skill_target(self) -> Result<String, hiroute_domain::OperationValidationError> {let (profile_id, integration_profile_ref) = match self {- Self::Codex => (+ Self::Codex | Self::CodexProfile => (hiroute_integrations::CODEX_PROFILE_ID_V1,hiroute_integrations::CODEX_INTEGRATION_PROFILE_REF_V1,),@@ -112,12 +118,16 @@ impl LocalControlAdapter {}pub(super) fn settings_agent_for_context(&self, context: &str) -> Option<SettingsAgentClass> {- [SettingsAgentClass::Codex, SettingsAgentClass::Claude]- .into_iter()- .find(|class| context == self.settings_context(*class))+ [+ SettingsAgentClass::Codex,+ SettingsAgentClass::CodexProfile,+ SettingsAgentClass::Claude,+ ]+ .into_iter()+ .find(|class| context == self.settings_context(*class))}- fn settings_context(&self, class: SettingsAgentClass) -> String {+ pub(super) fn settings_context(&self, class: SettingsAgentClass) -> String {let path = class.native_path(&self.scanner);let digest = CanonicalDigest::of_bytes(path.as_os_str().as_encoded_bytes());format!(@@ -134,6 +144,7 @@ impl LocalControlAdapter {let class = self.settings_agent_for_context(&spec.context_id).ok_or(ControlReadError::NotFound)?;+ self.check_codex_slot(spec, class)?;let first = self.settings_snapshot(spec, class)?;let second = self.settings_snapshot(spec, class)?;if first.facts.dependency_digest != second.facts.dependency_digest {@@ -180,6 +191,8 @@ impl LocalControlAdapter {&spec.collaboration,AgentFacetIntent::Configure { .. }))+ } else if class == SettingsAgentClass::CodexProfile {+ self.scanner.codex_profile_settings_discovery()} else {self.scanner.codex_settings_discovery(matches!(&spec.collaboration,@@ -232,7 +245,11 @@ impl LocalControlAdapter {});let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(installation.agent_id.clone(),- installation.profile.profile_id.clone(),+ if class == SettingsAgentClass::CodexProfile {+ hiroute_integrations::CODEX_STANDALONE_PROFILE_ID.to_owned()+ } else {+ installation.profile.profile_id.clone()+ },installation.profile.integration_profile_ref.clone(),).map_err(|_| ControlReadError::Corrupt)?;@@ -259,8 +276,9 @@ impl LocalControlAdapter {}drop(bytes);- let skill_target = AgentConnectionEffectRoleV1::RoutingSkill- .target_for(&subject)+ // Collaboration belongs to the original home, not the standalone model profile.+ let skill_target = class+ .skill_target().map_err(|_| ControlReadError::Corrupt)?;let skill_before_fingerprint = self.artifacts@@ -339,7 +357,9 @@ impl LocalControlAdapter {// New settings saves do not manage startup. Keep the preview field for V2 clients;// only an older, journal-owned login item may require cleanup on final restore.let other_context = match class {- SettingsAgentClass::Codex => SettingsAgentClass::Claude,+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {+ SettingsAgentClass::Claude+ }SettingsAgentClass::Claude => SettingsAgentClass::Codex,};let other_grant = stores@@ -406,7 +426,7 @@ impl LocalControlAdapter {selected_collaboration_restore = Some(original.operation_id.clone());}let model = match class {- SettingsAgentClass::Codex => original+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => original.plan.external().iter()@@ -526,7 +546,7 @@ impl LocalControlAdapter {};let mut fixed_candidate_facts = match &spec.model {AgentFacetIntent::Configure { settings }- if class == SettingsAgentClass::Codex || !settings.fixed_models().is_empty() =>+ if class.is_codex() || !settings.fixed_models().is_empty() =>{match self.routing_compilation_snapshot(&workspace) {Ok(snapshot) => snapshot.facts.candidates,@@ -552,13 +572,13 @@ impl LocalControlAdapter {&& let Some(active) = active_configuration.as_ref(){self.codex_restore_model_facts(active, &target)?.catalog- } else if class == SettingsAgentClass::Codex {+ } else if class.is_codex() {self.scanner.codex_catalog_summary().ok()} else {None};let native_default_model = match class {- SettingsAgentClass::Codex => codex_catalog_summary+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => codex_catalog_summary.as_ref().map(|catalog| catalog.native_default_model.clone()),SettingsAgentClass::Claude => self@@ -620,7 +640,7 @@ impl LocalControlAdapter {None};let collaboration_state = self.settings_collaboration_state(spec)?;- let original_native_ids = if class == SettingsAgentClass::Codex+ let original_native_ids = if class.is_codex()&& preserve_native_models&& matches!(&spec.model, AgentFacetIntent::Configure { .. }){@@ -643,7 +663,14 @@ impl LocalControlAdapter {},Some(catalog),) if preserve_native_models && active_protected_native_ids.is_empty() => self- .preserved_codex_model_selections(catalog, &mut fixed_candidate_facts)+ .preserved_codex_model_selections(+ catalog,+ &mut fixed_candidate_facts,+ active_configuration+ .as_ref()+ .filter(|_| class == SettingsAgentClass::Codex)+ .map(|op| (op, target.as_str())),+ ).unwrap_or_default(),(AgentFacetIntent::Configure { .. }, _)if preserve_native_models && !active_protected_native_ids.is_empty() =>@@ -694,38 +721,40 @@ impl LocalControlAdapter {.filter(|name| !proven_native_model_ids.contains(name)).collect::<Vec<_>>();let native_default_must_be_original = preserve_native_models;- let mut model_catalog =- if let (SettingsAgentClass::Codex, AgentFacetIntent::Configure { settings }) =- (class, &spec.model)+ let mut model_catalog = if let (+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile,+ AgentFacetIntent::Configure { settings },+ ) = (class, &spec.model)+ {+ let baseline = if class == SettingsAgentClass::CodexProfile {+ hiroute_integrations::CodexCatalogBaseline::Scope+ } else {+ let stores = self.stores_lock().map_err(super::map_port)?;+ super::native_model::codex_catalog_baseline(+ stores.control(),+ &self.artifacts,+ active_configuration.as_ref(),+ &target,+ )+ .map_err(super::map_port)?+ };+ let mut complete = settings.clone();+ if let hiroute_domain::AgentModelSelectionV2::CodexDefault { fixed_models, .. } =+ &mut complete{- let baseline = {- let stores = self.stores_lock().map_err(super::map_port)?;- super::native_model::codex_catalog_baseline(- stores.control(),- &self.artifacts,- active_configuration.as_ref(),- &target,- )- .map_err(super::map_port)?- };- let mut complete = settings.clone();- if let hiroute_domain::AgentModelSelectionV2::CodexDefault {- fixed_models, ..- } = &mut complete- {- for preserved in &preserved_codex_models {- if !fixed_models- .iter()- .any(|model| model.client_model_id == preserved.client_model_id)- {- fixed_models.push(preserved.clone());- }+ for preserved in &preserved_codex_models {+ if !fixed_models+ .iter()+ .any(|model| model.client_model_id == preserved.client_model_id)+ {+ fixed_models.push(preserved.clone());}}- self.codex_catalog_facts(&complete, active.as_ref(), &baseline, &mut installation)- } else {- None- };+ }+ self.codex_catalog_facts(&complete, active.as_ref(), &baseline, &mut installation)+ } else {+ None+ };if let Some(catalog) = model_catalog.as_mut() {let catalog_target = settings_codex_catalog_target(&subject, &spec.context_id, catalog).map_err(|_| ControlReadError::Corrupt)?;@@ -763,7 +792,7 @@ impl LocalControlAdapter {== hiroute_domain::CollaborationSkillFileOwnership::BorrowedIdentical&& record.contexts.contains(&spec.context_id)});- let codex_context_override = class == SettingsAgentClass::Codex+ let codex_context_override = class.is_codex()&& matches!(&spec.model, AgentFacetIntent::Configure { settings } if !settings.allowed_plan_ids().is_empty())&& hiroute_integrations::codex_has_context_override(&hiroute_integrations::CodexConfigurationScope::user_file(@@ -791,6 +820,7 @@ impl LocalControlAdapter {.claude_context_override().map_err(|_| ControlReadError::Unavailable)?;let dependency_digest = CanonicalDigest::of(&serde_json::json!({+ "codex_profile_dependencies": self.codex_profile_dependencies(class, spec, active_configuration.as_ref())?,"claude_context_override": claude_context_override,"claude_plan_capability_unavailable": claude_plan_capability_unavailable,"codex_context_override": codex_context_override,@@ -814,6 +844,7 @@ impl LocalControlAdapter {"native_default_must_be_original":native_default_must_be_original,"native_claude_presets":native_claude_presets,"restore_native_model_ids":restore_native_model_ids,+ "restore_inherits_root":class == SettingsAgentClass::CodexProfile,"restored_native_model":restored_native_model,"collaboration_file_conflict":collaboration_file_conflict,"model_catalog":&model_catalog,@@ -834,10 +865,12 @@ impl LocalControlAdapter {)).map_err(|_| ControlReadError::Corrupt)?;let model_target = match class {- SettingsAgentClass::Codex => SettingsModelTargetFacts::Codex {- provider_id: "hiroute".into(),- endpoint: runtime.gateway_base_url.clone(),- },+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => {+ SettingsModelTargetFacts::Codex {+ provider_id: "hiroute".into(),+ endpoint: runtime.gateway_base_url.clone(),+ }+ }SettingsAgentClass::Claude => {SettingsModelTargetFacts::Claude(SettingsClaudeModelFacts {installation: installation.clone(),@@ -896,6 +929,7 @@ impl LocalControlAdapter {native_default_model,native_claude_presets,restore_native_model_ids,+ restore_inherits_root: class == SettingsAgentClass::CodexProfile,restored_native_model,collaboration_file_conflict,restore_points,diff --git a/crates/daemon/src/control/runtime/settings_facts/codex_models.rs b/crates/daemon/src/control/runtime/settings_facts/codex_models.rsindex 550ba70f..b1b4921c 100644--- a/crates/daemon/src/control/runtime/settings_facts/codex_models.rs+++ b/crates/daemon/src/control/runtime/settings_facts/codex_models.rs@@ -129,15 +129,50 @@ impl LocalControlAdapter {&self,catalog: &CodexCatalogSummaryV1,candidates: &mut Vec<hiroute_application::compiler::CandidateCompilationFactV1>,+ managed_root: Option<(&hiroute_domain::OperationId, &str)>,) -> Option<(Vec<AgentFixedModelSelectionV2>, Vec<String>)> {- let mut native_candidates = self- .scanner- .codex_source_candidates(&CodexSelectionTarget::Root)- .ok()?;- if native_candidates.len() != 1 {- return None;- }- let native = native_candidates.pop()?;+ let restored_source = if let Some((original, target)) = managed_root {+ let stores = self.stores_lock().ok()?;+ let operation = stores.control().load_operation(original).ok()??;+ if operation.state != hiroute_domain::OperationState::Succeeded+ || operation.plan.spec().resource_id.as_deref()+ != Some(&self.settings_context(SettingsAgentClass::Codex))+ {+ return None;+ }+ let intent = operation.plan.external().iter().find(|i| {+ super::native_model::is_settings_codex_model(i) && i.target() == target+ })?;+ let record = self+ .artifacts+ .load_native_restore(original, intent)+ .ok()??;+ if record.len() < 3 || record[0] != 1 || record[1] > 1 {+ return None;+ }+ let restore = CodexNativeRestore::decode_protected(&record[2..]).ok()?;+ drop(stores);+ Some(+ self.scanner+ .codex_source_before_managed_change(&restore)+ .ok()??,+ )+ } else {+ None+ };+ let native = match &restored_source {+ Some((native, _)) => native.clone(),+ None => {+ let mut sources = self+ .scanner+ .codex_source_candidates(&CodexSelectionTarget::Root)+ .ok()?;+ if sources.len() != 1 {+ return None;+ }+ sources.pop()?+ }+ };let stores = self.stores_lock().ok()?;let management = stores.control()@@ -166,10 +201,13 @@ impl LocalControlAdapter {NativeIdentity::ConnectorAccount(account_ref)}DiscoveredAuthSource::EnvironmentKey | DiscoveredAuthSource::InlineToken => {- let protected = self- .scanner- .read_selected_codex_source(&CodexSelectionTarget::Root, &native)- .ok()?;+ let protected = match restored_source {+ Some((_, protected)) => protected,+ None => self+ .scanner+ .read_selected_codex_source(&CodexSelectionTarget::Root, &native)+ .ok()?,+ };let fingerprint = stores.secrets().fingerprint(protected.credential.as_ref()?)diff --git a/crates/daemon/src/control/runtime/settings_profile_fault.rs b/crates/daemon/src/control/runtime/settings_profile_fault.rsnew file mode 100644index 00000000..125b4c51--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_profile_fault.rs@@ -0,0 +1,134 @@+//! Test-only file race at the real coordinator's final activation boundary.+use super::*;+use hiroute_application::control::ApplicationMutationPort;+use hiroute_application::{+ PreparedTransactionV1, TransactionCoordinator, TransactionError, VerifiedPrincipal,+};+use hiroute_domain::{+ CompensationOutcome, EffectReconciliation, ExternalEffectIntentV1, ExternalEffectPort,+ OperationV1, OwnedEffectV1, PortError, PortErrorCode, PortResult, PriceGenerationRefV1,+};++pub(super) struct FileRace {+ pub adapter: Arc<LocalControlAdapter>,+ pub path: std::path::PathBuf,+ pub fail_after_file: bool,+}+impl ApplicationMutationPort for FileRace {+ fn preview_change(+ &self,+ r: api::PreviewRequestV1,+ ) -> Result<api::PreviewResultV1, TransactionError> {+ self.adapter.preview_change(r)+ }+ fn apply_change(+ &self,+ p: api::PrincipalKind,+ r: api::ApplyRequestV1,+ ) -> Result<OperationV1, TransactionError> {+ self.adapter.apply_change(p, r)+ }+ fn apply_local_change(&self, r: api::ApplyRequestV1) -> Result<OperationV1, TransactionError> {+ self.adapter.apply_local_change(r)+ }+ fn apply_prepared_change(+ &self,+ p: api::PrincipalKind,+ r: PreparedTransactionV1,+ ) -> Result<OperationV1, TransactionError> {+ self.adapter.apply_prepared_change(p, r)+ }+ fn apply_local_prepared_change(+ &self,+ r: PreparedTransactionV1,+ ) -> Result<OperationV1, TransactionError> {+ let a = self.adapter.as_ref();+ let coordinator = TransactionCoordinator::new(a, a, a, self, a, &a.admission);+ let accepted = coordinator.accept_prepared(+ &WorkspaceId::default(),+ &VerifiedPrincipal::for_local_control(),+ r,+ )?;+ coordinator.run_accepted(accepted)+ }+}+impl ExternalEffectPort for FileRace {+ fn install_source_price_snapshot(&self, op: &OperationV1) -> PortResult<PriceGenerationRefV1> {+ self.adapter.install_source_price_snapshot(op)+ }+ fn validate_external_admission(&self, i: &ExternalEffectIntentV1) -> PortResult<()> {+ self.adapter.validate_external_admission(i)+ }+ fn begin_publication_activation(&self, op: &OperationV1) -> PortResult<()> {+ self.adapter.begin_publication_activation(op)+ }+ fn prepare_publication_activation(+ &self,+ op: &OperationV1,+ e: &OwnedEffectV1,+ ) -> PortResult<OwnedEffectV1> {+ if self.fail_after_file {+ let restored = fs::read_to_string(&self.path).unwrap();+ assert!(!restored.contains("X-HiRoute-Token"));+ return Err(PortError::new(+ PortErrorCode::Unavailable,+ "test.profile.service_after_restore",+ ));+ }+ self.adapter.prepare_publication_activation(op, e)+ }+ fn prepare_publication_rollback(+ &self,+ op: &OperationV1,+ e: &OwnedEffectV1,+ ) -> PortResult<OwnedEffectV1> {+ self.adapter.prepare_publication_rollback(op, e)+ }+ fn finish_publication_activation(&self, op: &OperationV1) -> PortResult<()> {+ self.adapter.finish_publication_activation(op)+ }+ fn prepare_agent_artifact_activation(+ &self,+ op: &OperationV1,+ i: &ExternalEffectIntentV1,+ ) -> PortResult<()> {+ self.adapter.prepare_agent_artifact_activation(op, i)+ }+ fn current_external_fingerprint(&self, t: &str) -> PortResult<Option<CanonicalDigest>> {+ self.adapter.current_external_fingerprint(t)+ }+ fn apply_external(+ &self,+ op: &OperationV1,+ i: &ExternalEffectIntentV1,+ ) -> PortResult<OwnedEffectV1> {+ self.adapter.apply_external(op, i)+ }+ fn observe_external(+ &self,+ op: &OperationV1,+ i: &ExternalEffectIntentV1,+ ) -> PortResult<EffectReconciliation> {+ self.adapter.observe_external(op, i)+ }+ fn activate_external(&self, op: &OperationV1, e: &OwnedEffectV1) -> PortResult<OwnedEffectV1> {+ if !self.fail_after_file+ && op.plan.external().iter().any(|i| {+ i.target() == e.target+ && crate::control::runtime::native_model::is_settings_codex_model(i)+ })+ {+ let original = fs::read_to_string(&self.path).unwrap();+ fs::write(&self.path, format!("# user's concurrent edit\n{original}")).unwrap();+ return self.adapter.activate_external(op, e);+ }+ self.adapter.activate_external(op, e)+ }+ fn compensate_external(+ &self,+ op: &OperationV1,+ e: &OwnedEffectV1,+ ) -> PortResult<CompensationOutcome> {+ self.adapter.compensate_external(op, e)+ }+}diff --git a/crates/daemon/src/control/runtime/settings_profile_legacy_fixture.rs b/crates/daemon/src/control/runtime/settings_profile_legacy_fixture.rsnew file mode 100644index 00000000..736605c6--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_profile_legacy_fixture.rs@@ -0,0 +1,205 @@+//! Frozen pre-file-first revoke ordering. Uses production ports and stores to create the+//! historical service-complete, file-unstaged checkpoint; never used by current producers.+use super::*;+use hiroute_application::control::ApplicationMutationPort;+use hiroute_application::{+ PreparedTransactionV1, TransactionCoordinator, TransactionError, VerifiedPrincipal,+};+use hiroute_domain::{+ AgentAccessGrantMutationKindV1, ControlRepositoryPort, EffectReconciliation,+ ExternalEffectPort, OperationStepKind, OperationStepStatus, SecretStorePort,+ SettingsServiceCompletionV1,+};++pub(super) struct ServiceFirstRevoke(pub Arc<LocalControlAdapter>);++impl ApplicationMutationPort for ServiceFirstRevoke {+ fn preview_change(+ &self,+ r: api::PreviewRequestV1,+ ) -> Result<api::PreviewResultV1, TransactionError> {+ self.0.preview_change(r)+ }+ fn apply_change(+ &self,+ p: api::PrincipalKind,+ r: api::ApplyRequestV1,+ ) -> Result<OperationV1, TransactionError> {+ self.0.apply_change(p, r)+ }+ fn apply_local_change(&self, r: api::ApplyRequestV1) -> Result<OperationV1, TransactionError> {+ self.0.apply_local_change(r)+ }+ fn apply_prepared_change(+ &self,+ p: api::PrincipalKind,+ r: PreparedTransactionV1,+ ) -> Result<OperationV1, TransactionError> {+ self.0.apply_prepared_change(p, r)+ }+ fn apply_local_prepared_change(+ &self,+ prepared: PreparedTransactionV1,+ ) -> Result<OperationV1, TransactionError> {+ let a = self.0.as_ref();+ let coordinator = TransactionCoordinator::new(a, a, a, a, a, &a.admission);+ let accepted = coordinator.accept_prepared(+ &WorkspaceId::default(),+ &VerifiedPrincipal::for_local_control(),+ prepared,+ )?;+ let mut op = accepted.operation().clone();+ assert_eq!(op.plan.spec().command_id, "agents.settings.apply");+ assert!(op.plan.secrets().is_empty() && op.plan.runtime().is_empty());+ assert_eq!(op.plan.agent_access_grants().len(), 1);+ assert_eq!(+ op.plan.agent_access_grants()[0].kind(),+ AgentAccessGrantMutationKindV1::Revoke+ );+ assert!(op.plan.external().iter().all(|i| {+ matches!(+ i.kind(),+ OwnedEffectKind::AgentArtifact | OwnedEffectKind::Publication+ )+ }));+ for kind in OperationStepKind::ALL {+ op.transition(kind.state()).unwrap();+ op.step_mut(kind).status = OperationStepStatus::Started;+ op.step_mut(kind).attempts += 1;+ a.save_operation(&mut op)?;+ match kind {+ OperationStepKind::Prepare => {}+ OperationStepKind::ApplySecrets => {+ let mutation = op.plan.agent_access_grants()[0].clone();+ let effect = a.apply_agent_access_grant(&op.operation_id, &mutation, None)?;+ record(a, &mut op, kind, effect)?;+ }+ OperationStepKind::MaterializeSources => {+ let effect = a.apply_control(+ &op.operation_id,+ &op.workspace_id,+ op.expected_revisions.target,+ op.plan.control(),+ )?;+ record(a, &mut op, kind, effect)?;+ }+ OperationStepKind::CompilePublication | OperationStepKind::ApplyAgentArtifacts => {+ // Old revokes deferred the managed model file until after sealing service.+ let effect_kind = if kind == OperationStepKind::CompilePublication {+ OwnedEffectKind::Publication+ } else {+ OwnedEffectKind::AgentArtifact+ };+ for intent in op+ .plan+ .external()+ .iter()+ .filter(|i| {+ i.kind() == effect_kind+ && !hiroute_domain::is_settings_managed_configuration(i)+ })+ .cloned()+ .collect::<Vec<_>>()+ {+ let effect = a.apply_external(&op, &intent)?;+ record(a, &mut op, kind, effect)?;+ }+ }+ OperationStepKind::Activate => {+ a.begin_publication_activation(&op)?;+ let effect = op.step(OperationStepKind::MaterializeSources).effects[0].clone();+ let effect = a.activate_control(&effect)?;+ record(a, &mut op, OperationStepKind::MaterializeSources, effect)?;+ for intent in op+ .plan+ .external()+ .iter()+ .filter(|i| {+ i.kind() == OwnedEffectKind::AgentArtifact+ && !hiroute_domain::is_settings_managed_configuration(i)+ })+ .cloned()+ .collect::<Vec<_>>()+ {+ a.prepare_agent_artifact_activation(&op, &intent)?;+ let EffectReconciliation::Staged(effect) =+ a.observe_external(&op, &intent)?+ else {+ panic!("legacy fixture artifact must be staged");+ };+ let effect = a.activate_external(&op, &effect)?;+ record(a, &mut op, OperationStepKind::ApplyAgentArtifacts, effect)?;+ }+ let staged = op.step(OperationStepKind::CompilePublication).effects[0].clone();+ let checkpoint = a.prepare_publication_activation(&op, &staged)?;+ record(+ a,+ &mut op,+ OperationStepKind::CompilePublication,+ checkpoint.clone(),+ )?;+ let published = a.activate_external(&op, &checkpoint)?;+ record(+ a,+ &mut op,+ OperationStepKind::CompilePublication,+ published.clone(),+ )?;+ let grant = op.step(OperationStepKind::ApplySecrets).effects[0].clone();+ let revoked = a.activate_agent_access_grant(&grant)?;+ record(a, &mut op, OperationStepKind::ApplySecrets, revoked)?;+ let revision = published.compensation["publication_revision"]+ .as_u64()+ .unwrap();+ let digest = published.after_fingerprint.unwrap();+ let receipt = SettingsServiceCompletionV1 {+ schema: hiroute_domain::SETTINGS_SERVICE_COMPLETION_SCHEMA.into(),+ publication_revision: revision,+ publication_digest: digest.clone(),+ // Exact frozen v2 receipt algorithm, including the immutable admitted plan.+ completed_effects_digest: CanonicalDigest::of(&(+ "hiroute.settings-service-proof/v2",+ op.operation_id.as_str(),+ &op.accepted_digest,+ revision,+ &digest,+ op.stable_input_digest().unwrap(),+ ))+ .unwrap(),+ };+ op.step_mut(kind).terminal_result =+ Some(serde_json::to_string(&receipt).unwrap());+ op.safe_error_code = Some("SETTINGS_TAIL_PENDING".into());+ a.save_operation(&mut op)?;+ a.save_operation_tail(&mut op)?;+ assert!(hiroute_application::settings_service_completion_is_current(+ &op, revision, &digest+ ));+ return Ok(op);+ }+ }+ op.step_mut(kind).status = OperationStepStatus::Applied;+ op.step_mut(kind).terminal_result = Some("applied".into());+ a.save_operation(&mut op)?;+ }+ unreachable!()+ }+}++fn record(+ a: &LocalControlAdapter,+ op: &mut OperationV1,+ step: OperationStepKind,+ effect: hiroute_domain::OwnedEffectV1,+) -> hiroute_domain::PortResult<()> {+ let effects = &mut op.step_mut(step).effects;+ if let Some(old) = effects+ .iter_mut()+ .find(|old| old.effect_id == effect.effect_id)+ {+ *old = effect;+ } else {+ effects.push(effect);+ }+ a.save_operation(op)+}diff --git a/crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs b/crates/daemon/src/control/runtime/settings_profile_legacy_tests.rsnew file mode 100644index 00000000..16361a7b--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_profile_legacy_tests.rs@@ -0,0 +1,227 @@+//! Recovery through current production wire entry from a frozen service-first revoke.+use super::*;+use hiroute_domain::{ControlRepositoryPort, ExternalEffectPort, SecretStorePort};++#[path = "settings_profile_legacy_fixture.rs"]+mod fixture;++#[test]+fn legacy_service_first_revoke_survives_restart_and_same_operation_retry() {+ if crate::test_support::isolated_agent_home(+ "control::runtime::native_model::tests::settings_entry_tests::settings_profile_tests::legacy::legacy_service_first_revoke_survives_restart_and_same_operation_retry",+ ) {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ ensure_target_cache(&runtime.adapter);+ runtime.adapter.reconcile_startup_and_open().unwrap();+ runtime+ .adapter+ .finish_startup_publication_recovery()+ .unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ let access = runtime.adapter.codex_access_view().unwrap();+ let context = access.profile_context_id;+ let other_context = access.root_context_id;+ let root = runtime.adapter.scanner.codex_user_config_target();+ let original = "# ordinary entry remains native\nuser_option = true\n";+ fs::write(&root, original).unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o600)).unwrap();+ let plan = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .verify()+ .unwrap()+ .published_agent_plans()+ .unwrap()+ .into_iter()+ .find(|p| {+ p.active+ && p.supported_ingress+ .contains(&AgentIngressProtocolV1::Responses)+ })+ .unwrap();+ let spec = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"configure","settings":{+ "mode":"codex_default","native_model_mode":"hiroute_only","fixed_models":[],"allowed_plan_ids":[plan.agent_plan_id],"default_selection":{"kind":"plan","plan_id":plan.agent_plan_id}}}});+ let configured = apply(&service, &runtime, spec, "legacy-create-profile");+ let created_id: OperationId =+ serde_json::from_value(configured["operation_id"].clone()).unwrap();+ let profile = runtime.adapter.scanner.codex_profile_config_target();+ let before = fs::read_to_string(&profile).unwrap();+ let restore = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"restore","restore_point_ref":codex_model_restore_point_ref(&created_id)}});+ let mut ports = runtime.application_ports();+ ports.mutation = Some(Arc::new(fixture::ServiceFirstRevoke(+ runtime.adapter.clone(),+ )));+ let legacy = LocalControlDaemon::new(ApplicationService::new(ports));+ let preview = legacy.dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ));+ assert!(preview.error.is_none(), "{preview:?}");+ let preview = preview.data.unwrap();+ let result = legacy.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"legacy-revoke-profile"}), None));+ assert!(result.error.is_none(), "{result:?}");+ let pending = result.data.unwrap();+ assert_eq!(pending["state"], "activating");+ let pending_id: OperationId = serde_json::from_value(pending["operation_id"].clone()).unwrap();+ let op = runtime+ .adapter+ .load_operation(&pending_id)+ .unwrap()+ .unwrap();+ let file = op+ .plan+ .external()+ .iter()+ .find(|i| hiroute_domain::is_settings_managed_configuration(i))+ .unwrap();+ assert!(matches!(+ runtime.adapter.observe_external(&op, file).unwrap(),+ hiroute_domain::EffectReconciliation::Missing+ ));+ assert!(+ runtime+ .adapter+ .stores_lock()+ .unwrap()+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{context}")+ )+ .unwrap()+ .is_none()+ );+ assert_eq!(fs::read_to_string(&profile).unwrap(), before);+ let conflicted = before.replace("name = \"HiRoute\"", "name = \"My Gateway\"");+ assert_ne!(before, conflicted);+ fs::write(&profile, &conflicted).unwrap();+ drop(legacy);+ drop(service);+ drop(runtime);+ // New process composition: rebuild committed Gateway authority before journal recovery.+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ runtime.adapter.restore_active_publication().unwrap();+ runtime.adapter.reconcile_startup_and_open().unwrap();+ runtime+ .adapter+ .finish_startup_publication_recovery()+ .unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ assert_eq!(fs::read_to_string(&profile).unwrap(), conflicted);+ let access = runtime.adapter.codex_access_view().unwrap();+ assert!(access.slot_occupied && access.access_revoked);+ assert_eq!(+ access.pending_operation.as_deref(),+ Some(pending_id.as_str())+ );+ assert!(access.conflict_fields.iter().any(|f| f.contains("name")));+ assert!(runtime.adapter.guard_codex_pending_change(None).is_err());+ assert!(+ runtime+ .adapter+ .guard_codex_pending_change(Some(&pending_id))+ .is_ok()+ );+ let op = runtime+ .adapter+ .load_operation(&pending_id)+ .unwrap()+ .unwrap();+ let publication = op+ .plan+ .external()+ .iter()+ .find(|i| i.kind() == OwnedEffectKind::Publication)+ .unwrap();+ assert!(+ runtime+ .adapter+ .validate_external_admission(publication)+ .is_err()+ );+ // Target-local diagnostics must preserve all Agents and the same recovery entry.+ for (bytes, expected) in [+ (Some(vec![0xff, 0xfe]), "configuration_encoding"),+ (None, "configuration_unreadable"),+ ] {+ fs::remove_file(&profile).unwrap();+ if let Some(bytes) = bytes {+ fs::write(&profile, bytes).unwrap();+ } else {+ std::os::unix::fs::symlink(&root, &profile).unwrap();+ }+ let scan = service.dispatch_wire(request("ScanAgents", json!({}), None));+ assert!(scan.error.is_none(), "{scan:?}");+ let scan = scan.data.unwrap();+ let access = &scan["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["agent_id"] == "agent_codex_default")+ .unwrap()["codex_access"];+ assert_eq!(access["pending_operation"], pending["operation_id"]);+ assert_eq!(access["access_revoked"], true);+ assert_eq!(access["conflict_fields"], json!([expected]));+ }+ assert_eq!(fs::read_to_string(&root).unwrap(), original);+ fs::remove_file(&profile).unwrap();+ fs::write(&profile, &conflicted).unwrap();+ fs::set_permissions(&profile, fs::Permissions::from_mode(0o600)).unwrap();+ let retry = json!({"schema":"hiroute.agent-settings-retry/v1","context_id":context,"operation_id":pending["operation_id"]});+ let mut wrong = retry.clone();+ wrong["context_id"] = json!(other_context);+ assert!(+ service+ .dispatch_wire(request("ApplyAgentConnectionChange", wrong, None))+ .error+ .is_some()+ );+ let still_pending =+ service.dispatch_wire(request("ApplyAgentConnectionChange", retry.clone(), None));+ assert!(still_pending.error.is_none(), "{still_pending:?}");+ assert_eq!(still_pending.data.unwrap()["state"], "activating");+ assert_eq!(fs::read_to_string(&profile).unwrap(), conflicted);+ // A collaboration-only writer also cannot invalidate the sealed publication/control facts.+ let collaboration =+ LocalControlDaemon::new(ApplicationService::new(+ runtime.application_ports().with_agent_connection(Arc::new(+ FixtureFacts::collaboration(runtime.adapter.clone()),+ )),+ ));+ let skill_spec = json!({"schema_version":{"major":2,"minor":0},"context_id":other_context,+ "collaboration":{"intent":"configure","settings":{"trigger_mode":"delegate_by_default"}}});+ let preview = collaboration.dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":skill_spec}),+ None,+ ));+ assert!(preview.error.is_none(), "{preview:?}");+ let preview = preview.data.unwrap();+ assert_eq!(preview["applicable"], true, "{preview}");+ let denied = collaboration.dispatch_wire(request("ApplyAgentConnectionChange", json!({"spec":skill_spec,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"legacy-pending-skill"}), None));+ assert!(denied.error.is_some(), "{denied:?}");+ // User-owned semantic cleanup is accepted without rewriting comments or unrelated fields.+ let cleaned = "# user's concurrent edit\nanother_user_edit = 'retained'\n";+ fs::write(&profile, cleaned).unwrap();+ let invalid_root = "[invalid root TOML";+ fs::write(&root, invalid_root).unwrap();+ fs::remove_file(root.parent().unwrap().join("models_cache.json")).unwrap();+ let done = service.dispatch_wire(request("ApplyAgentConnectionChange", retry, None));+ assert!(done.error.is_none(), "{done:?}");+ let done = done.data.unwrap();+ assert_eq!(done["operation_id"], pending["operation_id"]);+ assert_eq!(done["state"], "succeeded", "{done}");+ assert_eq!(fs::read_to_string(&profile).unwrap(), cleaned);+ assert_eq!(fs::read_to_string(&root).unwrap(), invalid_root);+ assert!(runtime.adapter.guard_codex_pending_change(None).is_ok());+ assert!(!runtime.adapter.codex_access_view().unwrap().slot_occupied);+}diff --git a/crates/daemon/src/control/runtime/settings_profile_tests.rs b/crates/daemon/src/control/runtime/settings_profile_tests.rsnew file mode 100644index 00000000..04b027af--- /dev/null+++ b/crates/daemon/src/control/runtime/settings_profile_tests.rs@@ -0,0 +1,590 @@+//! Native profile lifecycle through the production wire entry and protected stores.+use super::*;++#[test]+fn profile_lifecycle_inheritance_slot_and_safe_restore() {+ if crate::test_support::isolated_agent_home(+ "control::runtime::native_model::tests::settings_entry_tests::settings_profile_tests::profile_lifecycle_inheritance_slot_and_safe_restore",+ ) {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ ensure_target_cache(&runtime.adapter);+ let root = runtime.adapter.scanner.codex_user_config_target();+ fs::create_dir_all(root.parent().unwrap()).unwrap();+ fs::set_permissions(root.parent().unwrap(), fs::Permissions::from_mode(0o700)).unwrap();+ let original = "# ordinary entry remains native\nuser_option = true\n";+ fs::write(&root, original).unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o600)).unwrap();+ runtime.adapter.reconcile_startup_and_open().unwrap();+ // Complete the same Gateway handoff as the production startup entry.+ runtime+ .adapter+ .finish_startup_publication_recovery()+ .unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ let scan = service+ .dispatch_wire(request("ScanAgents", json!({}), None))+ .data+ .unwrap();+ let codex = scan["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["agent_id"] == "agent_codex_default")+ .unwrap();+ let access = &codex["codex_access"];+ assert_eq!(access["selected_mode"], "profile");+ assert_eq!(codex["context_id"], access["profile_context_id"]);+ assert_ne!(access["root_context_id"], access["profile_context_id"]);+ let context = access["profile_context_id"].clone();+ let profile = runtime.adapter.scanner.codex_profile_config_target();+ let publication = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .verify()+ .unwrap();+ let plans = publication.published_agent_plans().unwrap();+ let plan = plans+ .iter()+ .find(|p| {+ p.active+ && p.supported_ingress+ .contains(&AgentIngressProtocolV1::Responses)+ })+ .unwrap();+ let spec = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"configure","settings":{+ "mode":"codex_default","native_model_mode":"hiroute_only","fixed_models":[],"allowed_plan_ids":[plan.agent_plan_id],"default_selection":{"kind":"plan","plan_id":plan.agent_plan_id}}}});+ // A filename never establishes ownership, even for an empty preexisting file.+ fs::write(&profile, "").unwrap();+ fs::set_permissions(&profile, fs::Permissions::from_mode(0o600)).unwrap();+ assert!(+ service+ .dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":spec}),+ None+ ))+ .error+ .is_some()+ );+ fs::remove_file(&profile).unwrap();+ let preview = service.dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":spec}),+ None,+ ));+ assert!(preview.error.is_none(), "{preview:?}");+ let preview = preview.data.unwrap();+ assert_eq!(preview["applicable"], true, "{preview}");+ // Root changes invalidate preview even though the target profile is still absent.+ fs::write(&root, format!("{original}[model_providers.hiroute]\nhttp_headers = {{ Authorization = 'user-owned' }}\n")).unwrap();+ let stale = service.dispatch_wire(request("ApplyAgentConnectionChange", json!({"spec":spec,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"stale-profile"}), None));+ assert!(stale.error.is_some(), "{stale:?}");+ assert!(!profile.exists());+ fs::write(&root, original).unwrap();+ apply(&service, &runtime, spec.clone(), "create-profile");+ assert_eq!(fs::read_to_string(&root).unwrap(), original);+ let configured = fs::read_to_string(&profile).unwrap();+ assert!(configured.contains("requires_openai_auth = false"));+ // Root and profile have distinct context ids but share the same home slot.+ let mut root_spec = spec.clone();+ root_spec["context_id"] = access["root_context_id"].clone();+ assert!(+ service+ .dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":root_spec}),+ None+ ))+ .error+ .is_some()+ );+ fs::write(&profile, format!("user_edit = true\n{configured}")).unwrap();+ // Configure/edit tails must pin the publication as well as revoke tails.+ let before_edit = fs::read(&profile).unwrap();+ let mut edit_ports = runtime.application_ports();+ edit_ports.mutation = Some(Arc::new(fault::FileRace {+ adapter: runtime.adapter.clone(),+ path: profile.clone(),+ fail_after_file: false,+ }));+ let editing = LocalControlDaemon::new(ApplicationService::new(edit_ports));+ let edit_preview = editing+ .dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":spec}),+ None,+ ))+ .data+ .unwrap();+ let parked_edit = editing.dispatch_wire(request("ApplyAgentConnectionChange", json!({"spec":spec,"accept_digest":edit_preview["accept_digest"],"dependency_digest":edit_preview["dependency_digest"],"expected_revisions":edit_preview["expected_revisions"],"idempotency_key":"edit-profile"}), None));+ assert!(parked_edit.error.is_none(), "{parked_edit:?}");+ let parked_edit = parked_edit.data.unwrap();+ assert_eq!(parked_edit["state"], "activating");+ assert!(runtime.adapter.guard_codex_pending_change(None).is_err());+ fs::write(&profile, before_edit).unwrap();+ let edited = service.dispatch_wire(request("ApplyAgentConnectionChange", json!({"schema":"hiroute.agent-settings-retry/v1","context_id":context,"operation_id":parked_edit["operation_id"]}), None));+ assert!(edited.error.is_none(), "{edited:?}");+ let edited = edited.data.unwrap();+ assert_eq!(edited["state"], "succeeded");+ assert!(runtime.adapter.guard_codex_pending_change(None).is_ok());+ assert!(+ fs::read_to_string(&profile)+ .unwrap()+ .contains("user_edit = true")+ );+ let operation: OperationId = serde_json::from_value(edited["operation_id"].clone()).unwrap();+ let restore = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"restore","restore_point_ref":codex_model_restore_point_ref(&operation)}});+ // A profile revoke needs neither the original metadata directory nor a valid root file.+ let unavailable_root = "[invalid root TOML";+ fs::write(&root, unavailable_root).unwrap();+ fs::remove_file(root.parent().unwrap().join("models_cache.json")).unwrap();+ let mut ports = runtime.application_ports();+ ports.mutation = Some(Arc::new(fault::FileRace {+ adapter: runtime.adapter.clone(),+ path: profile.clone(),+ fail_after_file: false,+ }));+ let racing = LocalControlDaemon::new(ApplicationService::new(ports));+ let preview = racing+ .dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ))+ .data+ .unwrap();+ assert_eq!(preview["applicable"], true, "{preview}");+ let pending = racing.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"revoke-profile"}), None));+ assert!(pending.error.is_none(), "{pending:?}");+ let failed = pending.data.unwrap();+ assert_eq!(failed["state"], "rolled_back", "{failed}");+ let access = runtime.adapter.codex_access_view().unwrap();+ assert!(access.slot_occupied && !access.access_revoked);+ assert!(access.pending_operation.is_none());+ assert!(runtime.adapter.guard_codex_pending_change(None).is_ok());+ assert!(+ fs::read_to_string(&profile)+ .unwrap()+ .starts_with("# user's concurrent edit")+ );+ // A concurrent edit is preserved while the unused staged restoration is discarded.+ runtime.adapter.reconcile_startup_and_open().unwrap();+ let status = service+ .dispatch_wire(request("GetClientServiceStatus", json!({}), None))+ .data+ .unwrap();+ assert_eq!(status["mutation_available"], true, "{status}");+ fs::write(&root, original).unwrap();+ ensure_target_cache(&runtime.adapter);+ let preserved = fs::read(&profile).unwrap();+ fs::write(&profile, [0xff, 0xfe]).unwrap();+ let damaged = service.dispatch_wire(request("ScanAgents", json!({}), None));+ assert!(damaged.error.is_none(), "{damaged:?}");+ assert_eq!(+ runtime.adapter.codex_access_view().unwrap().conflict_fields,+ ["configuration_encoding"]+ );+ fs::remove_file(&profile).unwrap();+ std::os::unix::fs::symlink(&root, &profile).unwrap();+ let unsafe_target = service.dispatch_wire(request("ScanAgents", json!({}), None));+ assert!(unsafe_target.error.is_none(), "{unsafe_target:?}");+ assert_eq!(+ runtime.adapter.codex_access_view().unwrap().conflict_fields,+ ["configuration_unreadable"]+ );+ fs::remove_file(&profile).unwrap();+ fs::write(&profile, &preserved).unwrap();+ fs::set_permissions(&profile, fs::Permissions::from_mode(0o600)).unwrap();+ // An unrelated real collaboration save remains available after the failed disable.+ let collaboration =+ LocalControlDaemon::new(ApplicationService::new(+ runtime.application_ports().with_agent_connection(Arc::new(+ FixtureFacts::collaboration(runtime.adapter.clone()),+ )),+ ));+ let skill_spec = json!({"schema_version":{"major":2,"minor":0},"context_id":root_spec["context_id"],+ "collaboration":{"intent":"configure","settings":{"trigger_mode":"delegate_by_default"}}});+ apply(+ &collaboration,+ &runtime,+ skill_spec,+ "skill-after-failed-disable",+ );+ // A fresh preview/operation completes restoration without metadata or a valid root.+ fs::write(&root, unavailable_root).unwrap();+ fs::remove_file(root.parent().unwrap().join("models_cache.json")).unwrap();+ apply(&service, &runtime, restore, "retry-disable-after-race");+ assert!(!runtime.adapter.codex_access_view().unwrap().slot_occupied);+ let remaining = fs::read_to_string(&profile).unwrap();+ assert!(+ remaining.contains("# user's concurrent edit") && remaining.contains("user_edit = true")+ );+ assert!(!remaining.contains("X-HiRoute-Token") && !remaining.contains("model_provider ="));+ assert_eq!(fs::read_to_string(&root).unwrap(), unavailable_root);+ fs::write(&root, original).unwrap();+ ensure_target_cache(&runtime.adapter);+ apply(&service, &runtime, root_spec, "switch-after-revoke");+}++#[path = "settings_profile_fault.rs"]+mod fault;++#[path = "settings_profile_legacy_tests.rs"]+mod legacy;++#[test]+fn codex_discovery_keeps_desktop_in_default_profile_mode() {+ if crate::test_support::isolated_agent_home(+ "control::runtime::native_model::tests::settings_entry_tests::settings_profile_tests::codex_discovery_keeps_desktop_in_default_profile_mode",+ ) {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ ensure_target_cache(&runtime.adapter);+ runtime.adapter.reconcile_startup_and_open().unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ let scan = service+ .dispatch_wire(request("ScanAgents", json!({}), None))+ .data+ .unwrap();+ let codex = scan["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["agent_id"] == "agent_codex_default")+ .unwrap();+ assert_eq!(codex["codex_access"]["selected_mode"], "profile");+ let surfaces = codex["available_surfaces"].as_array().unwrap();+ assert!(surfaces.contains(&json!("codex_cli")));+ assert!(surfaces.contains(&json!("codex_desktop")));+}++#[test]+fn preexisting_profile_conflict_preserves_connection_and_other_writes() {+ use hiroute_domain::SecretStorePort;+ if crate::test_support::isolated_agent_home(+ "control::runtime::native_model::tests::settings_entry_tests::settings_profile_tests::preexisting_profile_conflict_preserves_connection_and_other_writes",+ ) {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ ensure_target_cache(&runtime.adapter);+ runtime.adapter.reconcile_startup_and_open().unwrap();+ // The fixture composes a real suspended target; complete the production startup handoff.+ runtime+ .adapter+ .publication_target()+ .unwrap()+ .unwrap()+ .resume_requests()+ .unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ let scan = service+ .dispatch_wire(request("ScanAgents", json!({}), None))+ .data+ .unwrap();+ let codex = scan["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["agent_id"] == "agent_codex_default")+ .unwrap();+ let context = codex["codex_access"]["profile_context_id"].clone();+ let plans = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .verify()+ .unwrap()+ .published_agent_plans()+ .unwrap();+ let plan = plans+ .iter()+ .find(|p| {+ p.active+ && p.supported_ingress+ .contains(&AgentIngressProtocolV1::Responses)+ })+ .unwrap();+ let spec = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"configure","settings":{+ "mode":"codex_default","native_model_mode":"hiroute_only","fixed_models":[],"allowed_plan_ids":[plan.agent_plan_id],"default_selection":{"kind":"plan","plan_id":plan.agent_plan_id}}}});+ apply(+ &service,+ &runtime,+ spec,+ "create-preexisting-conflict-profile",+ );+ let status = service+ .dispatch_wire(request(+ "GetAgentConnectionStatus",+ json!({"schema_version":{"major":2,"minor":0},"context_id":context}),+ None,+ ))+ .data+ .unwrap();+ let profile = runtime.adapter.scanner.codex_profile_config_target();+ let configured = fs::read_to_string(&profile).unwrap();+ let conflicted = configured.replace("name = \"HiRoute\"", "name = \"My Gateway\"");+ assert_ne!(conflicted, configured);+ fs::write(&profile, &conflicted).unwrap();+ let publication_before = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap();+ let grant_before = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{}", context.as_str().unwrap()),+ )+ .unwrap();+ let restore = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"restore","restore_point_ref":status["restore_point_ref"]}});+ let preview = service+ .dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ))+ .data+ .unwrap();+ assert_eq!(preview["applicable"], true);+ let response = service.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"revoke-preexisting-conflict"}), None));+ assert!(response.error.is_none(), "{response:?}");+ let failed = response.data.unwrap();+ assert_eq!(failed["state"], "rolled_back", "{failed}");+ let access = runtime.adapter.codex_access_view().unwrap();+ assert!(!access.access_revoked && access.slot_occupied);+ assert!(access.pending_operation.is_none());+ assert!(+ access+ .conflict_fields+ .iter()+ .any(|field| field.contains("name")),+ "{:?}",+ access.conflict_fields+ );+ assert!(+ runtime+ .adapter+ .stores_lock()+ .unwrap()+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{}", context.as_str().unwrap())+ )+ .unwrap()+ .is_some()+ );+ assert_eq!(fs::read_to_string(&profile).unwrap(), conflicted);+ assert_eq!(+ runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .digest,+ publication_before.digest+ );+ assert_eq!(+ runtime+ .adapter+ .stores_lock()+ .unwrap()+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{}", context.as_str().unwrap())+ )+ .unwrap(),+ grant_before+ );+ runtime.adapter.reconcile_startup_and_open().unwrap();+ let available = service+ .dispatch_wire(request("GetClientServiceStatus", json!({}), None))+ .data+ .unwrap();+ assert_eq!(available["mutation_available"], true, "{available}");+ assert!(runtime.adapter.guard_codex_pending_change(None).is_ok());+ fs::write(+ &profile,+ format!("# kept user comments\nuser_option = 'retained'\n{configured}"),+ )+ .unwrap();+ let repaired = fs::read(&profile).unwrap();+ let mut fault_ports = runtime.application_ports();+ fault_ports.mutation = Some(Arc::new(fault::FileRace {+ adapter: runtime.adapter.clone(),+ path: profile.clone(),+ fail_after_file: true,+ }));+ let fault_service = LocalControlDaemon::new(ApplicationService::new(fault_ports));+ let preview = fault_service+ .dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ))+ .data+ .unwrap();+ let failed_service = fault_service.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"service-failure-after-restoring-file"}), None));+ assert!(failed_service.error.is_none(), "{failed_service:?}");+ assert_eq!(failed_service.data.unwrap()["state"], "rolled_back");+ assert_eq!(fs::read(&profile).unwrap(), repaired);+ assert!(!runtime.adapter.codex_access_view().unwrap().access_revoked);+ assert_eq!(+ service+ .dispatch_wire(request("GetClientServiceStatus", json!({}), None))+ .data+ .unwrap()["mutation_available"],+ true+ );+ apply(&service, &runtime, restore, "retry-preexisting-conflict");+ let cleaned = fs::read_to_string(&profile).unwrap();+ assert!(+ cleaned.contains("# kept user comments") && cleaned.contains("user_option = 'retained'")+ );+ assert!(!cleaned.contains("X-HiRoute-Token"));+ assert!(!runtime.adapter.codex_access_view().unwrap().slot_occupied);+}++#[test]+fn profile_delete_race_rolls_back_and_releases_writer() {+ if crate::test_support::isolated_agent_home(+ "control::runtime::native_model::tests::settings_entry_tests::settings_profile_tests::profile_delete_race_rolls_back_and_releases_writer",+ ) {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (runtime, _) = open_with_codex_fixture_surfaces(dir.path());+ ensure_target_cache(&runtime.adapter);+ let root = runtime.adapter.scanner.codex_user_config_target();+ fs::create_dir_all(root.parent().unwrap()).unwrap();+ fs::set_permissions(root.parent().unwrap(), fs::Permissions::from_mode(0o700)).unwrap();+ let original = "# ordinary entry remains native\nuser_option = true\n";+ fs::write(&root, original).unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o600)).unwrap();+ runtime.adapter.reconcile_startup_and_open().unwrap();+ // Complete the same Gateway handoff as the production startup entry.+ runtime+ .adapter+ .finish_startup_publication_recovery()+ .unwrap();+ let service = LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()));+ let scan = service+ .dispatch_wire(request("ScanAgents", json!({}), None))+ .data+ .unwrap();+ let codex = scan["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["agent_id"] == "agent_codex_default")+ .unwrap();+ let access = &codex["codex_access"];+ assert_eq!(access["selected_mode"], "profile");+ assert_eq!(codex["context_id"], access["profile_context_id"]);+ assert_ne!(access["root_context_id"], access["profile_context_id"]);+ let context = access["profile_context_id"].clone();+ let profile = runtime.adapter.scanner.codex_profile_config_target();+ let publication = runtime+ .adapter+ .stores_lock()+ .unwrap()+ .control()+ .active_publication(&WorkspaceId::default())+ .unwrap()+ .unwrap()+ .verify()+ .unwrap();+ let plans = publication.published_agent_plans().unwrap();+ let plan = plans+ .iter()+ .find(|p| {+ p.active+ && p.supported_ingress+ .contains(&AgentIngressProtocolV1::Responses)+ })+ .unwrap();+ let spec = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"configure","settings":{+ "mode":"codex_default","native_model_mode":"hiroute_only","fixed_models":[],"allowed_plan_ids":[plan.agent_plan_id],"default_selection":{"kind":"plan","plan_id":plan.agent_plan_id}}}});++ let configured = apply(&service, &runtime, spec.clone(), "create-delete-race");+ let grant = || {+ runtime+ .adapter+ .stores_lock()+ .unwrap()+ .secrets()+ .inspect_agent_access_grant(+ WorkspaceId::DEFAULT,+ &format!("agent-connection/{}", context.as_str().unwrap()),+ )+ .unwrap()+ };+ let grant_before = grant();+ assert!(grant_before.is_some());+ let operation: OperationId =+ serde_json::from_value(configured["operation_id"].clone()).unwrap();+ let restore = json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"restore","restore_point_ref":codex_model_restore_point_ref(&operation)}});+ let before = fs::read_to_string(&profile).unwrap();+ let mut ports = runtime.application_ports();+ ports.mutation = Some(Arc::new(fault::FileRace {+ adapter: runtime.adapter.clone(),+ path: profile.clone(),+ fail_after_file: false,+ }));+ let racing = LocalControlDaemon::new(ApplicationService::new(ports));+ let preview = racing+ .dispatch_wire(request(+ "PreviewAgentConnectionRestore",+ json!({"spec":restore}),+ None,+ ))+ .data+ .unwrap();+ assert_eq!(preview["applicable"], true);+ let failed = racing.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":restore,"accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],"expected_revisions":preview["expected_revisions"],"idempotency_key":"delete-race"}), None));+ assert!(failed.error.is_none(), "{failed:?}");+ assert_eq!(failed.data.unwrap()["state"], "rolled_back");+ assert_eq!(grant(), grant_before);+ assert_eq!(+ fs::read_to_string(&profile).unwrap(),+ format!("# user's concurrent edit\n{before}")+ );+ let access = runtime.adapter.codex_access_view().unwrap();+ assert!(access.slot_occupied && !access.access_revoked);+ assert!(access.pending_operation.is_none());+ let status = service+ .dispatch_wire(request("GetClientServiceStatus", json!({}), None))+ .data+ .unwrap();+ assert_eq!(status["mutation_available"], true);+ apply(&service, &runtime, restore, "retry-delete-race");+ assert!(!runtime.adapter.codex_access_view().unwrap().slot_occupied);+ assert!(!profile.exists());+}diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rsindex 7d3fdc9c..9149463c 100644--- a/crates/daemon/src/control/runtime/settings_status.rs+++ b/crates/daemon/src/control/runtime/settings_status.rs@@ -38,9 +38,8 @@ impl LocalControlAdapter {|| !request.allow_model_call|| !request.valid_target()|| self- .settings_context_for_agent(&request.agent_id)- .as_deref()- != Some(target.context_id.as_str())+ .settings_agent_for_context(&target.context_id)+ .is_none_or(|class| class.agent_id() != request.agent_id){return Err(ControlReadError::Denied);}@@ -69,7 +68,17 @@ impl LocalControlAdapter {request: &AgentSettingsStatusRequestV2,) -> Result<AgentModelSettingsStatusV2, ControlReadError> {let (mut status, _, _) = self.evaluate_model_settings(request)?;- status.collaboration = Some(self.collaboration_settings_status(request)?);+ let collaboration_request = if self.settings_agent_for_context(&request.context_id)+ == Some(SettingsAgentClass::CodexProfile)+ {+ AgentSettingsStatusRequestV2 {+ schema_version: request.schema_version,+ context_id: self.settings_context(SettingsAgentClass::Codex),+ }+ } else {+ request.clone()+ };+ status.collaboration = Some(self.collaboration_settings_status(&collaboration_request)?);Ok(status)}@@ -146,9 +155,10 @@ impl LocalControlAdapter {};if let Some(pending) = stores.control()- .writer_claim_operation()+ .recoverable_operations().map_err(super::map_port)?- && belongs(&pending)+ .into_iter()+ .find(|op| belongs(op)){status.state = if pending.state == OperationState::NeedsAttention {State::NeedsAttention@@ -206,12 +216,18 @@ impl LocalControlAdapter {.claude_native_routing_conflict().map_err(|_| ControlReadError::Corrupt)?} else {- hiroute_integrations::codex_native_configuration_is_applied(- &self.artifacts,- &operation.operation_id,- intent,- )- .map_err(super::map_port)?+ (class != SettingsAgentClass::CodexProfile+ || hiroute_integrations::codex_profile_dependency_digest(+ &self.scanner.codex_user_config_target(),+ true,+ )+ .is_ok())+ && hiroute_integrations::codex_native_configuration_is_applied(+ &self.artifacts,+ &operation.operation_id,+ intent,+ )+ .map_err(super::map_port)?};let [mutation] = operation.plan.agent_access_grants() else {return Err(ControlReadError::Corrupt);@@ -273,6 +289,10 @@ impl LocalControlAdapter {hiroute_domain::AgentModelSelectionV2::CodexDefault { .. },SettingsAgentClass::Codex,) => self.scanner.available_model_surfaces(class.agent_id()),+ (+ hiroute_domain::AgentModelSelectionV2::CodexDefault { .. },+ SettingsAgentClass::CodexProfile,+ ) => [hiroute_domain::AgentModelSurfaceV2::CodexCli].into(),(hiroute_domain::AgentModelSelectionV2::ClaudeLauncher {surfaces, ..@@ -405,7 +425,8 @@ fn model_intent(.external.iter().find(|intent| match class {- super::settings_facts::SettingsAgentClass::Codex => {+ super::settings_facts::SettingsAgentClass::Codex+ | super::settings_facts::SettingsAgentClass::CodexProfile => {super::native_model::is_settings_codex_model(intent)}super::settings_facts::SettingsAgentClass::Claude => {@@ -420,7 +441,8 @@ fn model_action(intent: &hiroute_domain::ExternalEffectIntentV1,) -> hiroute_domain::PortResult<ModelAction> {match class {- super::settings_facts::SettingsAgentClass::Codex => {+ super::settings_facts::SettingsAgentClass::Codex+ | super::settings_facts::SettingsAgentClass::CodexProfile => {match settings_codex_model_file_for_operation(operation, intent)?.change {CodexModelFileAction::Configure { .. } => Ok(ModelAction::Configure),CodexModelFileAction::Restore { .. } => Ok(ModelAction::Restore),diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rsindex 26d61d23..cefcee0f 100644--- a/crates/daemon/tests/subscription_management_product.rs+++ b/crates/daemon/tests/subscription_management_product.rs@@ -35,7 +35,7 @@ import reimport sysimport urllib.parse-VERSION = "8.0.4-hiroute.1"+VERSION = "8.0.4-hiroute.2"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 e8ea6b3d..f56ace69 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.1'+VERSION = '8.0.4-hiroute.2'controls = Path(__file__).resolve().parentmodel_override = controls / 'model-id'MODEL = (model_override.read_text().strip()diff --git a/crates/daemon/tests/support/delegation_product.py b/crates/daemon/tests/support/delegation_product.pyindex fc939989..dc45cea6 100644--- a/crates/daemon/tests/support/delegation_product.py+++ b/crates/daemon/tests/support/delegation_product.py@@ -271,7 +271,7 @@ def run(repository, expected_sha):assert checked['data']['trusted_cli_execution'] == 'proven', checkedstage = 'confirmed-collaboration-with-local-worker-plan-policy'scan = product.preview('agents scan')- context = next(agent['context_id'] for agent in scan['agents'] if agent['agent_id'] == 'agent_codex_default')+ context = next(agent['codex_access']['root_context_id'] for agent in scan['agents'] if agent['agent_id'] == 'agent_codex_default')settings = {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context,'collaboration': {'intent': 'configure', 'settings': {'trigger_mode': 'explicit'}}}diff --git a/crates/daemon/tests/support/publication_process.py b/crates/daemon/tests/support/publication_process.pyindex 82500851..138b1abf 100644--- a/crates/daemon/tests/support/publication_process.py+++ b/crates/daemon/tests/support/publication_process.py@@ -41,8 +41,12 @@ def configure_model_settings_v2(product, allowed_plan_ids, key, default_plan_id=context = getattr(product, 'agent_context_id', None)if context is None:scan = product.preview('agents scan')- context = next(agent['context_id'] for agent in scan['agents']- if agent['agent_id'] == agent_id)+ agent = next(agent for agent in scan['agents'] if agent['agent_id'] == agent_id)+ # Existing product scenarios explicitly exercise default configuration takeover.+ # Profile acceptance selects the separate context rather than copying root output.+ access = agent.get('codex_access')+ mode = getattr(product, 'codex_access_mode', 'root')+ context = access[mode + '_context_id'] if access else agent['context_id']product.agent_context_id = contextproduct.agent_settings_agent_id = agent_idproduct.agent_connection = 'agent-connection/' + context@@ -56,7 +60,9 @@ def configure_model_settings_v2(product, allowed_plan_ids, key, default_plan_id='operations get ' + applied['data']['operation_id'])[1]raise AssertionError({'apply': applied, 'operation': operation})product.agent_settings_path = (- product.codex_settings if agent_id == 'agent_codex_default' else product.settings)+ (product.codex_settings.with_name('hiroute.config.toml')+ if getattr(product, 'codex_access_mode', 'root') == 'profile'+ else product.codex_settings) if agent_id == 'agent_codex_default' else product.settings)status = product.cli('agents connect status ' + context)[1]assert status['status'] == 'succeeded', statusassert status['data']['current_selection'] == preview['spec']['model']['settings'], statusdiff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.pyindex b748a1db..97078c77 100644--- a/crates/daemon/tests/support/standalone_headless_product.py+++ b/crates/daemon/tests/support/standalone_headless_product.py@@ -342,7 +342,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.1',+ '--cpa-binary', str(cpa), '--cpa-version', '8.0.4-hiroute.2','--cpa-license', str(license_path),'--notices', str(package_source / 'notices'), '--output', str(self.package),], cwd=self.repo, env=self.env, capture_output=True, timeout=90)@@ -677,13 +677,13 @@ def run(repository):codex = next(agent for agent in scan['agents']if agent['agent_id'] == 'agent_codex_default')assert codex['supported'], codex- context = codex['context_id']+ context = codex['codex_access']['root_context_id']checked_agent = product.cli('agents', 'check', 'agent_codex_default', '--scope', 'native-authentication')['data']assert checked_agent['native_authentication'] == 'proven'rescanned = next(agent for agent in product.cli('agents', 'scan')['data']['agents']if agent['agent_id'] == 'agent_codex_default')- assert rescanned['supported'] and rescanned['context_id'] == context, rescanned+ assert rescanned['supported'] and rescanned['codex_access']['root_context_id'] == context, rescannedspec = {'schema_version': {'major': 2, 'minor': 0},'context_id': context,diff --git a/crates/domain/src/agents/native_artifacts.rs b/crates/domain/src/agents/native_artifacts.rsindex cc3d4a21..fb05834f 100644--- a/crates/domain/src/agents/native_artifacts.rs+++ b/crates/domain/src/agents/native_artifacts.rs@@ -12,6 +12,14 @@ pub trait NativeAgentArtifactPort: ExternalEffectPort {operation: &OperationId,intent: &ExternalEffectIntentV1,) -> PortResult<crate::EffectReconciliation>;+ /// A trusted adapter has verified semantic restoration against the protected field record.+ /// Acknowledge only this exact safe snapshot; never write or compensate the user's file.+ fn acknowledge_native_restoration(+ &self,+ operation: &OperationId,+ intent: &ExternalEffectIntentV1,+ current: Option<&[u8]>,+ ) -> PortResult<OwnedEffectV1>;/// Stage a Skill effect while carrying only validated original directory ownership into its marker.fn stage_native_skill_target(&self,diff --git a/crates/integrations/src/agents/codex_catalog_effects.rs b/crates/integrations/src/agents/codex_catalog_effects.rsindex 1ec6cddd..3852da1e 100644--- a/crates/integrations/src/agents/codex_catalog_effects.rs+++ b/crates/integrations/src/agents/codex_catalog_effects.rs@@ -132,7 +132,10 @@ fn decode(intent: &ExternalEffectIntentV1) -> PortResult<CatalogPayload> {|| intent.desired_mode() != 0o600|| value["transaction"] != "settings"|| value["subject"]["agent_id"] != "agent_codex_default"- || value["subject"]["profile_id"] != "codex-responses-v1"+ || !matches!(+ value["subject"]["profile_id"].as_str(),+ Some("codex-responses-v1" | "codex-standalone-profile-v1")+ )|| value["subject"]["integration_profile_ref"] != "builtin/codex-responses/v1"{return Err(invalid());diff --git a/crates/integrations/src/agents/codex_config.rs b/crates/integrations/src/agents/codex_config.rsindex a3e3beb6..8c8822be 100644--- a/crates/integrations/src/agents/codex_config.rs+++ b/crates/integrations/src/agents/codex_config.rs@@ -149,6 +149,9 @@ pub(super) fn reconfigure_codex_native(if &CanonicalDigest::of_bytes(current.as_bytes()) != expected {return Err(CodexNativeError::SourceChanged);}+ if !managed_provider_shape(&parse(current)?) {+ return Err(CodexNativeError::FieldConflict);+ }let base = restore_codex_native(current, previous)?;configure_codex_base(&base,@@ -250,7 +253,7 @@ fn configure_codex_base()?;}for (key, value) in [- ("requires_openai_auth", true),+ ("requires_openai_auth", false),("supports_websockets", false),] {set(@@ -283,23 +286,75 @@ fn configure_codex_base(impl CodexNativeRestore {/// Status follows the fields HiRoute wrote. Other native settings and TOML formatting/// may change independently after the configuration Operation succeeds.- pub fn managed_fields_are_applied(&self, current: &str) -> bool {+ pub fn conflicting_fields(&self, current: &str) -> Vec<String> {let Ok(document) = parse(current) else {- return false;+ return vec!["invalid TOML".into()];};self.fields.iter()- .filter(|field| !field.passive_model)- .all(|field| {- let Some((key, parent)) = field.path.split_last() else {+ .filter(|field| {+ if field.passive_model {return false;+ }+ let Some((key, parent)) = field.path.split_last() else {+ return true;};- optional_table(&document, parent)+ let item = optional_table(&document, parent).ok().flatten()- .and_then(|table| table.get(key))- .is_some_and(|item| fingerprint(item) == field.after)+ .and_then(|t| t.get(key));+ item.map(fingerprint) != field.before.as_ref().map(fingerprint)+ && item.map(fingerprint).as_ref() != Some(&field.after)})+ .map(|field| field.path.join("."))+ .collect()+ }++ /// Pending cleanup names are safe to display; no previous values or credentials escape.+ pub fn pending_restoration_fields(&self, current: &str) -> Vec<String> {+ let Ok(document) = parse(current) else {+ return vec!["invalid TOML".into()];+ };+ self.fields+ .iter()+ .filter(|field| {+ let Some((key, parent)) = field.path.split_last() else {+ return true;+ };+ let item = optional_table(&document, parent)+ .ok()+ .flatten()+ .and_then(|t| t.get(key));+ if field.passive_model {+ return item.and_then(Item::as_str).is_some_and(|model| {+ self.managed_aliases.iter().any(|alias| alias == model)+ });+ }+ item.map(fingerprint) != field.before.as_ref().map(fingerprint)+ })+ .map(|field| field.path.join("."))+ .collect()+ }++ pub fn managed_fields_are_applied(&self, current: &str) -> bool {+ let Ok(document) = parse(current) else {+ return false;+ };+ managed_provider_shape(&document)+ && self+ .fields+ .iter()+ .filter(|field| !field.passive_model)+ .all(|field| {+ let Some((key, parent)) = field.path.split_last() else {+ return false;+ };+ optional_table(&document, parent)+ .ok()+ .flatten()+ .and_then(|table| table.get(key))+ .is_some_and(|item| fingerprint(item) == field.after)+ })}fn owns_provider(&self, provider_id: &str) -> bool {@@ -587,3 +642,27 @@ fn set(#[cfg(test)]mod tests;++fn managed_provider_shape(document: &DocumentMut) -> bool {+ let Some(provider) = document+ .get("model_providers")+ .and_then(|v| v.get("hiroute"))+ .and_then(Item::as_table)+ else {+ return false;+ };+ provider.iter().all(|(key, _)| {+ matches!(+ key,+ "name"+ | "base_url"+ | "wire_api"+ | "requires_openai_auth"+ | "supports_websockets"+ | "http_headers"+ )+ }) && provider+ .get("http_headers")+ .and_then(Item::as_table)+ .is_some_and(|headers| headers.iter().all(|(key, _)| key == "X-HiRoute-Token"))+}diff --git a/crates/integrations/src/agents/codex_config/tests.rs b/crates/integrations/src/agents/codex_config/tests.rsindex ff095b96..68306647 100644--- a/crates/integrations/src/agents/codex_config/tests.rs+++ b/crates/integrations/src/agents/codex_config/tests.rs@@ -64,7 +64,7 @@ fn codex_native_preserves_comments_unknown_fields_and_original_provider() {.as_str().is_some());- assert_eq!(provider["requires_openai_auth"].as_bool(), Some(true));+ assert_eq!(provider["requires_openai_auth"].as_bool(), Some(false));assert_eq!(provider["supports_websockets"].as_bool(), Some(false));for forbidden in ["experimental_bearer_token",@@ -421,3 +421,44 @@ fn codex_native_never_produces_a_config_too_large_for_its_restore_reader() {Err(CodexNativeError::InvalidToml)));}++#[test]+fn managed_profile_rejects_added_auth_fields_and_headers_but_preserves_them_on_revoke() {+ let edit = configure("", CodexSelectionTarget::Root).unwrap();+ for extra in [+ "[model_providers.hiroute]\nenv_key = 'USER_SECRET'\n",+ "[model_providers.hiroute.http_headers]\nAuthorization = 'user-owned'\n",+ ] {+ let mut current = edit.rendered.parse::<DocumentMut>().unwrap();+ let addition = extra.parse::<DocumentMut>().unwrap();+ if extra.contains("Authorization") {+ current["model_providers"]["hiroute"]["http_headers"]["Authorization"] =+ addition["model_providers"]["hiroute"]["http_headers"]["Authorization"].clone();+ } else {+ current["model_providers"]["hiroute"]["env_key"] =+ addition["model_providers"]["hiroute"]["env_key"].clone();+ }+ let current = current.to_string();+ assert!(!edit.restore.managed_fields_are_applied(¤t));+ assert!(matches!(+ reconfigure_codex_native(+ ¤t,+ &CanonicalDigest::of_bytes(current.as_bytes()),+ &edit.restore,+ CodexSelectionTarget::Root,+ "hiroute",+ "http://127.0.0.1:5837/v1",+ None,+ &AgentAccessGrantMaterial::from_csprng_entropy([4; 32]),+ ),+ Err(CodexNativeError::FieldConflict)+ ));+ let restored = restore_codex_native(¤t, &edit.restore).unwrap();+ assert!(!restored.contains("X-HiRoute-Token"));+ assert!(restored.contains(if extra.contains("Authorization") {+ "user-owned"+ } else {+ "USER_SECRET"+ }));+ }+}diff --git a/crates/integrations/src/agents/codex_profile.rs b/crates/integrations/src/agents/codex_profile.rsnew file mode 100644index 00000000..02f93fcb--- /dev/null+++ b/crates/integrations/src/agents/codex_profile.rs@@ -0,0 +1,183 @@+//! The first release owns one fixed standalone profile per original CODEX_HOME.+use super::AgentFilesystemScanError;+use super::filesystem_config::{read_system_config_bytes, read_validated_config_bytes};+use hiroute_domain::CanonicalDigest;+use std::path::{Path, PathBuf};+use toml_edit::DocumentMut;++pub const CODEX_STANDALONE_PROFILE_ID: &str = "codex-standalone-profile-v1";+pub const CODEX_MANAGED_PROFILE_NAME: &str = "hiroute";++/// Hash every inherited file, including absence. Never infer ownership from a filename.+pub fn codex_profile_dependency_digest(+ root: &Path,+ owned: bool,+) -> Result<CanonicalDigest, AgentFilesystemScanError> {+ let profile = root.with_file_name("hiroute.config.toml");+ let mut sampled = Vec::new();+ for (path, system) in [+ (PathBuf::from("/etc/codex/config.toml"), true),+ (PathBuf::from("/etc/codex/managed_config.toml"), true),+ (root.to_owned(), false),+ (profile.clone(), false),+ ] {+ let content = if system {+ read_system_config_bytes(&path)?+ } else {+ read_validated_config_bytes(&path)?+ };+ sampled.push((+ path.clone(),+ content+ .as_ref()+ .map(|(bytes, _)| CanonicalDigest::of_bytes(bytes)),+ ));+ if let Some((bytes, _)) = content {+ if path == profile && !owned {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ let text =+ std::str::from_utf8(&bytes).map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ let doc = text+ .parse::<DocumentMut>()+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;+ if path != profile+ && (doc+ .get("model_providers")+ .and_then(|v| v.get("hiroute"))+ .is_some()+ || doc.get("profiles").and_then(|v| v.get("hiroute")).is_some()+ || doc.get("profile").and_then(|v| v.as_str())+ == Some(CODEX_MANAGED_PROFILE_NAME))+ {+ return Err(AgentFilesystemScanError::InvalidConfig);+ }+ }+ }+ CanonicalDigest::of(&sampled).map_err(|_| AgentFilesystemScanError::InvalidConfig)+}++/// Explicit HOME binding is intentional: the terminal environment is not known to the UI.+pub fn codex_profile_commands(+ home: &Path,+) -> Result<std::collections::BTreeMap<String, String>, AgentFilesystemScanError> {+ let home = home+ .to_str()+ .filter(|v| !v.contains(['\0', '\r', '\n']))+ .ok_or(AgentFilesystemScanError::InvalidConfig)?;+ let posix = format!("'{}'", home.replace('\'', "'\"'\"'"));+ let fish = format!("'{}'", home.replace('\\', "\\\\").replace('\'', "\\'"));+ let powershell = format!("'{}'", home.replace('\'', "''"));+ Ok(std::collections::BTreeMap::from([+ (+ "bash/zsh".into(),+ format!("CODEX_HOME={posix} codex --profile hiroute"),+ ),+ (+ "fish".into(),+ format!("env CODEX_HOME={fish} codex --profile hiroute"),+ ),+ (+ "PowerShell".into(),+ format!(+ "& {{ $previous = $env:CODEX_HOME; try {{ $env:CODEX_HOME = {powershell}; codex --profile hiroute }} finally {{ $env:CODEX_HOME = $previous }} }}"+ ),+ ),+ ]))+}++/// Resolve the existing ancestor without creating files or following a replacement later.+pub fn canonical_codex_config_path(path: &Path) -> PathBuf {+ let Some(parent) = path.parent() else {+ return path.to_owned();+ };+ let mut ancestor = parent.to_owned();+ let mut suffix = Vec::new();+ while !ancestor.exists() {+ let Some(name) = ancestor.file_name().map(|v| v.to_owned()) else {+ return path.to_owned();+ };+ suffix.push(name);+ if !ancestor.pop() {+ return path.to_owned();+ }+ }+ let Ok(mut canonical) = ancestor.canonicalize() else {+ return path.to_owned();+ };+ for name in suffix.iter().rev() {+ canonical.push(name);+ }+ canonical.join("config.toml")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn launch_command_binds_original_home_without_shell_interpolation() {+ let home = Path::new("/tmp/a b'\"$HOME`false`\\codex");+ let commands = codex_profile_commands(home).unwrap();+ let script = format!(+ "codex() {{ printf '%s\\n' \"$CODEX_HOME\" \"$@\"; }}\n{}",+ commands["bash/zsh"]+ );+ let output = std::process::Command::new("bash")+ .args(["--noprofile", "--norc", "-c", &script])+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_eq!(+ String::from_utf8(output.stdout).unwrap(),+ format!("{}\n--profile\nhiroute\n", home.display())+ );+ assert!(commands["PowerShell"].contains("finally"));+ assert!(codex_profile_commands(Path::new("/tmp/line\nbreak")).is_err());+ }++ #[cfg(unix)]+ #[test]+ fn home_symlink_and_missing_suffix_have_one_canonical_identity() {+ let dir = tempfile::tempdir().unwrap();+ let actual = dir.path().join("actual");+ std::fs::create_dir(&actual).unwrap();+ let alias = dir.path().join("alias");+ std::os::unix::fs::symlink(&actual, &alias).unwrap();+ assert_eq!(+ canonical_codex_config_path(&actual.join("new/config.toml")),+ canonical_codex_config_path(&alias.join("new/config.toml"))+ );+ }++ #[cfg(unix)]+ #[test]+ fn inheritance_and_file_existence_are_preview_dependencies() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();+ let root = dir.path().join("config.toml");+ let absent = codex_profile_dependency_digest(&root, false).unwrap();+ std::fs::write(&root, "user_option = true\n").unwrap();+ std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o600)).unwrap();+ assert_ne!(+ absent,+ codex_profile_dependency_digest(&root, false).unwrap()+ );+ std::fs::write(&root, "[model_providers.hiroute]\nenv_key = 'SECRET'\n").unwrap();+ assert!(codex_profile_dependency_digest(&root, true).is_err());+ std::fs::write(&root, "[profiles.hiroute]\nmodel = 'legacy'\n").unwrap();+ assert!(codex_profile_dependency_digest(&root, true).is_err());+ std::fs::write(&root, "profile = 'hiroute'\n").unwrap();+ assert!(codex_profile_dependency_digest(&root, false).is_err());+ assert!(codex_profile_dependency_digest(&root, true).is_err());+ std::fs::write(&root, "profile = 'user_keep'\n").unwrap();+ assert!(codex_profile_dependency_digest(&root, false).is_ok());+ std::fs::write(&root, "").unwrap();+ let profile = root.with_file_name("hiroute.config.toml");+ std::fs::write(&profile, "").unwrap();+ std::fs::set_permissions(&profile, std::fs::Permissions::from_mode(0o600)).unwrap();+ assert!(codex_profile_dependency_digest(&root, false).is_err());+ assert!(codex_profile_dependency_digest(&root, true).is_ok());+ }+}diff --git a/crates/integrations/src/agents/codex_sources.rs b/crates/integrations/src/agents/codex_sources.rsindex e5f6ae28..90b82e9f 100644--- a/crates/integrations/src/agents/codex_sources.rs+++ b/crates/integrations/src/agents/codex_sources.rs@@ -61,21 +61,7 @@ impl FilesystemAgentScannerV1 {if &draft.public != selected {return Err(Error::SourceChanged);}- let credential = match draft.auth {- Auth::None => None,- Auth::Environment(key) => {- let value =- Zeroizing::new(std::env::var(key).map_err(|_| Error::SourceUnavailable)?);- Some(- ProtectedSecret::new(value.as_bytes().to_vec())- .map_err(|_| Error::SourceUnavailable)?,- )- }- Auth::Inline(value) => Some(- ProtectedSecret::new(value.as_bytes().to_vec())- .map_err(|_| Error::SourceUnavailable)?,- ),- };+ let protected = protect(draft)?;if self.codex_source_draft(scope)?.map(|draft| draft.public)@@ -84,17 +70,56 @@ impl FilesystemAgentScannerV1 {{return Err(Error::SourceChanged);}- Ok(ProtectedAgentSource {- endpoint: draft.endpoint,- model: draft.model,- credential,- })+ Ok(protected)+ }++ /// Trusted settings restoration supplies the authenticated field record. Source identity+ /// comes from the original provider, never the currently selected HiRoute Gateway provider.+ /// Sampling twice retains the existing race check; no user file is written.+ pub fn codex_source_before_managed_change(+ &self,+ restore: &super::CodexNativeRestore,+ ) -> Result<Option<(AgentSourceCandidate, ProtectedAgentSource)>, Error> {+ let scope =+ super::CodexConfigurationScope::user_file(self.layout.codex_user_config.clone());+ let Some(draft) = self.codex_source_draft_with_restore(&scope, Some(restore))? else {+ return Ok(None);+ };+ let selected = draft.public.clone();+ let protected = protect(draft)?;+ if self+ .codex_source_draft_with_restore(&scope, Some(restore))?+ .map(|d| d.public)+ .as_ref()+ != Some(&selected)+ {+ return Err(Error::SourceChanged);+ }+ Ok(Some((selected, protected)))}fn codex_source_draft(&self,scope: &super::CodexConfigurationScope,) -> Result<Option<Draft>, Error> {- let sampled = super::sample_codex_configuration(scope)?;+ self.codex_source_draft_with_restore(scope, None)+ }+ fn codex_source_draft_with_restore(+ &self,+ scope: &super::CodexConfigurationScope,+ restore: Option<&super::CodexNativeRestore>,+ ) -> Result<Option<Draft>, Error> {+ let mut sampled = super::sample_codex_configuration(scope)?;+ if let Some(restore) = restore {+ let text = Zeroizing::new(sampled.source_document.to_string());+ let restored =+ super::restore_codex_native(&text, restore).map_err(|_| Error::SourceChanged)?;+ sampled.source_document = restored.parse().map_err(|_| Error::InvalidConfig)?;+ sampled.dependency_digest = CanonicalDigest::of(&(+ sampled.dependency_digest,+ CanonicalDigest::of_bytes(restored.as_bytes()),+ ))+ .map_err(|_| Error::InvalidConfig)?;+ }let document = &sampled.source_document;// An absent or empty config.toml is a valid Codex configuration: the built-in// OpenAI provider and native login still apply.@@ -197,3 +222,25 @@ fn identifier(value: &str) -> bool {fn environment_identifier(value: &str) -> bool {identifier(value) && !value.contains('-') && !value.as_bytes()[0].is_ascii_digit()}++fn protect(draft: Draft) -> Result<ProtectedAgentSource, Error> {+ let credential = match draft.auth {+ Auth::None => None,+ Auth::Environment(key) => {+ let value = Zeroizing::new(std::env::var(key).map_err(|_| Error::SourceUnavailable)?);+ Some(+ ProtectedSecret::new(value.as_bytes().to_vec())+ .map_err(|_| Error::SourceUnavailable)?,+ )+ }+ Auth::Inline(value) => Some(+ ProtectedSecret::new(value.as_bytes().to_vec())+ .map_err(|_| Error::SourceUnavailable)?,+ ),+ };+ Ok(ProtectedAgentSource {+ endpoint: draft.endpoint,+ model: draft.model,+ credential,+ })+}diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rsindex 2cf232e4..9f5f756a 100644--- a/crates/integrations/src/agents/filesystem.rs+++ b/crates/integrations/src/agents/filesystem.rs@@ -236,7 +236,8 @@ impl FilesystemAgentScannerV1 {))}- pub fn new(layout: AgentFilesystemLayoutV1, registry: ClaudeRegistrationIndexV1) -> Self {+ pub fn new(mut layout: AgentFilesystemLayoutV1, registry: ClaudeRegistrationIndexV1) -> Self {+ layout.codex_user_config = super::canonical_codex_config_path(&layout.codex_user_config);Self {layout,registry,@@ -493,6 +494,12 @@ impl FilesystemAgentScannerV1 {self.layout.codex_user_config.clone()}+ pub fn codex_profile_config_target(&self) -> PathBuf {+ self.layout+ .codex_user_config+ .with_file_name("hiroute.config.toml")+ }+/// Exact engine selected for one Codex surface. This is target location only: callers must/// never turn a version, digest, or installation proof into product admission.pub fn codex_engine_target(diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rsindex 31fe4ee5..9b559167 100644--- a/crates/integrations/src/agents/mod.rs+++ b/crates/integrations/src/agents/mod.rs@@ -57,3 +57,6 @@ pub use subscription_sources::*;#[cfg(test)]mod tests;++mod codex_profile;+pub use codex_profile::*;diff --git a/crates/integrations/src/agents/settings_discovery.rs b/crates/integrations/src/agents/settings_discovery.rsindex 196c0366..484cd066 100644--- a/crates/integrations/src/agents/settings_discovery.rs+++ b/crates/integrations/src/agents/settings_discovery.rs@@ -2,6 +2,14 @@use super::*;impl FilesystemAgentScannerV1 {+ pub fn codex_profile_settings_discovery(&self) -> FilesystemAgentDiscoveryV1 {+ // The profile owns its file capabilities; inherited root is independently sealed for+ // configure, and must not make a safe revoke depend on the current root's validity.+ let mut profile = self.clone();+ profile.layout.codex_user_config = self.codex_profile_config_target();+ profile.codex_settings_discovery(false)+ }+pub fn codex_settings_discovery(&self,include_collaboration_evidence: bool,diff --git a/crates/local-storage/src/agents/native_artifacts.rs b/crates/local-storage/src/agents/native_artifacts.rsindex 22ce91af..4921a73f 100644--- a/crates/local-storage/src/agents/native_artifacts.rs+++ b/crates/local-storage/src/agents/native_artifacts.rs@@ -11,6 +11,72 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {) -> PortResult<hiroute_domain::EffectReconciliation> {ManagedArtifactStore::observe_artifact(self, operation, intent)}+ fn acknowledge_native_restoration(+ &self,+ operation: &OperationId,+ intent: &ExternalEffectIntentV1,+ expected: Option<&[u8]>,+ ) -> PortResult<OwnedEffectV1> {+ if matches!(+ self.observe_artifact(operation, intent)?,+ EffectReconciliation::Missing+ ) && self+ .load_marker(operation, intent.effect_id())+ .map_err(|_| port(PortErrorCode::Corrupt, "native.restoration.marker"))?+ .is_none()+ {+ return self.acknowledge_unstaged_native_restoration(operation, intent, expected);+ }+ // Observe authenticates the marker, intent binding and backup before any acknowledgment.+ if !matches!(+ self.observe_artifact(operation, intent)?,+ hiroute_domain::EffectReconciliation::OwnershipLost(_)+ ) {+ return Err(port(PortErrorCode::Conflict, "native.restoration.state"));+ }+ let mut marker = self+ .load_marker(operation, intent.effect_id())+ .map_err(|_| port(PortErrorCode::Corrupt, "native.restoration.marker"))?+ .ok_or_else(|| port(PortErrorCode::NotFound, "native.restoration.marker"))?;+ if marker.compensated+ || !marker.rendered+ || marker.kind != OwnedEffectKind::AgentArtifact+ || marker.after_mode != intent.desired_mode()+ || marker.target != intent.target()+ || marker.before_digest.as_ref() != intent.before_fingerprint()+ || marker.intent_digest.as_ref()+ != Some(+ &hiroute_domain::CanonicalDigest::of(intent.desired()).map_err(|_| {+ port(PortErrorCode::InvalidData, "native.restoration.intent")+ })?,+ )+ {+ return Err(port(PortErrorCode::Conflict, "native.restoration.binding"));+ }+ self.validated_backup(&marker)+ .map_err(|_| port(PortErrorCode::Corrupt, "native.restoration.backup"))?;+ let path = self+ .target_path(intent.target())+ .map_err(|_| port(PortErrorCode::PermissionDenied, "native.restoration.target"))?;+ let current = read_native_file(&path, MAX_NATIVE_BYTES)+ .map_err(|_| port(PortErrorCode::Conflict, "native.restoration.file"))?;+ if current.as_deref().map(|b| b.as_slice()) != expected {+ return Err(port(PortErrorCode::Conflict, "native.restoration.changed"));+ }+ let snapshot = read_artifact(&path)+ .map_err(|_| port(PortErrorCode::Conflict, "native.restoration.snapshot"))?;+ if snapshot.as_ref().map(|s| s.bytes.as_slice()) != expected {+ return Err(port(PortErrorCode::Conflict, "native.restoration.changed"));+ }+ marker.native_restoration = Some(NativeRestorationReceipt {+ fingerprint: snapshot.map(|s| s.fingerprint),+ });+ marker.activated = true;+ self.save_marker(&marker)+ .map_err(|_| port(PortErrorCode::Unavailable, "native.restoration.persist"))?;+ Ok(Self::effect(&marker))+ }+fn stage_native_skill_target(&self,operation: &OperationId,diff --git a/crates/local-storage/src/agents/native_file_tests.rs b/crates/local-storage/src/agents/native_file_tests.rsindex 05675bfd..100d692c 100644--- a/crates/local-storage/src/agents/native_file_tests.rs+++ b/crates/local-storage/src/agents/native_file_tests.rs@@ -521,3 +521,355 @@ fn all_native_target_bindings_are_restored_together_before_marker_validation() {redirected[1].1 = root.path().join("replacement.toml");assert!(open(redirected).is_err());}++#[test]+fn native_restoration_acknowledgment_preserves_bytes_and_reopens() {+ let temp = crate::test_tempdir().unwrap();+ let path = temp.path().join("config.toml");+ write(&path, b"owned = true\n");+ let prototype = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ None,+ );+ let artifacts = store(temp.path(), prototype.target(), &path);+ let cleanup = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ artifacts+ .current_external_fingerprint(prototype.target())+ .unwrap(),+ );+ let op = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();+ artifacts+ .stage_native_target(&op, &cleanup, None, true)+ .unwrap();+ let cleaned = b"# new unrelated comment\nuser_setting = true\n";+ write(&path, cleaned);+ assert!(+ artifacts+ .acknowledge_native_restoration(&op, &cleanup, Some(b"stale"))+ .is_err()+ );+ let effect = artifacts+ .acknowledge_native_restoration(&op, &cleanup, Some(cleaned))+ .unwrap();+ assert_eq!(fs::read(&path).unwrap(), cleaned);+ drop(artifacts);+ let reopened = store(temp.path(), prototype.target(), &path);+ assert!(matches!(+ reopened.observe_artifact(&op, &cleanup).unwrap(),+ EffectReconciliation::Applied(_)+ ));+ assert_eq!(+ reopened.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::OwnershipLost+ );+ write(&path, b"# changed after acknowledgment\n");+ assert!(matches!(+ reopened.observe_artifact(&op, &cleanup).unwrap(),+ EffectReconciliation::OwnershipLost(_)+ ));+}++#[test]+fn unstaged_restoration_ack_is_protected_bound_and_never_rewrites() {+ let original = OperationId::parse("op_11112222333344445555666677778888").unwrap();+ let cleanup = |before| {+ let spec = ChangeSpecV1 {+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,+ command_id: "agents.settings.apply".into(),+ resource_id: Some("agent-context/unstaged-cleanup".into()),+ desired_state: json!({"schema_version":{"major":2,"minor":0},+ "context_id":"agent-context/unstaged-cleanup",+ "model":{"intent":"restore","restore_point_ref":"restore/original"}}),+ };+ let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(+ "agent_codex_default",+ "codex-standalone-profile-v1",+ "builtin/codex-responses/v1",+ )+ .unwrap();+ let control = AgentConnectionControlIntentV1::from_settings_planner(+ subject,+ &spec,+ false,+ &json!({"revision":1}),+ )+ .unwrap();+ settings_codex_model_file_intent(+ &control,+ "agent-context/unstaged-cleanup",+ CanonicalDigest::of_bytes(b"original"),+ before,+ CodexModelFileAction::Restore {+ original_operation: original.clone(),+ native_model: None,+ },+ )+ .unwrap()+ };+ let temp = crate::test_tempdir().unwrap();+ let path = temp.path().join("hiroute.config.toml");+ write(&path, b"original");+ let prototype = cleanup(None);+ let artifacts = store(temp.path(), prototype.target(), &path);+ let intent = cleanup(+ artifacts+ .current_external_fingerprint(prototype.target())+ .unwrap(),+ );+ let op = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();+ let cleaned = b"# user retained content\nuser_setting = true\n";+ write(&path, cleaned);+ assert!(+ artifacts+ .acknowledge_native_restoration(&op, &intent, Some(b"stale"))+ .is_err()+ );+ let effect = artifacts+ .acknowledge_native_restoration(&op, &intent, Some(cleaned))+ .unwrap();+ assert_eq!(fs::read(&path).unwrap(), cleaned);+ drop(artifacts);+ let reopened = store(temp.path(), prototype.target(), &path);+ assert!(matches!(+ reopened.observe_artifact(&op, &intent).unwrap(),+ EffectReconciliation::Applied(_)+ ));+ assert!(matches!(+ reopened.observe_artifact(&original, &intent).unwrap(),+ EffectReconciliation::Missing+ ));+ assert_eq!(+ reopened.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::OwnershipLost+ );+ let record = fs::read_dir(&reopened.restore_root)+ .unwrap()+ .map(|e| e.unwrap().path())+ .find(|p| p.extension().is_some_and(|e| e == "native-restore"))+ .unwrap();+ let encrypted = fs::read(&record).unwrap();+ let mut damaged = encrypted.clone();+ *damaged.last_mut().unwrap() ^= 1;+ fs::write(&record, damaged).unwrap();+ assert!(reopened.observe_artifact(&op, &intent).is_err());+ fs::write(&record, encrypted).unwrap();+ write(&path, b"# changed after acknowledgment\n");+ assert!(matches!(+ reopened.observe_artifact(&op, &intent).unwrap(),+ EffectReconciliation::OwnershipLost(_)+ ));+}++// Exercise ownership checks even when the caller permits group/world writes. Changing+// a process-wide umask in the parallel parent would race fixtures, so isolate each case.+fn run_with_permissive_umask(name: &str) -> bool {+ const CHILD_CASE: &str = "HIROUTE_STORAGE_PERMISSIVE_UMASK_CASE";+ if std::env::var(CHILD_CASE).as_deref() == Ok(name) {+ rustix::process::umask(rustix::fs::Mode::from_raw_mode(0o000));+ return false;+ }+ let test = format!("control::native_file_tests::{name}");+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", &test, "--nocapture"])+ .env(CHILD_CASE, name)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success()+ && stdout.contains(&format!("test {test} ... ok"))+ && stdout.contains("1 passed; 0 failed; 0 ignored;"),+ "Permissive umask child did not pass the selected case: {name}\n{stdout}\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ true+}++#[test]+fn settings_unactivated_target_race_discards_only_the_owned_rendered_stage() {+ if run_with_permissive_umask(+ "settings_unactivated_target_race_discards_only_the_owned_rendered_stage",+ ) {+ return;+ }+ let root = crate::test_tempdir().unwrap();+ let target = root.path().join("config.toml");+ write(&target, b"before = true\n");+ let op = OperationId::parse("op_55555555555555555555555555555555").unwrap();+ let i = intent(+ AgentConnectionTransactionKindV1::Apply,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ None,+ );+ let artifact = store(root.path(), i.target(), &target);+ let i = intent(+ AgentConnectionTransactionKindV1::Apply,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ artifact.current_external_fingerprint(i.target()).unwrap(),+ );+ let effect = artifact+ .stage_native_target(&op, &i, Some(b"after = true\n"), true)+ .unwrap();+ write(&target, b"user_edit = true\n");+ assert!(matches!(+ artifact.observe_artifact(&op, &i).unwrap(),+ EffectReconciliation::OwnershipLost(_)+ ));+ assert_eq!(+ artifact.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::Compensated+ );+ assert_eq!(fs::read(&target).unwrap(), b"user_edit = true\n");+ assert_eq!(+ artifact.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::AlreadyCompensated+ );+ assert!(matches!(+ artifact.observe_artifact(&op, &i).unwrap(),+ EffectReconciliation::Missing+ ));+}++#[test]+fn settings_missing_stage_does_not_prove_a_target_was_never_written() {+ if run_with_permissive_umask("settings_missing_stage_does_not_prove_a_target_was_never_written")+ {+ return;+ }+ let root = crate::test_tempdir().unwrap();+ let target = root.path().join("config.toml");+ write(&target, b"before = true\n");+ let op = OperationId::parse("op_66666666666666666666666666666666").unwrap();+ let prototype = intent(+ AgentConnectionTransactionKindV1::Apply,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ None,+ );+ let artifact = store(root.path(), prototype.target(), &target);+ let i = intent(+ AgentConnectionTransactionKindV1::Apply,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ artifact+ .current_external_fingerprint(prototype.target())+ .unwrap(),+ );+ let effect = artifact+ .stage_native_target(&op, &i, Some(b"after = true\n"), true)+ .unwrap();+ let marker = artifact.load_marker(&op, i.effect_id()).unwrap().unwrap();+ fs::rename(artifact.stage_path(&marker).unwrap(), &target).unwrap();+ write(&target, b"user_edit_after_rename = true\n");+ assert_eq!(+ artifact.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::OwnershipLost+ );+ assert_eq!(+ fs::read(&target).unwrap(),+ b"user_edit_after_rename = true\n"+ );+}++#[test]+fn settings_delete_with_intact_stage_does_not_prove_no_target_write() {+ if run_with_permissive_umask("settings_delete_with_intact_stage_does_not_prove_no_target_write")+ {+ return;+ }+ let root = crate::test_tempdir().unwrap();+ let target = root.path().join("profile.toml");+ write(&target, b"managed = true\n");+ let op = OperationId::parse("op_77777777777777777777777777777777").unwrap();+ let prototype = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ None,+ );+ let artifact = store(root.path(), prototype.target(), &target);+ let i = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ artifact+ .current_external_fingerprint(prototype.target())+ .unwrap(),+ );+ let effect = artifact.stage_native_target(&op, &i, None, true).unwrap();+ let marker = artifact.load_marker(&op, i.effect_id()).unwrap().unwrap();+ assert!(artifact.stage_path(&marker).unwrap().exists());+ fs::remove_file(&target).unwrap();+ // Model a crash after unlink: a reopened store must not regain in-process proof.+ drop(artifact);+ let artifact = store(root.path(), prototype.target(), &target);+ assert_eq!(+ artifact.compensate_artifact(&effect).unwrap(),+ CompensationOutcome::OwnershipLost+ );+ assert!(!target.exists());+}++#[test]+fn settings_delete_race_requires_live_untouched_target_proof() {+ if run_with_permissive_umask("settings_delete_race_requires_live_untouched_target_proof") {+ return;+ }+ for case in [+ "fresh",+ "reopen",+ "missing_stage",+ "tampered_stage",+ "unlink_attempt",+ ] {+ let root = crate::test_tempdir().unwrap();+ let target = root.path().join("profile.toml");+ write(&target, b"managed = true\n");+ let op = OperationId::parse("op_88888888888888888888888888888888").unwrap();+ let prototype = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ None,+ );+ let mut artifact = store(root.path(), prototype.target(), &target);+ let i = intent(+ AgentConnectionTransactionKindV1::Restore,+ AgentConnectionEffectRoleV1::ManagedConfiguration,+ artifact+ .current_external_fingerprint(prototype.target())+ .unwrap(),+ );+ let effect = artifact.stage_native_target(&op, &i, None, true).unwrap();+ let marker = artifact.load_marker(&op, i.effect_id()).unwrap().unwrap();+ let stage = artifact.stage_path(&marker).unwrap();+ if case == "unlink_attempt" {+ // Execute the real unlink, then reconstruct the durable crash window before+ // stage consumption/marker persistence. Live proof must already be consumed.+ artifact.activate_artifact(&effect).unwrap();+ assert!(!target.exists());+ artifact.save_marker(&marker).unwrap();+ write(&stage, b"");+ }+ write(&target, b"user_edit = true\n");+ if case == "reopen" {+ drop(artifact);+ artifact = store(root.path(), prototype.target(), &target);+ }+ assert!(artifact.activate_artifact(&effect).is_err());+ match case {+ "missing_stage" => fs::remove_file(&stage).unwrap(),+ "tampered_stage" => write(&stage, b"foreign stage"),+ _ => {}+ }+ let expected = if case == "fresh" {+ CompensationOutcome::Compensated+ } else {+ CompensationOutcome::OwnershipLost+ };+ assert_eq!(+ artifact.compensate_artifact(&effect).unwrap(),+ expected,+ "{case}"+ );+ assert_eq!(fs::read(&target).unwrap(), b"user_edit = true\n", "{case}");+ }+}diff --git a/crates/local-storage/src/agents/native_restoration_ack.rs b/crates/local-storage/src/agents/native_restoration_ack.rsnew file mode 100644index 00000000..b468690e--- /dev/null+++ b/crates/local-storage/src/agents/native_restoration_ack.rs@@ -0,0 +1,135 @@+//! Protected proof of user cleanup when restoration failed before any file was staged.+use super::native_artifacts::read_native_file;+use super::*;+use hiroute_domain::NativeAgentArtifactPort;++pub(super) const ACK_SCHEMA: &str = "hiroute.native-restoration-ack/v1";++#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct RestorationAck {+ schema: String,+ fingerprint: Option<CanonicalDigest>,+}++fn accepts_ack(intent: &ExternalEffectIntentV1) -> bool {+ hiroute_domain::is_settings_managed_configuration(intent)+ && intent.desired()["payload"]["schema"] == "hiroute.settings-codex-model-file/v1"+ && intent.desired()["payload"]["change"]["action"] == "restore"+}++impl ManagedArtifactStore {+ fn unstaged_ack_effect(+ operation: &OperationId,+ intent: &ExternalEffectIntentV1,+ fingerprint: Option<CanonicalDigest>,+ ) -> OwnedEffectV1 {+ OwnedEffectV1 {+ effect_id: intent.effect_id().into(),+ kind: intent.kind(),+ target: intent.target().into(),+ before_fingerprint: intent.before_fingerprint().cloned(),+ after_fingerprint: fingerprint,+ compensation:+ json!({"schema":ACK_SCHEMA,"operation_id":operation,"effect_id":intent.effect_id()})+ .into(),+ }+ }++ pub(super) fn observe_unstaged_native_restoration(+ &self,+ operation: &OperationId,+ intent: &ExternalEffectIntentV1,+ ) -> PortResult<Option<EffectReconciliation>> {+ if !accepts_ack(intent) {+ return Ok(None);+ }+ let Some(record) = self.load_native_restore(operation, intent)? else {+ return Ok(None);+ };+ let ack: RestorationAck = serde_json::from_slice(&record)+ .map_err(|_| port(PortErrorCode::Corrupt, "native.restoration.ack.decode"))?;+ if ack.schema != ACK_SCHEMA {+ return Err(port(+ PortErrorCode::Corrupt,+ "native.restoration.ack.schema",+ ));+ }+ let target = self.native_target_path(intent.target())?;+ let safe = read_native_file(&target, 1024 * 1024).map_err(|_| {+ port(+ PortErrorCode::PermissionDenied,+ "native.restoration.ack.read",+ )+ })?;+ let snapshot = read_artifact(&target).map_err(|_| {+ port(+ PortErrorCode::PermissionDenied,+ "native.restoration.ack.snapshot",+ )+ })?;+ if safe.as_deref().map(|b| b.as_slice()) != snapshot.as_ref().map(|s| s.bytes.as_slice()) {+ return Err(port(+ PortErrorCode::Conflict,+ "native.restoration.ack.changed",+ ));+ }+ let current = snapshot.map(|s| s.fingerprint);+ let effect = Self::unstaged_ack_effect(operation, intent, ack.fingerprint.clone());+ Ok(Some(if current == ack.fingerprint {+ EffectReconciliation::Applied(effect)+ } else {+ EffectReconciliation::OwnershipLost(effect)+ }))+ }++ pub(super) fn acknowledge_unstaged_native_restoration(+ &self,+ operation: &OperationId,+ intent: &ExternalEffectIntentV1,+ expected: Option<&[u8]>,+ ) -> PortResult<OwnedEffectV1> {+ if !accepts_ack(intent) {+ return Err(port(+ PortErrorCode::InvalidData,+ "native.restoration.ack.intent",+ ));+ }+ let target = self.native_target_path(intent.target())?;+ let current = read_native_file(&target, 1024 * 1024).map_err(|_| {+ port(+ PortErrorCode::PermissionDenied,+ "native.restoration.ack.read",+ )+ })?;+ let snapshot = read_artifact(&target).map_err(|_| {+ port(+ PortErrorCode::PermissionDenied,+ "native.restoration.ack.snapshot",+ )+ })?;+ if current.as_deref().map(|b| b.as_slice()) != expected+ || snapshot.as_ref().map(|s| s.bytes.as_slice()) != expected+ {+ return Err(port(+ PortErrorCode::Conflict,+ "native.restoration.ack.changed",+ ));+ }+ let fingerprint = snapshot.map(|s| s.fingerprint);+ let encoded = serde_json::to_vec(&RestorationAck {+ schema: ACK_SCHEMA.into(),+ fingerprint: fingerprint.clone(),+ })+ .map_err(|_| port(PortErrorCode::InvalidData, "native.restoration.ack.encode"))?;+ // Existing encryption authenticates the exact Operation, intent, target and store key.+ self.save_native_restore(operation, intent, &encoded)?;+ match self.observe_unstaged_native_restoration(operation, intent)? {+ Some(EffectReconciliation::Applied(effect)) => Ok(effect),+ _ => Err(port(+ PortErrorCode::Conflict,+ "native.restoration.ack.changed",+ )),+ }+ }+}diff --git a/crates/local-storage/src/control/mod.rs b/crates/local-storage/src/control/mod.rsindex 12459a76..65629e49 100644--- a/crates/local-storage/src/control/mod.rs+++ b/crates/local-storage/src/control/mod.rs@@ -42,6 +42,8 @@ mod journal;mod native_artifacts;#[path = "../agents/native_directories.rs"]mod native_directories;+#[path = "../agents/native_restoration_ack.rs"]+mod native_restoration_ack;mod operation_status;mod plans;mod prices;@@ -1879,6 +1881,11 @@ fn port(code: PortErrorCode, context: &'static str) -> PortError {PortError::new(code, context)}+#[derive(Clone, Debug, Deserialize, Serialize)]+struct NativeRestorationReceipt {+ fingerprint: Option<CanonicalDigest>,+}+#[derive(Clone, Debug, Deserialize, Serialize)]struct ArtifactMarker {schema: String,@@ -1907,6 +1914,8 @@ struct ArtifactMarker {backup_aad: ArtifactBackupAad,activated: bool,compensated: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ native_restoration: Option<NativeRestorationReceipt>,#[serde(default, skip_serializing_if = "Vec::is_empty")]created_directories: Vec<CreatedNativeDirectory>,}@@ -1931,6 +1940,8 @@ pub struct ManagedArtifactStore {restore_store_uuid: String,restore_key_id: CanonicalDigest,external_targets: BTreeMap<String, PathBuf>,+ // Process-local proof only. Reopening/replaying a deletion never recreates it.+ untouched_deletions: std::sync::Mutex<BTreeMap<(String, String), CanonicalDigest>>,}fn artifact_present() -> bool {@@ -1968,6 +1979,7 @@ impl ManagedArtifactStore {restore_store_uuid: restore.store_uuid,restore_key_id: restore.key_id,external_targets: BTreeMap::new(),+ untouched_deletions: std::sync::Mutex::new(BTreeMap::new()),};store.migrate_legacy_markers()?;store.validate_existing_marker_bindings()?;@@ -2018,6 +2030,7 @@ impl ManagedArtifactStore {restore_store_uuid: restore.store_uuid,restore_key_id: restore.key_id,external_targets,+ untouched_deletions: std::sync::Mutex::new(BTreeMap::new()),};// Validate every durable marker only after its native path binding is present. This is// the restart-safe counterpart to bind_external_target, which is used before first Apply.@@ -2323,6 +2336,11 @@ impl ManagedArtifactStore {|| !supported_artifact_mode(marker.after_mode)|| (marker.sensitive && marker.after_mode != 0o600)|| marker.external_path_digest != self.external_path_digest(&marker.target)?+ || marker.native_restoration.is_some()+ && (!marker.rendered+ || !marker.activated+ || marker.compensated+ || marker.kind != OwnedEffectKind::AgentArtifact)|| marker.rendered != marker.intent_digest.is_some()|| (marker.backup_name.is_none() && marker.backup_aad != ArtifactBackupAad::CurrentV4){@@ -2420,7 +2438,10 @@ impl ManagedArtifactStore {kind: marker.kind,target: marker.target.clone(),before_fingerprint: marker.before_digest.clone(),- after_fingerprint: marker.after_exists.then(|| marker.after_digest.clone()),+ after_fingerprint: marker.native_restoration.as_ref().map_or_else(+ || marker.after_exists.then(|| marker.after_digest.clone()),+ |r| r.fingerprint.clone(),+ ),compensation: json!({"schema": "hiroute.managed-artifact-compensation/v1","operation_id": marker.operation_id,@@ -2461,6 +2482,10 @@ impl ManagedArtifactStore {after_exists: bool,inherited_parents: Vec<CreatedNativeDirectory>,) -> PortResult<OwnedEffectV1> {+ let mut untouched = self+ .untouched_deletions+ .lock()+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.deletion.lock"))?;if !matches!(intent.kind(),OwnedEffectKind::Publication | OwnedEffectKind::AgentArtifact@@ -2553,6 +2578,7 @@ impl ManagedArtifactStore {backup_aad: ArtifactBackupAad::CurrentV4,activated: false,compensated: false,+ native_restoration: None,created_directories,};if let (Some(snapshot), Some(name)) = (&before, &marker.backup_name) {@@ -2574,6 +2600,14 @@ impl ManagedArtifactStore {.map_err(|_| port(PortErrorCode::InvalidData, "artifact.stage"))?;atomic_write(&stage, desired, marker.after_mode, marker.sensitive).map_err(|_| port(PortErrorCode::Unavailable, "artifact.stage.write"))?;+ if marker.rendered && !marker.after_exists && marker.kind == OwnedEffectKind::AgentArtifact+ {+ untouched.insert(+ (marker.operation_id.clone(), marker.effect_id.clone()),+ CanonicalDigest::of(&marker)+ .map_err(|_| port(PortErrorCode::InvalidData, "artifact.deletion.identity"))?,+ );+ }Ok(Self::effect(&marker))}}@@ -2617,6 +2651,9 @@ impl ManagedArtifactStore {.load_marker(operation_id, intent.effect_id()).map_err(|_| port(PortErrorCode::Unavailable, "artifact.marker.observe"))?else {+ if let Some(state) = self.observe_unstaged_native_restoration(operation_id, intent)? {+ return Ok(state);+ }return Ok(EffectReconciliation::Missing);};if marker.compensated {@@ -2659,6 +2696,15 @@ impl ManagedArtifactStore {let current_digest = current.as_ref().map(|snapshot| snapshot.fingerprint.clone());+ if let Some(receipt) = &marker.native_restoration {+ return Ok(+ if marker.activated && current_digest == receipt.fingerprint {+ EffectReconciliation::Applied(Self::effect(&marker))+ } else {+ EffectReconciliation::OwnershipLost(Self::effect(&marker))+ },+ );+ }if marker.activated&& current_digest.as_ref() == marker.after_exists.then_some(&marker.after_digest){@@ -2689,6 +2735,10 @@ impl ManagedArtifactStore {}pub fn activate_artifact(&self, effect: &OwnedEffectV1) -> PortResult<OwnedEffectV1> {+ let mut untouched = self+ .untouched_deletions+ .lock()+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.deletion.lock"))?;let operation_id = effect.compensation.get("operation_id")@@ -2742,6 +2792,8 @@ impl ManagedArtifactStore {"artifact.activate.stage_ownership",));}+ // Clear before the first target mutation, including uncertain I/O failures.+ untouched.remove(&(marker.operation_id.clone(), marker.effect_id.clone()));if marker.after_exists {fs::rename(&stage, &target).map_err(|_| port(PortErrorCode::Unavailable, "artifact.activate.rename"))?;@@ -2758,6 +2810,8 @@ impl ManagedArtifactStore {sync_parent(&target).map_err(|_| port(PortErrorCode::Unavailable, "artifact.activate.sync"))?;}+ // Also consume proof when absence was already observed, before finalization.+ untouched.remove(&(marker.operation_id.clone(), marker.effect_id.clone()));let activated = read_artifact(&target).map_err(|_| port(PortErrorCode::Unavailable, "artifact.activate.verify"))?;if activated.as_ref().map(|snapshot| &snapshot.fingerprint)@@ -2794,6 +2848,15 @@ impl ManagedArtifactStore {}pub fn compensate_artifact(&self, effect: &OwnedEffectV1) -> PortResult<CompensationOutcome> {+ let mut untouched = self+ .untouched_deletions+ .lock()+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.deletion.lock"))?;+ // A semantic acknowledgment did not write the client file; it never authorizes undoing+ // the user's cleanup, including recovery of a failed enclosing operation.+ if effect.compensation["schema"] == native_restoration_ack::ACK_SCHEMA {+ return Ok(CompensationOutcome::OwnershipLost);+ }let operation_id = effect.compensation.get("operation_id")@@ -2810,6 +2873,9 @@ impl ManagedArtifactStore {.load_marker(&operation_id, effect_id).map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.marker"))?.ok_or_else(|| port(PortErrorCode::NotFound, "artifact.compensate.marker"))?;+ if marker.native_restoration.is_some() {+ return Ok(CompensationOutcome::OwnershipLost);+ }if marker.compensated {return Ok(CompensationOutcome::AlreadyCompensated);}@@ -2827,25 +2893,41 @@ impl ManagedArtifactStore {let stage = self.stage_path(&marker).map_err(|_| port(PortErrorCode::Corrupt, "artifact.compensate.stage"))?;- if let Some(snapshot) = read_artifact(&stage)- .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.stage"))?+ let staged = read_artifact(&stage)+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.stage"))?;+ let stage_present = staged.is_some();+ let key = (marker.operation_id.clone(), marker.effect_id.clone());+ let fresh_delete = marker.rendered+ && !marker.after_exists+ && marker.kind == OwnedEffectKind::AgentArtifact+ && untouched.get(&key)+ == Some(&CanonicalDigest::of(&marker).map_err(|_| {+ port(PortErrorCode::InvalidData, "artifact.deletion.identity")+ })?);+ if let Some(snapshot) = &staged+ && snapshot.fingerprint != marker.after_digest{- if snapshot.fingerprint != marker.after_digest {- return Ok(CompensationOutcome::OwnershipLost);- }- fs::remove_file(&stage)- .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.stage"))?;- sync_parent(&stage)- .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.sync"))?;+ return Ok(CompensationOutcome::OwnershipLost);}- if current_digest != marker.before_digest+ // An intact rendered stage proves rename has not happened. Discard only our+ // stage and preserve a concurrent user edit; no target write needs undoing.+ // Without the stage, a crash after rename remains uncertain and fails closed.+ if !(marker.rendered && (marker.after_exists || fresh_delete) && stage_present)+ && current_digest != marker.before_digest&& !(!marker.before_exists && current.is_none()){return Ok(CompensationOutcome::OwnershipLost);}+ if stage_present {+ fs::remove_file(&stage)+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.stage"))?;+ sync_parent(&stage)+ .map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.sync"))?;+ }marker.compensated = true;self.save_marker(&marker).map_err(|_| port(PortErrorCode::Unavailable, "artifact.compensate.mark"))?;+ untouched.remove(&key);return Ok(CompensationOutcome::Compensated);}if current_digest != marker.after_exists.then(|| marker.after_digest.clone()) {diff --git a/crates/local-storage/src/lib.rs b/crates/local-storage/src/lib.rsindex eba7f62f..180820ab 100644--- a/crates/local-storage/src/lib.rs+++ b/crates/local-storage/src/lib.rs@@ -320,8 +320,8 @@ pub fn upgrade_backup_root(storage_root: &Path) -> Result<std::path::PathBuf, Lomod startup_tests {use super::*;use hiroute_domain::{- CanonicalDigest, ControlRepositoryPort, ProtectedApplyCapability, RevisionSetV1,- WorkspaceId,+ CanonicalDigest, ControlRepositoryPort, PortErrorCode, ProtectedApplyCapability,+ RevisionSetV1, WorkspaceId,};#[test]@@ -404,15 +404,17 @@ mod startup_tests {"ApplyComputeConnection",accepted,revisions,- now + 301,+ // A stale now + 301 can enter the permitted 300-second window while the+ // preceding registration/verification runs. An unbounded expiry cannot.+ i64::MAX,).unwrap();- assert!(- stores- .apply_capability_registrar()- .register(too_long)- .is_err()- );+ let error = stores+ .apply_capability_registrar()+ .register(too_long)+ .unwrap_err();+ assert_eq!(error.code, PortErrorCode::PermissionDenied);+ assert_eq!(error.context, "control.capability.expiry");}#[test]diff --git a/docs/local-user-configuration.md b/docs/local-user-configuration.mdindex a5abbe36..3569b9bb 100644--- a/docs/local-user-configuration.md+++ b/docs/local-user-configuration.md@@ -14,3 +14,41 @@ This local trust decision does not authorize remote Agent collaboration, Gatewaypotentially billable model checks. Those flows keep their own consent and credential boundaries.The Desktop WebView can only use its explicitly exposed native commands and cannot supply anarbitrary Local Control request.++## Codex CLI profile++The default Codex connection owns one `hiroute.config.toml` profile in the detected original+`CODEX_HOME`. It preserves `config.toml` and the ordinary CLI/Desktop default provider.+Copy the launch command from the Agent page and select your shell. The command explicitly+sets the detected `CODEX_HOME` for that invocation because a newly opened terminal may have+another environment; it does not change `HOME` or your shell configuration.++One canonical `CODEX_HOME` supports one managed model connection: either this CLI profile+or the advanced default-configuration takeover. The advanced mode changes the default provider+for ordinary Codex and Desktop using that home. To switch, restore the current model settings,+finish any pending cleanup, and then configure the other mode. An existing unowned profile+or an inherited `model_providers.hiroute`/`profiles.hiroute` entry is a conflict; HiRoute does+not adopt files by name or remove their authentication fields. Preserve your own files and+resolve the conflicting entry manually before a fresh preview.++Profile mode uses native `codex --profile hiroute`; it does not provide a Desktop profile+launcher. History can differ between entry points. Cross-provider history restoration and+session database changes are outside this feature. Gateway credentials authorize the selected+models independently of the Codex client's OpenAI login; retaining original models still+requires a usable upstream source configured in HiRoute.++A pending operation reserves the home even if Gateway access is already revoked. The Agent+page shows the target and conflicting fields, and can recheck and resume the original Operation.+Save your edits before repairing the file. A file change after the operation was staged,+including formatting, must be undone before retry; after cleanup you can reapply unrelated+edits. HiRoute never force-overwrites a conflict. A newly created profile containing user-added+settings is retained after the managed fields are removed.++Same-user CLI callers can resume that same operation through `agents connect apply` with:++```json+{"schema":"hiroute.agent-settings-retry/v1","context_id":"<discovered context>","operation_id":"<pending Operation>"}+```++This retry accepts no new settings or grants. The daemon checks the stored operation and its+context before continuing. First-time creation and edits still require normal Preview/Apply.diff --git a/scripts/codex-profile-preflight.py b/scripts/codex-profile-preflight.pynew file mode 100644index 00000000..4551b4e1--- /dev/null+++ b/scripts/codex-profile-preflight.py@@ -0,0 +1,234 @@+#!/usr/bin/env python3+"""Opt-in real Codex acceptance using the production profile-creation entry.++Uses an explicitly supplied subscription through real HiRoute/CPA and a real Codex+CLI with no client login. All created configuration and services are disposable.+Requires consent to use the supplied subscription. Never prints credentials or+raw provider/client errors. A failure exits nonzero and leaves a bounded report.+"""+import argparse+import hashlib+import http.client+import json+import os+from pathlib import Path+import subprocess+import sys+import traceback+import urllib.parse++REPO = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO / 'crates/daemon/tests/support'))+from publication_product import Product # noqa: E402+from publication_process import prepare_subscription_source, apply_control # noqa: E402+from cpa_luna_gateway_live import ( # noqa: E402+ configure_isolated_codex, publish_luna_plan,+)+++def digest(path):+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def codex_completed(stdout, returncode):+ events = []+ for line in stdout.splitlines():+ try:+ event = json.loads(line)+ except ValueError:+ continue+ if isinstance(event, dict):+ events.append(event)+ return (returncode == 0+ and any(event.get('type') == 'turn.completed' for event in events)+ and not any(event.get('type') in ('turn.failed', 'error') for event in events)+ and any(event.get('type') == 'item.completed'+ and event.get('item', {}).get('type') == 'agent_message'+ and 'PROFILE_OK' in event['item'].get('text', '') for event in events))+++def safe_cpa_summary(product):+ """Read only our disposable CPA; emit no account IDs, tokens or response text."""+ summaries = []+ for config in product.root.rglob('config.yaml'):+ capability = config.parent / 'capability.private'+ if not capability.is_file():+ continue+ # The rendered managed config has a numeric top-level port. The config's+ # secret-key may already be hashed by CPA; use its private instance secret.+ port = next(int(line.split(':', 1)[1]) for line in config.read_text().splitlines()+ if line.startswith('port:'))+ secret = capability.read_text().splitlines()[1]+ client = http.client.HTTPConnection('127.0.0.1', port, timeout=5)+ def get(path):+ client.request('GET', path, headers={'Authorization': 'Bearer ' + secret})+ response = client.getresponse()+ return response.status, json.loads(response.read())+ try:+ status, listing = get('/v0/management/auth-files')+ accounts = []+ for account in listing.get('files', []):+ model_status, models = get('/v0/management/auth-files/models?name='+ + urllib.parse.quote(account['id'], safe=''))+ accounts.append({+ 'active': account.get('status') == 'active',+ 'disabled': account.get('disabled'),+ 'unavailable': account.get('unavailable'),+ 'retry_zero': account.get('request_retry') == 0,+ 'models_http': model_status,+ 'model_count': len(models.get('models', [])),+ })+ summaries.append({'management_http': status, 'accounts': accounts})+ finally:+ client.close()+ return summaries+++def save_source(product, model):+ candidate, validation = prepare_subscription_source(product)+ selected = next((item for item in candidate['models']+ if item.get('upstream_model_id') == model and item.get('selectable')), None)+ if selected is None:+ raise ValueError('requested_model_not_selectable')+ snapshot = product.control('ListCompute', {})['data']+ change = {+ 'schema': 'hiroute.compute-management-change/v2',+ 'subject': {'kind': 'candidate', 'candidate': candidate['candidate']},+ 'expected_revisions': snapshot['revisions'],+ 'selected_model_refs': [selected['model_ref']],+ 'intent': 'save_ready', 'key_edits': [], 'validation': validation,+ }+ preview = product.control('PreviewComputeSave', {'change': change})['data']+ applied = apply_control(product, 'ApplyComputeSave', preview, 'profile-preflight-source')+ saved = product.control('GetComputeSaveResult', {'operation': applied['operation']})['data']+ if saved['disposition'] != 'saved' or saved['management_state'] != 'ready':+ raise ValueError('source_not_ready')+ if len(saved['bindings']) != 1:+ raise ValueError('source_binding_ambiguous')+ return saved['bindings'][0]['binding_id']+++def run(args):+ source_digest = digest(args.auth_source)+ product = Product(REPO)+ product.bin = args.bin_dir.resolve()+ report = {+ 'schema': 'hiroute.codex-profile-preflight/v1',+ 'scenario': 'not_executed', 'phase': 'prepare',+ 'binary_sha256': digest(product.bin / 'hirouted'),+ 'codex_version': subprocess.check_output(+ [str(args.codex_cli), '--version'], text=True, timeout=10).strip(),+ 'cpa_sha256': digest(args.cpa_binary),+ 'checks': {}, 'limitations': [+ 'Real creation and no-login model request; edit/restore covered by daemon tests.',+ 'Source auth remains available; the client uses an empty ephemeral auth store.',+ 'Desktop and cross-provider history are not verified.',+ ],+ }+ try:+ configure_isolated_codex(product, args.auth_source, args.codex_cli)+ client_home = product.root / "client codex ' $home"+ original_home = product.codex_settings.parent+ original_home.rename(client_home)+ product.codex_settings = client_home / 'config.toml'+ product.env['CODEX_HOME'] = str(client_home)+ product.codex_access_mode = 'profile'+ product.enable_debug_diagnostics()+ product.cpa_args = ['--cpa-binary', str(args.cpa_binary),+ '--cpa-sha256', report['cpa_sha256']]+ product.startup_timeout = 90+ product.start()+ report['phase'] = 'subscription_check'+ binding = save_source(product, args.model)+ report['checks']['upstream_source_ready'] = True+ root = product.codex_settings+ baseline = root.read_bytes()+ report['phase'] = 'publication'+ product.native_model_checked_agents = {'agent_codex_default'}+ publish_luna_plan(product, binding)+ profile = client_home / 'hiroute.config.toml'+ if 'requires_openai_auth = false' not in profile.read_text():+ raise ValueError('profile_writer_shape_changed')+ env = dict(product.env, CODEX_HOME=str(client_home))+ # Borrowed upstream auth must remain valid: deleting it revokes the source too.+ # Codex's ephemeral auth backend reads an initially empty process-local map, not+ # auth.json/keyring. This test-only override separates client auth from source auth+ # while exercising the exact CODEX_HOME and profile created by production Apply.+ client_prefix = [str(args.codex_cli), '-c', 'cli_auth_credentials_store="ephemeral"']+ login = subprocess.run([*client_prefix, 'login', 'status'], env=env,+ cwd=product.project, stdin=subprocess.DEVNULL, capture_output=True, timeout=15)+ report['checks']['client_not_logged_in'] = (+ login.returncode == 1 and b'Not logged in' in login.stderr)+ if not report['checks']['client_not_logged_in']:+ raise ValueError('client_auth_not_empty')+ report['client_auth_store'] = 'ephemeral'+ report['phase'] = 'real_codex_request'+ completed = subprocess.run([+ *client_prefix, '--profile', 'hiroute', 'exec', '--skip-git-repo-check',+ '--ephemeral', '--json', '--sandbox', 'read-only',+ 'Reply with PROFILE_OK only. Do not use tools.',+ ], env=env, cwd=product.project, stdin=subprocess.DEVNULL,+ capture_output=True, timeout=150)+ # Do not preserve raw stdout/stderr: provider diagnostics can contain secrets.+ report['client_exit'] = completed.returncode+ report['checks'].update(+ client_completed=codex_completed(completed.stdout, completed.returncode),+ root_unchanged=root.read_bytes() == baseline,+ upstream_auth_copy_unchanged=digest(client_home / 'auth.json') == source_digest)+ report['scenario'] = 'green' if all(report['checks'].values()) else 'red'+ report['phase'] = 'complete'+ except Exception as error:+ report.update(scenario='red', error_type=type(error).__name__)+ # Retain bounded code locations, never exception messages or source lines: assertions+ # in the shared harness can carry complete control responses and protected material.+ detail = error.args[0] if error.args else None+ if isinstance(detail, tuple) and len(detail) == 2:+ detail = detail[1]+ if isinstance(detail, dict) and isinstance(detail.get('error'), dict):+ code = detail['error'].get('code')+ if code in {'INVALID_ARGUMENTS', 'CHANGE_PREVIEW_STALE', 'CAPABILITY_DENIED',+ 'RESOURCE_NOT_FOUND', 'DAEMON_UNAVAILABLE', 'INTERNAL_ERROR'}:+ report['control_error_code'] = code+ report['error_locations'] = [+ {'file': Path(frame.filename).name, 'function': frame.name, 'line': frame.lineno}+ for frame in traceback.extract_tb(error.__traceback__)[-5:]+ ]+ try:+ report['cpa'] = safe_cpa_summary(product)+ except Exception as diagnostic_error:+ report['diagnostic_error_type'] = type(diagnostic_error).__name__+ finally:+ try:+ report['diagnostics'] = product.preserve_diagnostics(args.output / 'diagnostics')+ except Exception as error:+ report['diagnostic_error_type'] = type(error).__name__+ try:+ product.close()+ except Exception as error:+ report.update(scenario='red', cleanup_error_type=type(error).__name__)+ report['checks']['original_auth_unchanged'] = digest(args.auth_source) == source_digest+ if not report['checks']['original_auth_unchanged']:+ report['scenario'] = 'red'+ (args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n')+ print(json.dumps(report, ensure_ascii=False))+ return 0 if report['scenario'] == 'green' else 1+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--bin-dir', type=Path, required=True)+ parser.add_argument('--codex-cli', type=Path, required=True)+ parser.add_argument('--cpa-binary', type=Path, required=True)+ parser.add_argument('--auth-source', type=Path, required=True)+ parser.add_argument('--model', default='gpt-5.6-luna')+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ for key in ('bin_dir', 'codex_cli', 'cpa_binary', 'auth_source', 'output'):+ setattr(args, key, getattr(args, key).resolve())+ # Refuse to overwrite prior evidence, especially a prior failed gate.+ args.output.mkdir(mode=0o700, parents=True, exist_ok=False)+ return run(args)+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/stage-desktop-cpa.py b/scripts/stage-desktop-cpa.pyindex 87b12e5a..6ee8f0f2 100755--- a/scripts/stage-desktop-cpa.py+++ b/scripts/stage-desktop-cpa.py@@ -37,12 +37,12 @@ def fail(code: str) -> None:raise StageError(code)-def read_manifest() -> dict[str, Any]:+def read_manifest(path: Path = MANIFEST) -> dict[str, Any]:try:- manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))+ manifest = json.loads(path.read_text(encoding="utf-8"))except (OSError, ValueError):fail("DEVELOPMENT_CPA_MANIFEST_INVALID")- if manifest.get("schema") != SCHEMA or manifest.get("development_only") is not True:+ if manifest.get("schema") != SCHEMA or not isinstance(manifest.get("development_only"), bool):fail("DEVELOPMENT_CPA_MANIFEST_INVALID")return manifest@@ -69,6 +69,9 @@ def selected_artifact(manifest: dict[str, Any]) -> dict[str, Any]:fail("DEVELOPMENT_CPA_MANIFEST_INVALID")if artifact["binary_name"] != "cliproxyapi" or not re.fullmatch(r"[0-9a-f]{64}", artifact["sha256"]):fail("DEVELOPMENT_CPA_MANIFEST_INVALID")+ current = json.loads((MANIFEST.parents[3] / "vendor/cpa/source.json").read_text())+ if artifact["version"] != current["version"] or artifact["commit"] != current["commit"]:+ fail("DEVELOPMENT_CPA_PIN_STALE: generate a current CPA manifest with package-desktop.py; pass --manifest and build with the same HIROUTE_CPA_MANIFEST")return artifact@@ -163,8 +166,8 @@ def copy_and_measure(source: Path, destination_dir: Path, artifact: dict[str, Anraise-def stage(source: Path, hirouted: Path) -> dict[str, Any]:- artifact = selected_artifact(read_manifest())+def stage(source: Path, hirouted: Path, manifest: Path = MANIFEST) -> dict[str, Any]:+ artifact = selected_artifact(read_manifest(manifest))source_stat = regular_owned_file(source, "DEVELOPMENT_CPA_SOURCE_UNTRUSTED")if source_stat.st_mode & 0o022:fail("DEVELOPMENT_CPA_SOURCE_UNTRUSTED")@@ -204,9 +207,10 @@ def main() -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--cpa", required=True, type=Path, help="explicit path to the pinned CPA artifact")parser.add_argument("--hirouted", required=True, type=Path, help="already-built hirouted that will own the adjacent CPA")+ parser.add_argument("--manifest", type=Path, default=MANIFEST, help="manifest also selected by HIROUTE_CPA_MANIFEST when building Desktop")arguments = parser.parse_args()try:- result = stage(arguments.cpa.expanduser(), arguments.hirouted.expanduser())+ result = stage(arguments.cpa.expanduser(), arguments.hirouted.expanduser(), arguments.manifest.expanduser())except StageError as error:print(json.dumps({"status": "error", "code": str(error)}, sort_keys=True), file=sys.stderr)return 1diff --git a/scripts/test-codex-profile-preflight.py b/scripts/test-codex-profile-preflight.pynew file mode 100644index 00000000..495b778a--- /dev/null+++ b/scripts/test-codex-profile-preflight.py@@ -0,0 +1,46 @@+#!/usr/bin/env python3+"""Harness outcome checks; these do not establish product/client success."""+import importlib.util+import json+from pathlib import Path+import unittest++spec = importlib.util.spec_from_file_location(+ 'preflight', Path(__file__).with_name('codex-profile-preflight.py'))+preflight = importlib.util.module_from_spec(spec)+spec.loader.exec_module(preflight)+++def stream(*events):+ return b'\n'.join(json.dumps(event).encode() for event in events)+++ANSWER = {'type': 'item.completed', 'item': {'type': 'agent_message', 'text': 'PROFILE_OK'}}+COMPLETE = {'type': 'turn.completed'}+++class OutcomeTests(unittest.TestCase):+ def test_exit_zero_or_partial_answer_is_not_success(self):+ for output in (b'', b'not json', stream(ANSWER), stream(COMPLETE)):+ with self.subTest(output=output):+ self.assertFalse(preflight.codex_completed(output, 0))++ def test_error_after_answer_does_not_pass(self):+ for event in ({'type': 'turn.failed'}, {'type': 'error'}):+ self.assertFalse(preflight.codex_completed(stream(ANSWER, COMPLETE, event), 0))++ def test_completed_real_client_event_shape(self):+ self.assertTrue(preflight.codex_completed(stream(+ {'type': 'thread.started', 'thread_id': 'test'}, ANSWER, COMPLETE), 0))++ def test_nonzero_exit_does_not_pass_even_with_success_events(self):+ self.assertFalse(preflight.codex_completed(stream(ANSWER, COMPLETE), 1))++ def test_tool_output_cannot_impersonate_an_answer(self):+ self.assertFalse(preflight.codex_completed(stream(+ {'type': 'item.completed', 'item': {'type': 'command_execution',+ 'text': 'PROFILE_OK'}}, COMPLETE), 0))+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test-package-desktop.py b/scripts/test-package-desktop.pyindex fcc124ac..53bc608f 100644--- a/scripts/test-package-desktop.py+++ b/scripts/test-package-desktop.py@@ -75,7 +75,7 @@ class BundleIdentityTests(unittest.TestCase):def test_cpa_is_explicitly_signed_before_release_probe(self):events = []- release = ("CLIProxyAPI Version: 8.0.4-hiroute.1, Commit: "+ release = ("CLIProxyAPI Version: 8.0.4-hiroute.2, Commit: ""a270e7b9e57aaecd8f82555f44c2108518ad2330, ""BuiltAt: 2026-09-29T00:00:00Z")with patch.object(package, "sign", side_effect=lambda *_: events.append("sign")), \diff --git a/scripts/test-stage-desktop-cpa.py b/scripts/test-stage-desktop-cpa.pynew file mode 100644index 00000000..ebc7b982--- /dev/null+++ b/scripts/test-stage-desktop-cpa.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""Pin checks run without invoking native macOS tooling or copying an artifact."""+import copy+import importlib.util+import json+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('stage', Path(__file__).with_name('stage-desktop-cpa.py'))+stage = importlib.util.module_from_spec(spec)+spec.loader.exec_module(stage)+++class Pins(unittest.TestCase):+ def setUp(self):+ self.manifest = stage.read_manifest()+ self.source = json.loads((stage.MANIFEST.parents[3] / 'vendor/cpa/source.json').read_text())++ def test_historical_pin_rejected_before_file_access(self):+ with patch.object(stage, 'host_identity', return_value=('macos', 'aarch64')):+ with self.assertRaisesRegex(stage.StageError, 'DEVELOPMENT_CPA_PIN_STALE'):+ stage.stage(Path('/missing/source'), Path('/missing/daemon'))++ def test_current_generated_manifest_can_be_selected(self):+ current = copy.deepcopy(self.manifest)+ current['development_only'] = False+ current['artifacts'][0].update(version=self.source['version'], commit=self.source['commit'])+ with tempfile.TemporaryDirectory() as temp:+ path = Path(temp) / 'cpa-artifacts.json'+ path.write_text(json.dumps(current))+ with patch.object(stage, 'host_identity', return_value=('macos', 'aarch64')):+ self.assertEqual(stage.selected_artifact(stage.read_manifest(path))['version'], self.source['version'])++ def test_wrong_source_commit_rejected_even_with_current_version(self):+ self.manifest['artifacts'][0]['version'] = self.source['version']+ self.manifest['artifacts'][0]['commit'] = '0' * 40+ with patch.object(stage, 'host_identity', return_value=('macos', 'aarch64')):+ with self.assertRaisesRegex(stage.StageError, 'DEVELOPMENT_CPA_PIN_STALE'):+ stage.selected_artifact(self.manifest)++ def test_product_cpa_fixtures_match_runtime_pin(self):+ root = stage.MANIFEST.parents[3]+ for path in ['crates/daemon/tests/support/cpa_upstream.py',+ 'crates/daemon/tests/support/standalone_headless_product.py',+ 'crates/daemon/tests/subscription_management_product.rs',+ 'crates/cpa-bridge/src/lib.rs']:+ with self.subTest(path=path):+ self.assertIn(self.source['version'], (root / path).read_text())+++if __name__ == '__main__':+ unittest.main()diff --git a/tools/product-e2e/src/smoke/control.rs b/tools/product-e2e/src/smoke/control.rsindex 2866546e..dc76747f 100644--- a/tools/product-e2e/src/smoke/control.rs+++ b/tools/product-e2e/src/smoke/control.rs@@ -107,10 +107,13 @@ fn observe_cli(&& envelope.request_id.as_deref() == Some(&format!("{}-{id}", ctx.run_id)),"machine_identity_mismatch",)?;- let encoded = String::from_utf8_lossy(&stdout);require(- (secret.is_empty() || !encoded.contains(secret))- && !encoded.contains(ctx.runtime.to_string_lossy().as_ref()),+ response_is_private(+ &serde_json::from_slice::<Value>(&stdout)?,+ &ctx.runtime,+ secret,+ matches!(args, ["agents", "scan"] | ["agents", "list"]),+ ),"privacy_failure",)?;ctx.verify_artifact(artifact)?;@@ -458,3 +461,115 @@ pub(super) fn embedded_catalog(ctx: &mut Context<'_>) -> Result<()> {)?;ctx.verify_artifact(&daemon)}++// Only the owner-local connection controls may disclose their exact target.+// Check secrets before removing these fields from the path-leak check.+fn response_is_private(value: &Value, runtime: &Path, secret: &str, discovery: bool) -> bool {+ if !secret.is_empty() && value.to_string().contains(secret) {+ return false;+ }+ let mut redacted = value.clone();+ if discovery {+ let Some(agents) = redacted["data"]["agents"].as_array_mut() else {+ return false;+ };+ let Some(agent) = agents+ .iter_mut()+ .find(|a| a["agent_id"] == "agent_codex_default")+ else {+ return false;+ };+ let Some(access) = agent["codex_access"].as_object_mut() else {+ return false;+ };+ let home = runtime.join("agent-home/.codex");+ if access.remove("codex_home") != Some(json!(home))+ || access.remove("target_file") != Some(json!(home.join("hiroute.config.toml")))+ {+ return false;+ }+ let Some(Value::Object(commands)) = access.remove("commands") else {+ return false;+ };+ if commands.len() != 3+ || !["bash/zsh", "fish", "PowerShell"].iter().all(|shell| {+ commands+ .get(*shell)+ .and_then(Value::as_str)+ .is_some_and(|command| {+ command.contains(home.to_string_lossy().as_ref())+ && command.contains("codex --profile hiroute")+ })+ })+ {+ return false;+ }+ }+ !redacted+ .to_string()+ .contains(runtime.to_string_lossy().as_ref())+}++#[cfg(test)]+mod privacy_tests {+ use super::*;++ #[test]+ fn only_connection_controls_allow_exact_paths_and_never_credentials() {+ let runtime = Path::new("/private/smoke");+ let home = runtime.join("agent-home/.codex");+ let command = format!("CODEX_HOME={} codex --profile hiroute", home.display());+ let value = json!({"data":{"agents":[{"agent_id":"agent_codex_default","codex_access":{+ "codex_home":home,"target_file":home.join("hiroute.config.toml"),+ "commands":{"bash/zsh":command,"fish":command,"PowerShell":command}+ }}]}});+ assert!(response_is_private(+ &value,+ runtime,+ "sentinel-secret",+ true+ ));+ assert!(!response_is_private(+ &value,+ runtime,+ "sentinel-secret",+ false+ ));+ let mut unrelated = value.clone();+ unrelated["extra"] = json!(home);+ let raw = serde_json::to_vec(&unrelated).unwrap();+ let unrelated = serde_json::from_slice::<Value>(&raw).unwrap();+ assert!(!response_is_private(+ &unrelated,+ runtime,+ "sentinel-secret",+ true+ ));+ let mut unknown = value.clone();+ unknown["extra"] = json!("sentinel-secret");+ let raw = serde_json::to_vec(&unknown).unwrap();+ assert!(!response_is_private(+ &serde_json::from_slice::<Value>(&raw).unwrap(),+ runtime,+ "sentinel-secret",+ true+ ));+ let mut secret = value.clone();+ secret["data"]["agents"][0]["codex_access"]["commands"]["fish"] =+ json!(format!("{command} sentinel-secret"));+ assert!(!response_is_private(+ &secret,+ runtime,+ "sentinel-secret",+ true+ ));+ let mut wrong_target = value.clone();+ wrong_target["data"]["agents"][0]["codex_access"]["target_file"] = json!(home);+ assert!(!response_is_private(+ &wrong_target,+ runtime,+ "sentinel-secret",+ true+ ));+ }+}diff --git a/tools/product-e2e/tests/control_shell.rs b/tools/product-e2e/tests/control_shell.rsindex 4b944882..108269fb 100644--- a/tools/product-e2e/tests/control_shell.rs+++ b/tools/product-e2e/tests/control_shell.rs@@ -193,9 +193,35 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {claude["discovered_credential"]["field_selector"],"env.ANTHROPIC_AUTH_TOKEN");- let encoded = internal.to_string();- assert!(!encoded.contains(secret_sentinel));- assert!(!encoded.contains(agent_home.to_string_lossy().as_ref()));+ assert!(!internal.to_string().contains(secret_sentinel));+ // Owner-only connection controls intentionally expose the exact directory+ // used by copied commands. No other discovery field may expose paths.+ let mut redacted = internal.clone();+ let agents = redacted["data"]["agents"].as_array_mut().unwrap();+ let codex = agents+ .iter_mut()+ .find(|agent| agent["agent_id"] == "agent_codex_default")+ .unwrap();+ let access = codex["codex_access"].as_object_mut().unwrap();+ let home = agent_home.join(".codex");+ assert_eq!(access.remove("codex_home").unwrap(), json!(home));+ assert_eq!(+ access.remove("target_file").unwrap(),+ json!(home.join("hiroute.config.toml"))+ );+ let commands = access.remove("commands").unwrap();+ let commands = commands.as_object().unwrap();+ assert_eq!(commands.len(), 3);+ for shell in ["bash/zsh", "fish", "PowerShell"] {+ let command = commands[shell].as_str().unwrap();+ assert!(command.contains(home.to_str().unwrap()));+ assert!(command.contains("codex --profile hiroute"));+ }+ assert!(+ !redacted+ .to_string()+ .contains(agent_home.to_string_lossy().as_ref())+ );}for (command_id, arguments) in [diff --git a/vendor/cpa/README.md b/vendor/cpa/README.mdindex 8fe5fe12..00e3ffe7 100644--- a/vendor/cpa/README.md+++ b/vendor/cpa/README.md@@ -33,3 +33,33 @@ Focused upstream tests are shipped in the patch:go test ./sdk/cliproxy ./internal/runtime/executor ./cmd/server ./internal/api/handlers/management \-run 'TestCodexDiscovery|TestCodexModelDiscovery|TestRegisterModelsForAuth|TestLocalManagementPasswordPipeBounds|TestLocalMachinePasswordPreservesRemotePolicy'```++Managed children allowlist HTTP(S)_PROXY and NO_PROXY (both cases). The local+patch applies Go's standard per-destination environment proxy selection to+protected-host TLS transports when no explicit proxy/injected transport exists.+It preserves NO_PROXY and does not retry direct after proxy failure. ALL_PROXY+is not part of this contract; configure HTTPS_PROXY for subscription endpoints.++## Current macOS development artifacts++The checked-in `development-cpa-artifacts.v1.json` identifies a historical+`.1` binary; its hash is retained as measured, not relabeled as the current+`.2` build. Do not stage that old binary with the current daemon.++On macOS, `python3 scripts/package-desktop.py build --cpa-source-repo /absolute/CPA-checkout`+generates the current patched CPA and a measured `cpa-artifacts.json` in its+candidate output directory. For a Debug Desktop build, set+`HIROUTE_CPA_MANIFEST=/absolute/candidate-output/cpa-artifacts.json` and use that+same output's `HiRoute.app/Contents/MacOS/cliproxyapi` beside the Debug `hirouted`:++```sh+python3 scripts/stage-desktop-cpa.py \+ --manifest /absolute/candidate-output/cpa-artifacts.json \+ --cpa /absolute/candidate-output/HiRoute.app/Contents/MacOS/cliproxyapi \+ --hirouted /absolute/checkout/target/debug/hirouted+```++Use the default ad-hoc package identity for this development staging path.+The staging tool rejects stale versions before copying; it still verifies the+exact digest, architecture, signature, dependencies and version of the binary.+A Linux backend test does not validate this native macOS build/install path.diff --git a/vendor/cpa/local-management-stdin.patch b/vendor/cpa/local-management-stdin.patchindex 746c1adf..521a086b 100644--- a/vendor/cpa/local-management-stdin.patch+++ b/vendor/cpa/local-management-stdin.patch@@ -405,3 +405,143 @@+ t.Fatal("cross-account catalog leakage")+ }+}+--- a/internal/runtime/executor/helps/utls_client.go++++ b/internal/runtime/executor/helps/utls_client.go+@@ -385,6 +385,9 @@+ chromeRT = ctxRoundTripper+ anthropicRT = ctxRoundTripper+ standardTransport = ctxRoundTripper++ } else {++ chromeRT = &environmentProxyTransport{direct: chromeRT, build: func(proxy string) http.RoundTripper { return newUtlsRoundTripper(proxy) }, proxy: http.ProxyFromEnvironment}++ anthropicRT = &environmentProxyTransport{direct: anthropicRT, build: cachedClaudeCodeRoundTripper, proxy: http.ProxyFromEnvironment}+ }++ client := &http.Client{+--- /dev/null++++ b/internal/runtime/executor/helps/environment_proxy.go+@@ -0,0 +1,31 @@++package helps++++import (++ "errors"++ "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil"++ "net/http"++ "net/url"++)++++// Preserve provider TLS fingerprints while applying the standard environment++// proxy and NO_PROXY rules to the actual destination. Selection errors fail closed.++type environmentProxyTransport struct {++ direct http.RoundTripper++ build func(string) http.RoundTripper++ proxy func(*http.Request) (*url.URL, error)++}++++func (t *environmentProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {++ proxy, err := t.proxy(req)++ if err != nil {++ return nil, err++ }++ if proxy == nil {++ return t.direct.RoundTrip(req)++ }++ // CPA's transport constructor otherwise falls back to direct on invalid input.++ if !proxyutil.ValidRequestProxy(proxy.String()) {++ return nil, errors.New("invalid environment proxy")++ }++ return t.build(proxy.String()).RoundTrip(req)++}+--- /dev/null++++ b/internal/runtime/executor/helps/environment_proxy_test.go+@@ -0,0 +1,91 @@++package helps++++import (++ "context"++ "errors"++ "net/http"++ "net/url"++ "os"++ "os/exec"++ "testing"++)++++type environmentTestRT func(*http.Request) (*http.Response, error)++++func (f environmentTestRT) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++++func TestEnvironmentProxySelection(t *testing.T) {++ if os.Getenv("HIROUTE_PROXY_TEST_CHILD") == "1" {++ c := NewUtlsHTTPClient(context.Background(), nil, nil, 0)++ rt, ok := c.Transport.(*fallbackRoundTripper).chrome.(*environmentProxyTransport)++ if !ok {++ t.Fatal("protected transport ignores environment")++ }++ req, _ := http.NewRequest("GET", "https://chatgpt.com/backend-api/codex/models", nil)++ p, err := rt.proxy(req)++ if err != nil {++ t.Fatal(err)++ }++ want := os.Getenv("HIROUTE_EXPECT_PROXY")++ if want == "" {++ if p != nil {++ t.Fatal("NO_PROXY bypass lost")++ }++ } else if p == nil || p.String() != want {++ t.Fatal("HTTPS proxy lost")++ }++ return++ }++ for _, bypass := range []bool{false, true} {++ cmd := exec.Command(os.Args[0], "-test.run=^TestEnvironmentProxySelection$")++ cmd.Env = []string{"HIROUTE_PROXY_TEST_CHILD=1", "HTTPS_PROXY=http://127.0.0.1:1187"}++ if bypass {++ cmd.Env = append(cmd.Env, "NO_PROXY=chatgpt.com")++ } else {++ cmd.Env = append(cmd.Env, "HIROUTE_EXPECT_PROXY=http://127.0.0.1:1187")++ }++ if out, err := cmd.CombinedOutput(); err != nil {++ t.Fatalf("child: %v %s", err, out)++ }++ }++}++++func TestEnvironmentProxyTransportNeverFallsBackOnError(t *testing.T) {++ req, _ := http.NewRequest("GET", "https://chatgpt.com/", nil)++ sentinel := errors.New("proxy failure")++ directCalls := 0++ rt := &environmentProxyTransport{++ direct: environmentTestRT(func(*http.Request) (*http.Response, error) {++ directCalls++++ return &http.Response{StatusCode: 200}, nil++ }),++ proxy: func(*http.Request) (*url.URL, error) { return url.Parse("http://127.0.0.1:1187") },++ build: func(s string) http.RoundTripper {++ return environmentTestRT(func(*http.Request) (*http.Response, error) { return nil, sentinel })++ },++ }++ if _, err := rt.RoundTrip(req); err != sentinel || directCalls != 0 {++ t.Fatal("proxy failure fell back to direct")++ }++ rt.proxy = func(*http.Request) (*url.URL, error) { return nil, sentinel }++ if _, err := rt.RoundTrip(req); err != sentinel || directCalls != 0 {++ t.Fatal("selection failure fell back to direct")++ }++ rt.proxy = func(*http.Request) (*url.URL, error) { return nil, nil }++ if _, err := rt.RoundTrip(req); err != nil || directCalls != 1 {++ t.Fatal("direct bypass broken")++ }++}++++func TestInvalidEnvironmentProxyFailsBeforeTransportConstruction(t *testing.T) {++ req, _ := http.NewRequest("GET", "https://chatgpt.com/", nil)++ for _, raw := range []string{"ftp://127.0.0.1:1187", "http://127.0.0.1:0", "http://127.0.0.1:99999"} {++ rt := &environmentProxyTransport{++ proxy: func(*http.Request) (*url.URL, error) { return url.Parse(raw) },++ build: func(string) http.RoundTripper { t.Fatal("invalid proxy reached constructor"); return nil },++ }++ if _, err := rt.RoundTrip(req); err == nil {++ t.Fatal("invalid proxy accepted")++ }++ }++}diff --git a/vendor/cpa/source.json b/vendor/cpa/source.jsonindex 0bd3d80e..3561043c 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.1",+ "version": "8.0.4-hiroute.2","built_at": "2026-09-29T00:00:00Z","patch": "local-management-stdin.patch",- "patch_sha256": "c04588a9606700810b192520712536437c44dcbf4d7cc4c5ef762dd76da23877"+ "patch_sha256": "db4fdf029ae78f50d31f7a06d3d83bec03bfbad3c4da74cd86c9730561708d3c"}