mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Merge remote-tracking branch 'origin/main' into codex/guardian-timeout-manual-fallback
# Conflicts: # codex-rs/core/tests/common/test_codex.rs
This commit is contained in:
Generated
+70
-33
@@ -213,7 +213,7 @@ dependencies = [
|
||||
"lazy_static",
|
||||
"nom 7.1.3",
|
||||
"pin-project",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"rust-embed",
|
||||
"scrypt",
|
||||
"sha2 0.10.9",
|
||||
@@ -234,7 +234,7 @@ dependencies = [
|
||||
"hkdf 0.12.4",
|
||||
"io_tee",
|
||||
"nom 7.1.3",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"secrecy",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
@@ -786,7 +786,7 @@ dependencies = [
|
||||
"hex",
|
||||
"http 1.4.0",
|
||||
"p256",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"ring",
|
||||
"sha2 0.10.9",
|
||||
"time",
|
||||
@@ -1852,7 +1852,6 @@ dependencies = [
|
||||
name = "codex-agent-graph-store"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"codex-protocol",
|
||||
"codex-state",
|
||||
"pretty_assertions",
|
||||
@@ -1919,7 +1918,6 @@ dependencies = [
|
||||
"anyhow",
|
||||
"assert_matches",
|
||||
"async-channel",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
@@ -1953,7 +1951,6 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"app_test_support",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -1979,6 +1976,7 @@ dependencies = [
|
||||
"codex-git-utils",
|
||||
"codex-goal-extension",
|
||||
"codex-guardian",
|
||||
"codex-home",
|
||||
"codex-hooks",
|
||||
"codex-image-generation-extension",
|
||||
"codex-login",
|
||||
@@ -2004,6 +2002,7 @@ dependencies = [
|
||||
"codex-utils-cargo-bin",
|
||||
"codex-utils-cli",
|
||||
"codex-utils-json-to-toml",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-pty",
|
||||
"codex-web-search-extension",
|
||||
"codex-windows-sandbox",
|
||||
@@ -2183,6 +2182,7 @@ dependencies = [
|
||||
"codex-exec-server",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-cargo-bin",
|
||||
"codex-utils-path-uri",
|
||||
"pretty_assertions",
|
||||
"similar",
|
||||
"tempfile",
|
||||
@@ -2215,7 +2215,6 @@ dependencies = [
|
||||
name = "codex-async-utils"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"pretty_assertions",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
@@ -2319,6 +2318,7 @@ dependencies = [
|
||||
"codex-execpolicy",
|
||||
"codex-features",
|
||||
"codex-git-utils",
|
||||
"codex-home",
|
||||
"codex-install-context",
|
||||
"codex-login",
|
||||
"codex-mcp",
|
||||
@@ -2372,7 +2372,6 @@ dependencies = [
|
||||
name = "codex-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"codex-utils-cargo-bin",
|
||||
"codex-utils-rustls-provider",
|
||||
@@ -2427,7 +2426,6 @@ name = "codex-cloud-tasks"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"clap",
|
||||
"codex-client",
|
||||
@@ -2459,7 +2457,6 @@ name = "codex-cloud-tasks-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"codex-api",
|
||||
"codex-backend-client",
|
||||
@@ -2473,7 +2470,6 @@ dependencies = [
|
||||
name = "codex-cloud-tasks-mock-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"codex-cloud-tasks-client",
|
||||
"diffy",
|
||||
@@ -2483,10 +2479,10 @@ dependencies = [
|
||||
name = "codex-code-mode"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-code-mode-protocol",
|
||||
"codex-protocol",
|
||||
"deno_core_icudata",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
@@ -2494,6 +2490,22 @@ dependencies = [
|
||||
"v8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-code-mode-host"
|
||||
version = "0.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "codex-code-mode-protocol"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-protocol",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-collaboration-mode-templates"
|
||||
version = "0.0.0"
|
||||
@@ -2503,7 +2515,6 @@ name = "codex-config"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"codex-app-server-protocol",
|
||||
"codex-execpolicy",
|
||||
@@ -2515,6 +2526,7 @@ dependencies = [
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path",
|
||||
"codex-utils-path-uri",
|
||||
"core-foundation 0.9.4",
|
||||
"dns-lookup",
|
||||
"dunce",
|
||||
@@ -2579,7 +2591,6 @@ dependencies = [
|
||||
"assert_cmd",
|
||||
"assert_matches",
|
||||
"async-channel",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bm25",
|
||||
"chrono",
|
||||
@@ -2601,6 +2612,7 @@ dependencies = [
|
||||
"codex-features",
|
||||
"codex-feedback",
|
||||
"codex-git-utils",
|
||||
"codex-home",
|
||||
"codex-hooks",
|
||||
"codex-image-generation-extension",
|
||||
"codex-install-context",
|
||||
@@ -2634,6 +2646,7 @@ dependencies = [
|
||||
"codex-utils-image",
|
||||
"codex-utils-output-truncation",
|
||||
"codex-utils-path",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-plugins",
|
||||
"codex-utils-pty",
|
||||
"codex-utils-stream-parser",
|
||||
@@ -2704,6 +2717,7 @@ dependencies = [
|
||||
"codex-exec-server",
|
||||
"codex-extension-api",
|
||||
"codex-features",
|
||||
"codex-home",
|
||||
"codex-login",
|
||||
"codex-model-provider-info",
|
||||
"codex-models-manager",
|
||||
@@ -2725,11 +2739,13 @@ dependencies = [
|
||||
"codex-git-utils",
|
||||
"codex-hooks",
|
||||
"codex-login",
|
||||
"codex-mcp",
|
||||
"codex-model-provider",
|
||||
"codex-otel",
|
||||
"codex-plugin",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-plugins",
|
||||
"dirs",
|
||||
"flate2",
|
||||
@@ -2768,6 +2784,7 @@ dependencies = [
|
||||
"codex-skills",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-output-truncation",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-plugins",
|
||||
"dirs",
|
||||
"dunce",
|
||||
@@ -2835,7 +2852,6 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
@@ -2848,6 +2864,7 @@ dependencies = [
|
||||
"codex-shell-command",
|
||||
"codex-test-binary-support",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-pty",
|
||||
"codex-utils-rustls-provider",
|
||||
"ctor 0.6.3",
|
||||
@@ -2925,6 +2942,7 @@ dependencies = [
|
||||
"codex-context-fragments",
|
||||
"codex-protocol",
|
||||
"codex-tools",
|
||||
"codex-utils-absolute-path",
|
||||
"pretty_assertions",
|
||||
"tokio",
|
||||
]
|
||||
@@ -3001,9 +3019,9 @@ dependencies = [
|
||||
name = "codex-file-system"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -3027,6 +3045,7 @@ dependencies = [
|
||||
"codex-file-system",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"futures",
|
||||
"gix",
|
||||
"once_cell",
|
||||
@@ -3073,6 +3092,17 @@ dependencies = [
|
||||
"codex-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-home"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-extension-api",
|
||||
"codex-utils-absolute-path",
|
||||
"pretty_assertions",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-hooks"
|
||||
version = "0.0.0"
|
||||
@@ -3110,11 +3140,13 @@ dependencies = [
|
||||
"codex-tools",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-image",
|
||||
"codex-utils-path-uri",
|
||||
"http 1.4.0",
|
||||
"pretty_assertions",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3178,7 +3210,6 @@ name = "codex-login"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"codex-agent-identity",
|
||||
@@ -3220,6 +3251,7 @@ name = "codex-mcp"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arc-swap",
|
||||
"async-channel",
|
||||
"codex-api",
|
||||
"codex-async-utils",
|
||||
@@ -3273,6 +3305,7 @@ dependencies = [
|
||||
"codex-core",
|
||||
"codex-exec-server",
|
||||
"codex-extension-api",
|
||||
"codex-home",
|
||||
"codex-login",
|
||||
"codex-protocol",
|
||||
"codex-shell-command",
|
||||
@@ -3381,7 +3414,6 @@ dependencies = [
|
||||
name = "codex-model-provider"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"codex-agent-identity",
|
||||
"codex-api",
|
||||
"codex-aws-auth",
|
||||
@@ -3422,7 +3454,6 @@ dependencies = [
|
||||
name = "codex-models-manager"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"codex-app-server-protocol",
|
||||
"codex-collaboration-mode-templates",
|
||||
@@ -3444,7 +3475,6 @@ name = "codex-network-proxy"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"clap",
|
||||
@@ -3530,8 +3560,10 @@ name = "codex-plugin"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-config",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-plugins",
|
||||
"pretty_assertions",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
@@ -3679,7 +3711,6 @@ name = "codex-rollout"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"codex-file-search",
|
||||
"codex-git-utils",
|
||||
@@ -3721,7 +3752,6 @@ name = "codex-sandboxing"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"codex-network-proxy",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
@@ -3784,7 +3814,6 @@ name = "codex-shell-escalation"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"clap",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
@@ -3813,16 +3842,22 @@ dependencies = [
|
||||
name = "codex-skills-extension"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"codex-core",
|
||||
"codex-core-skills",
|
||||
"codex-exec-server",
|
||||
"codex-extension-api",
|
||||
"codex-mcp",
|
||||
"codex-protocol",
|
||||
"codex-tools",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-string",
|
||||
"pretty_assertions",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3891,7 +3926,6 @@ dependencies = [
|
||||
name = "codex-thread-store"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"codex-git-utils",
|
||||
"codex-install-context",
|
||||
@@ -3916,6 +3950,7 @@ dependencies = [
|
||||
"codex-app-server-protocol",
|
||||
"codex-code-mode",
|
||||
"codex-features",
|
||||
"codex-file-system",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-cargo-bin",
|
||||
@@ -4196,6 +4231,7 @@ dependencies = [
|
||||
"codex-exec-server",
|
||||
"codex-login",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4223,7 +4259,6 @@ name = "codex-utils-readiness"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"assert_matches",
|
||||
"async-trait",
|
||||
"thiserror 2.0.18",
|
||||
"time",
|
||||
"tokio",
|
||||
@@ -4324,7 +4359,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"glob",
|
||||
"pretty_assertions",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@@ -4578,6 +4613,7 @@ dependencies = [
|
||||
"codex-exec-server",
|
||||
"codex-extension-api",
|
||||
"codex-features",
|
||||
"codex-home",
|
||||
"codex-hooks",
|
||||
"codex-login",
|
||||
"codex-model-provider-info",
|
||||
@@ -4585,6 +4621,7 @@ dependencies = [
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-cargo-bin",
|
||||
"codex-utils-path-uri",
|
||||
"ctor 0.6.3",
|
||||
"futures",
|
||||
"notify",
|
||||
@@ -9431,7 +9468,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"getrandom 0.2.17",
|
||||
"http 1.4.0",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -11070,9 +11107,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.5"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha 0.3.1",
|
||||
@@ -11938,7 +11975,7 @@ dependencies = [
|
||||
"hkdf 0.12.4",
|
||||
"num",
|
||||
"once_cell",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"serde",
|
||||
"sha2 0.10.9",
|
||||
"zbus",
|
||||
@@ -15603,7 +15640,7 @@ dependencies = [
|
||||
"hex",
|
||||
"nix 0.29.0",
|
||||
"ordered-stream",
|
||||
"rand 0.8.5",
|
||||
"rand 0.8.6",
|
||||
"serde",
|
||||
"serde_repr",
|
||||
"sha1 0.10.6",
|
||||
|
||||
+8
-3
@@ -21,6 +21,9 @@ members = [
|
||||
"install-context",
|
||||
"codex-backend-openapi-models",
|
||||
"code-mode",
|
||||
"code-mode-host",
|
||||
"code-mode-protocol",
|
||||
"codex-home",
|
||||
"cloud-config",
|
||||
"cloud-tasks",
|
||||
"cloud-tasks-client",
|
||||
@@ -157,6 +160,8 @@ codex-cloud-config = { path = "cloud-config" }
|
||||
codex-cloud-tasks-client = { path = "cloud-tasks-client" }
|
||||
codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" }
|
||||
codex-code-mode = { path = "code-mode" }
|
||||
codex-code-mode-protocol = { path = "code-mode-protocol" }
|
||||
codex-home = { path = "codex-home" }
|
||||
codex-config = { path = "config" }
|
||||
codex-connectors = { path = "connectors" }
|
||||
codex-context-fragments = { path = "context-fragments" }
|
||||
@@ -237,6 +242,7 @@ codex-utils-json-to-toml = { path = "utils/json-to-toml" }
|
||||
codex-utils-oss = { path = "utils/oss" }
|
||||
codex-utils-output-truncation = { path = "utils/output-truncation" }
|
||||
codex-utils-path = { path = "utils/path-utils" }
|
||||
codex-utils-path-uri = { path = "utils/path-uri" }
|
||||
codex-utils-plugins = { path = "utils/plugins" }
|
||||
codex-utils-pty = { path = "utils/pty" }
|
||||
codex-utils-rustls-provider = { path = "utils/rustls-provider" }
|
||||
@@ -262,7 +268,6 @@ assert_matches = "1.5.0"
|
||||
async-channel = "2.3.1"
|
||||
async-io = "2.6.0"
|
||||
async-stream = "0.3.6"
|
||||
async-trait = "0.1.89"
|
||||
aws-config = "1"
|
||||
aws-credential-types = "1"
|
||||
aws-sigv4 = "1"
|
||||
@@ -511,8 +516,8 @@ split-debuginfo = "off"
|
||||
# sidecar symbols and stripped the binaries.
|
||||
strip = false
|
||||
|
||||
# See https://github.com/openai/codex/issues/1411 for details.
|
||||
codegen-units = 1
|
||||
# Balance parallel release code generation against binary size.
|
||||
codegen-units = 4
|
||||
|
||||
[profile.profiling]
|
||||
inherits = "release"
|
||||
|
||||
@@ -13,7 +13,6 @@ doctest = false
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-state = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use async_trait::async_trait;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_state::StateRuntime;
|
||||
use std::sync::Arc;
|
||||
@@ -29,7 +28,6 @@ impl LocalAgentGraphStore {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AgentGraphStore for LocalAgentGraphStore {
|
||||
async fn upsert_thread_spawn_edge(
|
||||
&self,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use async_trait::async_trait;
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
use crate::AgentGraphStoreResult;
|
||||
@@ -8,38 +7,37 @@ use crate::ThreadSpawnEdgeStatus;
|
||||
///
|
||||
/// Implementations are expected to return stable ordering for list methods so callers can merge
|
||||
/// persisted graph state with live in-memory state without introducing nondeterministic output.
|
||||
#[async_trait]
|
||||
pub trait AgentGraphStore: Send + Sync {
|
||||
/// Insert or replace the directional parent/child edge for a spawned thread.
|
||||
///
|
||||
/// `child_thread_id` has at most one persisted parent. Re-inserting the same child should
|
||||
/// update both the parent and status to match the supplied values.
|
||||
async fn upsert_thread_spawn_edge(
|
||||
fn upsert_thread_spawn_edge(
|
||||
&self,
|
||||
parent_thread_id: ThreadId,
|
||||
child_thread_id: ThreadId,
|
||||
status: ThreadSpawnEdgeStatus,
|
||||
) -> AgentGraphStoreResult<()>;
|
||||
) -> impl std::future::Future<Output = AgentGraphStoreResult<()>> + Send;
|
||||
|
||||
/// Update the persisted lifecycle status of a spawned thread's incoming edge.
|
||||
///
|
||||
/// Implementations should treat missing children as a successful no-op.
|
||||
async fn set_thread_spawn_edge_status(
|
||||
fn set_thread_spawn_edge_status(
|
||||
&self,
|
||||
child_thread_id: ThreadId,
|
||||
status: ThreadSpawnEdgeStatus,
|
||||
) -> AgentGraphStoreResult<()>;
|
||||
) -> impl std::future::Future<Output = AgentGraphStoreResult<()>> + Send;
|
||||
|
||||
/// List direct spawned children of a parent thread.
|
||||
///
|
||||
/// When `status_filter` is `Some`, only child edges with that exact status are returned. When
|
||||
/// it is `None`, all direct child edges are returned regardless of status, including statuses
|
||||
/// that may be added by a future store implementation.
|
||||
async fn list_thread_spawn_children(
|
||||
fn list_thread_spawn_children(
|
||||
&self,
|
||||
parent_thread_id: ThreadId,
|
||||
status_filter: Option<ThreadSpawnEdgeStatus>,
|
||||
) -> AgentGraphStoreResult<Vec<ThreadId>>;
|
||||
) -> impl std::future::Future<Output = AgentGraphStoreResult<Vec<ThreadId>>> + Send;
|
||||
|
||||
/// List spawned descendants breadth-first by depth, then by thread id.
|
||||
///
|
||||
@@ -47,9 +45,9 @@ pub trait AgentGraphStore: Send + Sync {
|
||||
/// For example, `Some(Open)` walks only open edges, so descendants under a closed edge are not
|
||||
/// included even if their own incoming edge is open. `None` walks and returns every persisted
|
||||
/// edge regardless of status.
|
||||
async fn list_thread_spawn_descendants(
|
||||
fn list_thread_spawn_descendants(
|
||||
&self,
|
||||
root_thread_id: ThreadId,
|
||||
status_filter: Option<ThreadSpawnEdgeStatus>,
|
||||
) -> AgentGraphStoreResult<Vec<ThreadId>>;
|
||||
) -> impl std::future::Future<Output = AgentGraphStoreResult<Vec<ThreadId>>> + Send;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ use crate::facts::AppInvocation;
|
||||
use crate::facts::AppMentionedInput;
|
||||
use crate::facts::AppUsedInput;
|
||||
use crate::facts::CodexCompactionEvent;
|
||||
use crate::facts::CodexErrKind;
|
||||
use crate::facts::CompactionImplementation;
|
||||
use crate::facts::CompactionPhase;
|
||||
use crate::facts::CompactionReason;
|
||||
@@ -778,6 +779,33 @@ fn sample_initialize_fact(connection_id: u64) -> AnalyticsFact {
|
||||
}
|
||||
}
|
||||
|
||||
async fn ingest_complete_child_turn(
|
||||
reducer: &mut AnalyticsReducer,
|
||||
events: &mut Vec<TrackEventRequest>,
|
||||
thread_id: &str,
|
||||
turn_id: &str,
|
||||
) {
|
||||
for fact in [
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new(
|
||||
sample_turn_resolved_config(thread_id, turn_id),
|
||||
))),
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::TurnProfile(Box::new(
|
||||
TurnProfileFact {
|
||||
turn_id: turn_id.to_string(),
|
||||
profile: sample_turn_profile(),
|
||||
},
|
||||
))),
|
||||
AnalyticsFact::Notification(Box::new(sample_turn_completed_notification(
|
||||
thread_id,
|
||||
turn_id,
|
||||
AppServerTurnStatus::Completed,
|
||||
/*codex_error_info*/ None,
|
||||
))),
|
||||
] {
|
||||
reducer.ingest(fact, events).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_command_execution_item(
|
||||
status: CommandExecutionStatus,
|
||||
exit_code: Option<i32>,
|
||||
@@ -1251,11 +1279,13 @@ fn compaction_event_serializes_expected_shape() {
|
||||
phase: CompactionPhase::MidTurn,
|
||||
strategy: CompactionStrategy::Memento,
|
||||
status: CompactionStatus::Completed,
|
||||
error: None,
|
||||
codex_error_kind: None,
|
||||
codex_error_http_status_code: None,
|
||||
active_context_tokens_before: 120_000,
|
||||
active_context_tokens_after: 18_000,
|
||||
retained_image_count: None,
|
||||
compaction_summary_tokens: None,
|
||||
cached_input_tokens: None,
|
||||
started_at: 100,
|
||||
completed_at: 106,
|
||||
duration_ms: Some(6543),
|
||||
@@ -1301,11 +1331,13 @@ fn compaction_event_serializes_expected_shape() {
|
||||
"phase": "mid_turn",
|
||||
"strategy": "memento",
|
||||
"status": "completed",
|
||||
"error": null,
|
||||
"codex_error_kind": null,
|
||||
"codex_error_http_status_code": null,
|
||||
"active_context_tokens_before": 120000,
|
||||
"active_context_tokens_after": 18000,
|
||||
"retained_image_count": null,
|
||||
"compaction_summary_tokens": null,
|
||||
"cached_input_tokens": null,
|
||||
"started_at": 100,
|
||||
"completed_at": 106,
|
||||
"duration_ms": 6543
|
||||
@@ -1823,11 +1855,13 @@ async fn compaction_event_ingests_custom_fact() {
|
||||
phase: CompactionPhase::StandaloneTurn,
|
||||
strategy: CompactionStrategy::Memento,
|
||||
status: CompactionStatus::Failed,
|
||||
error: Some("context limit exceeded".to_string()),
|
||||
codex_error_kind: Some(CodexErrKind::ContextWindowExceeded),
|
||||
codex_error_http_status_code: None,
|
||||
active_context_tokens_before: 131_000,
|
||||
active_context_tokens_after: 131_000,
|
||||
retained_image_count: None,
|
||||
compaction_summary_tokens: None,
|
||||
cached_input_tokens: None,
|
||||
started_at: 100,
|
||||
completed_at: 101,
|
||||
duration_ms: Some(1200),
|
||||
@@ -1843,6 +1877,14 @@ async fn compaction_event_ingests_custom_fact() {
|
||||
assert_eq!(payload[0]["event_params"]["session_id"], "session-thread-1");
|
||||
assert_eq!(payload[0]["event_params"]["thread_id"], "thread-1");
|
||||
assert_eq!(payload[0]["event_params"]["turn_id"], "turn-compact");
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["codex_error_kind"],
|
||||
json!("context_window_exceeded")
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["codex_error_http_status_code"],
|
||||
json!(null)
|
||||
);
|
||||
assert_eq!(
|
||||
payload[0]["event_params"]["app_server_client"]["product_client_id"],
|
||||
DEFAULT_ORIGINATOR
|
||||
@@ -2667,7 +2709,7 @@ async fn subagent_thread_started_publishes_without_initialize() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
|
||||
async fn subagent_events_use_inherited_connection_unless_turn_connection_is_explicit() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
let parent_thread_id =
|
||||
@@ -2749,11 +2791,13 @@ async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
|
||||
phase: CompactionPhase::StandaloneTurn,
|
||||
strategy: CompactionStrategy::Memento,
|
||||
status: CompactionStatus::Completed,
|
||||
error: None,
|
||||
codex_error_kind: None,
|
||||
codex_error_http_status_code: None,
|
||||
active_context_tokens_before: 131_000,
|
||||
active_context_tokens_after: 64_000,
|
||||
retained_image_count: None,
|
||||
compaction_summary_tokens: None,
|
||||
cached_input_tokens: None,
|
||||
started_at: 100,
|
||||
completed_at: 101,
|
||||
duration_ms: Some(1200),
|
||||
@@ -2774,6 +2818,68 @@ async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
|
||||
payload[0]["event_params"]["parent_thread_id"],
|
||||
"44444444-4444-4444-4444-444444444444"
|
||||
);
|
||||
|
||||
events.clear();
|
||||
ingest_complete_child_turn(&mut reducer, &mut events, "thread-review", "turn-inherited").await;
|
||||
let [TrackEventRequest::TurnEvent(event)] = events.as_slice() else {
|
||||
panic!("expected one turn event");
|
||||
};
|
||||
let params = &event.event_params;
|
||||
assert_eq!(params.session_id, "session-root");
|
||||
assert_eq!(params.thread_source, Some(ThreadSource::Subagent));
|
||||
assert_eq!(params.subagent_source.as_deref(), Some("thread_spawn"));
|
||||
assert_eq!(
|
||||
params.parent_thread_id.as_deref(),
|
||||
Some("44444444-4444-4444-4444-444444444444")
|
||||
);
|
||||
assert_eq!(params.app_server_client.product_client_id, "parent-client");
|
||||
assert_eq!(params.runtime.codex_rs_version, "0.1.0");
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::TurnTokenUsage(Box::new(
|
||||
sample_turn_token_usage_fact("thread-review", "turn-inherited"),
|
||||
))),
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(events.len(), 1);
|
||||
|
||||
events.clear();
|
||||
reducer
|
||||
.ingest(sample_initialize_fact(/*connection_id*/ 8), &mut events)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::ClientRequest {
|
||||
connection_id: 8,
|
||||
request_id: RequestId::Integer(3),
|
||||
request: Box::new(sample_turn_start_request(
|
||||
"thread-review",
|
||||
/*request_id*/ 3,
|
||||
)),
|
||||
},
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::ClientResponse {
|
||||
connection_id: 8,
|
||||
request_id: RequestId::Integer(3),
|
||||
response: Box::new(sample_turn_start_response("turn-explicit")),
|
||||
},
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
ingest_complete_child_turn(&mut reducer, &mut events, "thread-review", "turn-explicit").await;
|
||||
let [TrackEventRequest::TurnEvent(event)] = events.as_slice() else {
|
||||
panic!("expected one turn event");
|
||||
};
|
||||
assert_eq!(
|
||||
event.event_params.app_server_client.product_client_id,
|
||||
DEFAULT_ORIGINATOR
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -3757,6 +3863,32 @@ async fn turn_event_counts_completed_tool_items() {
|
||||
)
|
||||
.await;
|
||||
|
||||
let mcp_tool_call_item = |status, duration_ms| ThreadItem::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "server".to_string(),
|
||||
tool: "search".to_string(),
|
||||
status,
|
||||
arguments: json!({}),
|
||||
mcp_app_resource_uri: None,
|
||||
plugin_id: Some("sample@test".to_string()),
|
||||
result: None,
|
||||
error: None,
|
||||
duration_ms,
|
||||
};
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted(
|
||||
ItemStartedNotification {
|
||||
thread_id: "thread-2".to_string(),
|
||||
turn_id: "turn-2".to_string(),
|
||||
started_at_ms: 998,
|
||||
item: mcp_tool_call_item(McpToolCallStatus::InProgress, None),
|
||||
},
|
||||
))),
|
||||
&mut out,
|
||||
)
|
||||
.await;
|
||||
|
||||
let completed_tool_items = vec![
|
||||
sample_command_execution_item(CommandExecutionStatus::Completed, Some(0), Some(1)),
|
||||
ThreadItem::FileChange {
|
||||
@@ -3764,18 +3896,7 @@ async fn turn_event_counts_completed_tool_items() {
|
||||
changes: Vec::new(),
|
||||
status: PatchApplyStatus::Completed,
|
||||
},
|
||||
ThreadItem::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "server".to_string(),
|
||||
tool: "search".to_string(),
|
||||
status: McpToolCallStatus::Completed,
|
||||
arguments: json!({}),
|
||||
mcp_app_resource_uri: None,
|
||||
plugin_id: None,
|
||||
result: None,
|
||||
error: None,
|
||||
duration_ms: Some(2),
|
||||
},
|
||||
mcp_tool_call_item(McpToolCallStatus::Completed, Some(2)),
|
||||
ThreadItem::DynamicToolCall {
|
||||
id: "dynamic-1".to_string(),
|
||||
namespace: None,
|
||||
@@ -3833,6 +3954,13 @@ async fn turn_event_counts_completed_tool_items() {
|
||||
.await;
|
||||
}
|
||||
|
||||
let mcp_tool_call_event = out
|
||||
.iter()
|
||||
.find(|event| matches!(event, TrackEventRequest::McpToolCall(_)))
|
||||
.expect("MCP tool call event should be emitted");
|
||||
let payload = serde_json::to_value(mcp_tool_call_event).expect("serialize MCP tool call event");
|
||||
assert_eq!(payload["event_params"]["plugin_id"], json!("sample@test"));
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Notification(Box::new(sample_turn_completed_notification(
|
||||
|
||||
@@ -633,6 +633,7 @@ pub(crate) struct CodexMcpToolCallEventParams {
|
||||
pub(crate) mcp_server_name: String,
|
||||
pub(crate) mcp_tool_name: String,
|
||||
pub(crate) mcp_error_present: bool,
|
||||
pub(crate) plugin_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -762,11 +763,13 @@ pub(crate) struct CodexCompactionEventParams {
|
||||
pub(crate) phase: CompactionPhase,
|
||||
pub(crate) strategy: CompactionStrategy,
|
||||
pub(crate) status: CompactionStatus,
|
||||
pub(crate) error: Option<String>,
|
||||
pub(crate) codex_error_kind: Option<CodexErrKind>,
|
||||
pub(crate) codex_error_http_status_code: Option<u16>,
|
||||
pub(crate) active_context_tokens_before: i64,
|
||||
pub(crate) active_context_tokens_after: i64,
|
||||
pub(crate) retained_image_count: Option<usize>,
|
||||
pub(crate) compaction_summary_tokens: Option<i64>,
|
||||
pub(crate) cached_input_tokens: Option<i64>,
|
||||
pub(crate) started_at: u64,
|
||||
pub(crate) completed_at: u64,
|
||||
pub(crate) duration_ms: Option<u64>,
|
||||
@@ -999,11 +1002,13 @@ pub(crate) fn codex_compaction_event_params(
|
||||
phase: input.phase,
|
||||
strategy: input.strategy,
|
||||
status: input.status,
|
||||
error: input.error,
|
||||
codex_error_kind: input.codex_error_kind,
|
||||
codex_error_http_status_code: input.codex_error_http_status_code,
|
||||
active_context_tokens_before: input.active_context_tokens_before,
|
||||
active_context_tokens_after: input.active_context_tokens_after,
|
||||
retained_image_count: input.retained_image_count,
|
||||
compaction_summary_tokens: input.compaction_summary_tokens,
|
||||
cached_input_tokens: input.cached_input_tokens,
|
||||
started_at: input.started_at,
|
||||
completed_at: input.completed_at,
|
||||
duration_ms: input.duration_ms,
|
||||
|
||||
@@ -137,7 +137,7 @@ impl TurnCodexErrorFact {
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum CodexErrKind {
|
||||
pub enum CodexErrKind {
|
||||
TurnAborted,
|
||||
Stream,
|
||||
ContextWindowExceeded,
|
||||
@@ -364,6 +364,7 @@ pub enum CompactionReason {
|
||||
UserRequested,
|
||||
ContextLimit,
|
||||
ModelDownshift,
|
||||
CompHashChanged,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
@@ -407,11 +408,13 @@ pub struct CodexCompactionEvent {
|
||||
pub phase: CompactionPhase,
|
||||
pub strategy: CompactionStrategy,
|
||||
pub status: CompactionStatus,
|
||||
pub error: Option<String>,
|
||||
pub codex_error_kind: Option<CodexErrKind>,
|
||||
pub codex_error_http_status_code: Option<u16>,
|
||||
pub active_context_tokens_before: i64,
|
||||
pub active_context_tokens_after: i64,
|
||||
pub retained_image_count: Option<usize>,
|
||||
pub compaction_summary_tokens: Option<i64>,
|
||||
pub cached_input_tokens: Option<i64>,
|
||||
pub started_at: u64,
|
||||
pub completed_at: u64,
|
||||
pub duration_ms: Option<u64>,
|
||||
|
||||
@@ -24,6 +24,7 @@ pub use facts::AcceptedLineFingerprint;
|
||||
pub use facts::AnalyticsJsonRpcError;
|
||||
pub use facts::AppInvocation;
|
||||
pub use facts::CodexCompactionEvent;
|
||||
pub use facts::CodexErrKind;
|
||||
pub use facts::CodexGoalEvent;
|
||||
pub use facts::CodexTurnSteerEvent;
|
||||
pub use facts::CompactionImplementation;
|
||||
|
||||
@@ -1497,17 +1497,23 @@ impl AnalyticsReducer {
|
||||
let Some(thread_id) = turn_state.thread_id.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some(connection_id) = turn_state.connection_id else {
|
||||
let drop_site = AnalyticsDropSite::turn(thread_id, turn_id);
|
||||
let connection_id = turn_state.connection_id.or_else(|| {
|
||||
self.threads
|
||||
.get(drop_site.thread_id)
|
||||
.and_then(|thread| thread.connection_id)
|
||||
});
|
||||
let Some(connection_id) = connection_id else {
|
||||
warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadConnection);
|
||||
return;
|
||||
};
|
||||
let Some(connection_state) = self.connections.get(&connection_id) else {
|
||||
warn_missing_analytics_context(
|
||||
&AnalyticsDropSite::turn(thread_id, turn_id),
|
||||
&drop_site,
|
||||
MissingAnalyticsContext::Connection { connection_id },
|
||||
);
|
||||
return;
|
||||
};
|
||||
let drop_site = AnalyticsDropSite::turn(thread_id, turn_id);
|
||||
let Some(thread_metadata) = self
|
||||
.threads
|
||||
.get(drop_site.thread_id)
|
||||
@@ -1745,6 +1751,7 @@ fn tool_item_event(input: ToolItemEventInput<'_>) -> Option<TrackEventRequest> {
|
||||
status,
|
||||
error,
|
||||
duration_ms,
|
||||
plugin_id,
|
||||
..
|
||||
} => {
|
||||
let (terminal_status, failure_kind) = mcp_tool_call_outcome(status)?;
|
||||
@@ -1774,6 +1781,7 @@ fn tool_item_event(input: ToolItemEventInput<'_>) -> Option<TrackEventRequest> {
|
||||
mcp_server_name: server.clone(),
|
||||
mcp_tool_name: tool.clone(),
|
||||
mcp_error_present: error.is_some(),
|
||||
plugin_id: plugin_id.clone(),
|
||||
},
|
||||
},
|
||||
))
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
//! bridging async `mpsc` channels on both sides. Queues are bounded so overload
|
||||
//! surfaces as channel-full errors rather than unbounded memory growth.
|
||||
|
||||
mod path;
|
||||
mod remote;
|
||||
|
||||
use std::error::Error;
|
||||
@@ -22,6 +23,7 @@ use std::fmt;
|
||||
use std::io::Error as IoError;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Result as IoResult;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -48,11 +50,16 @@ use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::RemoteThreadConfigLoader;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_core::config::Config;
|
||||
pub use codex_core::otel_init::build_provider as build_otel_provider;
|
||||
use codex_core::personality_migration::PersonalityMigrationStatus;
|
||||
use codex_core::personality_migration::maybe_migrate_personality;
|
||||
pub use codex_exec_server::EnvironmentManager;
|
||||
pub use codex_exec_server::ExecServerRuntimePaths;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -60,6 +67,7 @@ use tokio::time::timeout;
|
||||
use toml::Value as TomlValue;
|
||||
use tracing::warn;
|
||||
|
||||
pub use crate::path::AppServerPath;
|
||||
pub use crate::remote::RemoteAppServerClient;
|
||||
pub use crate::remote::RemoteAppServerConnectArgs;
|
||||
pub use crate::remote::RemoteAppServerEndpoint;
|
||||
@@ -72,7 +80,6 @@ pub use crate::remote::RemoteAppServerEndpoint;
|
||||
pub mod legacy_core {
|
||||
pub use codex_core::check_execpolicy_for_warnings;
|
||||
pub use codex_core::format_exec_policy_error_with_source;
|
||||
pub use codex_core::grant_read_root_non_elevated;
|
||||
|
||||
pub mod config {
|
||||
pub use codex_core::config::*;
|
||||
@@ -81,26 +88,27 @@ pub mod legacy_core {
|
||||
pub use codex_core::config::edit::*;
|
||||
}
|
||||
}
|
||||
|
||||
pub mod otel_init {
|
||||
pub use codex_core::otel_init::*;
|
||||
}
|
||||
|
||||
pub mod personality_migration {
|
||||
pub use codex_core::personality_migration::*;
|
||||
}
|
||||
|
||||
pub mod test_support {
|
||||
pub use codex_core::test_support::*;
|
||||
}
|
||||
|
||||
pub mod windows_sandbox {
|
||||
pub use codex_core::windows_sandbox::*;
|
||||
}
|
||||
}
|
||||
|
||||
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Runs the embedded app-server personality migration.
|
||||
///
|
||||
/// Returns `true` when the migration changed config and the caller should reload it.
|
||||
pub async fn migrate_personality_if_needed(
|
||||
codex_home: &Path,
|
||||
config_toml: &ConfigToml,
|
||||
state_db: Option<StateDbHandle>,
|
||||
) -> IoResult<bool> {
|
||||
let status = maybe_migrate_personality(codex_home, config_toml, state_db).await?;
|
||||
match status {
|
||||
PersonalityMigrationStatus::Applied => Ok(true),
|
||||
PersonalityMigrationStatus::SkippedMarker
|
||||
| PersonalityMigrationStatus::SkippedExplicitPersonality
|
||||
| PersonalityMigrationStatus::SkippedNoSessions => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw app-server request result for typed in-process requests.
|
||||
///
|
||||
/// Even on the in-process path, successful responses still travel back through
|
||||
@@ -158,6 +166,7 @@ pub(crate) fn server_notification_requires_delivery(notification: &ServerNotific
|
||||
ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
| ServerNotification::ItemCompleted(_)
|
||||
| ServerNotification::ExternalAgentConfigImportCompleted(_)
|
||||
| ServerNotification::AgentMessageDelta(_)
|
||||
| ServerNotification::PlanDelta(_)
|
||||
| ServerNotification::ReasoningSummaryTextDelta(_)
|
||||
@@ -839,6 +848,15 @@ impl AppServerRequestHandle {
|
||||
}
|
||||
|
||||
impl AppServerClient {
|
||||
pub fn codex_home(&self, local_codex_home: &AbsolutePathBuf) -> Option<AppServerPath> {
|
||||
match self {
|
||||
Self::InProcess(_) => Some(AppServerPath::from_app_server(
|
||||
local_codex_home.display().to_string(),
|
||||
)),
|
||||
Self::Remote(client) => client.codex_home().map(AppServerPath::from_app_server),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn request(&self, request: ClientRequest) -> IoResult<RequestResult> {
|
||||
match self {
|
||||
Self::InProcess(client) => client.request(request).await,
|
||||
@@ -1104,6 +1122,7 @@ mod tests {
|
||||
id: request.id,
|
||||
result: serde_json::json!({
|
||||
"userAgent": "codex_cli_rs/9.8.7-test (Test OS; x86_64) rust",
|
||||
"codexHome": "/server/.codex",
|
||||
}),
|
||||
}),
|
||||
)
|
||||
@@ -1440,6 +1459,7 @@ mod tests {
|
||||
.expect("remote client should connect");
|
||||
|
||||
assert_eq!(client.server_version(), Some("9.8.7-test"));
|
||||
assert_eq!(client.codex_home(), Some("/server/.codex"));
|
||||
let response: GetAccountResponse = client
|
||||
.request_typed(ClientRequest::GetAccount {
|
||||
request_id: RequestId::Integer(1),
|
||||
@@ -1868,6 +1888,7 @@ mod tests {
|
||||
is_secret: false,
|
||||
options: Some(vec![]),
|
||||
}],
|
||||
auto_resolution_ms: None,
|
||||
})
|
||||
.expect("params should serialize"),
|
||||
),
|
||||
@@ -1929,6 +1950,7 @@ mod tests {
|
||||
is_secret: false,
|
||||
options: Some(vec![]),
|
||||
}],
|
||||
auto_resolution_ms: None,
|
||||
})
|
||||
.expect("params should serialize"),
|
||||
),
|
||||
@@ -2139,6 +2161,13 @@ mod tests {
|
||||
)
|
||||
)
|
||||
));
|
||||
assert!(event_requires_delivery(
|
||||
&InProcessServerEvent::ServerNotification(
|
||||
codex_app_server_protocol::ServerNotification::ExternalAgentConfigImportCompleted(
|
||||
codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification {},
|
||||
)
|
||||
)
|
||||
));
|
||||
assert!(!event_requires_delivery(&InProcessServerEvent::Lagged {
|
||||
skipped: 1
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Paths resolved using the app-server host's platform rules.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AppServerPath(String);
|
||||
|
||||
impl AppServerPath {
|
||||
pub fn from_app_server(path: impl Into<String>) -> Self {
|
||||
Self(path.into())
|
||||
}
|
||||
|
||||
pub fn from_absolute_str(raw: &str) -> Option<Self> {
|
||||
(raw.starts_with('/') || is_windows_absolute_path(raw)).then(|| Self(raw.to_string()))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn components(&self) -> Vec<&str> {
|
||||
let separators = if is_windows_absolute_path(&self.0) {
|
||||
&['/', '\\'][..]
|
||||
} else {
|
||||
&['/'][..]
|
||||
};
|
||||
self.0
|
||||
.split(separators)
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn join(&self, segment: impl AsRef<str>) -> Self {
|
||||
let is_windows = is_windows_absolute_path(&self.0);
|
||||
let (path, separator) = if is_windows {
|
||||
(self.0.trim_end_matches(['/', '\\']), '\\')
|
||||
} else {
|
||||
(self.0.trim_end_matches('/'), '/')
|
||||
};
|
||||
Self(format!("{path}{separator}{}", segment.as_ref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AppServerPath {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_windows_absolute_path(path: &str) -> bool {
|
||||
let bytes = path.as_bytes();
|
||||
(bytes.len() >= 3
|
||||
&& bytes[0].is_ascii_alphabetic()
|
||||
&& bytes[1] == b':'
|
||||
&& matches!(bytes[2], b'\\' | b'/'))
|
||||
|| path.starts_with("\\\\")
|
||||
|| path.starts_with("//")
|
||||
}
|
||||
@@ -124,7 +124,7 @@ pub(crate) fn websocket_url_supports_auth_token(url: &Url) -> bool {
|
||||
|
||||
enum RemoteClientCommand {
|
||||
Request {
|
||||
request: Box<ClientRequest>,
|
||||
request: Box<JSONRPCRequest>,
|
||||
response_tx: oneshot::Sender<IoResult<RequestResult>>,
|
||||
},
|
||||
Notify {
|
||||
@@ -151,6 +151,7 @@ pub struct RemoteAppServerClient {
|
||||
event_rx: mpsc::UnboundedReceiver<AppServerEvent>,
|
||||
pending_events: VecDeque<AppServerEvent>,
|
||||
server_version: Option<String>,
|
||||
codex_home: Option<String>,
|
||||
worker_handle: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -185,6 +186,10 @@ impl RemoteAppServerClient {
|
||||
self.server_version.as_deref()
|
||||
}
|
||||
|
||||
pub fn codex_home(&self) -> Option<&str> {
|
||||
self.codex_home.as_deref()
|
||||
}
|
||||
|
||||
async fn connect_with_stream<S>(
|
||||
channel_capacity: usize,
|
||||
endpoint: String,
|
||||
@@ -195,7 +200,7 @@ impl RemoteAppServerClient {
|
||||
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let mut stream = stream;
|
||||
let (pending_events, server_version) = initialize_remote_connection(
|
||||
let (pending_events, server_version, codex_home) = initialize_remote_connection(
|
||||
&mut stream,
|
||||
&endpoint,
|
||||
initialize_params,
|
||||
@@ -218,7 +223,7 @@ impl RemoteAppServerClient {
|
||||
};
|
||||
match command {
|
||||
RemoteClientCommand::Request { request, response_tx } => {
|
||||
let request_id = request_id_from_client_request(&request);
|
||||
let request_id = request.id.clone();
|
||||
if pending_requests.contains_key(&request_id) {
|
||||
let _ = response_tx.send(Err(IoError::new(
|
||||
ErrorKind::InvalidInput,
|
||||
@@ -229,7 +234,7 @@ impl RemoteAppServerClient {
|
||||
pending_requests.insert(request_id.clone(), response_tx);
|
||||
if let Err(err) = write_jsonrpc_message(
|
||||
&mut stream,
|
||||
JSONRPCMessage::Request(jsonrpc_request_from_client_request(*request)),
|
||||
JSONRPCMessage::Request(*request),
|
||||
&endpoint,
|
||||
)
|
||||
.await
|
||||
@@ -472,6 +477,7 @@ impl RemoteAppServerClient {
|
||||
event_rx,
|
||||
pending_events: pending_events.into(),
|
||||
server_version,
|
||||
codex_home,
|
||||
worker_handle,
|
||||
})
|
||||
}
|
||||
@@ -483,25 +489,7 @@ impl RemoteAppServerClient {
|
||||
}
|
||||
|
||||
pub async fn request(&self, request: ClientRequest) -> IoResult<RequestResult> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(RemoteClientCommand::Request {
|
||||
request: Box::new(request),
|
||||
response_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
IoError::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"remote app-server worker channel is closed",
|
||||
)
|
||||
})?;
|
||||
response_rx.await.map_err(|_| {
|
||||
IoError::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"remote app-server request channel is closed",
|
||||
)
|
||||
})?
|
||||
self.request_handle().request(request).await
|
||||
}
|
||||
|
||||
pub async fn request_typed<T>(&self, request: ClientRequest) -> Result<T, TypedRequestError>
|
||||
@@ -613,6 +601,7 @@ impl RemoteAppServerClient {
|
||||
event_rx,
|
||||
pending_events: _pending_events,
|
||||
server_version: _server_version,
|
||||
codex_home: _codex_home,
|
||||
worker_handle,
|
||||
} = self;
|
||||
let mut worker_handle = worker_handle;
|
||||
@@ -637,6 +626,11 @@ impl RemoteAppServerClient {
|
||||
|
||||
impl RemoteAppServerRequestHandle {
|
||||
pub async fn request(&self, request: ClientRequest) -> IoResult<RequestResult> {
|
||||
self.request_json_rpc(jsonrpc_request_from_client_request(request))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn request_json_rpc(&self, request: JSONRPCRequest) -> IoResult<RequestResult> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(RemoteClientCommand::Request {
|
||||
@@ -800,13 +794,14 @@ async fn initialize_remote_connection<S>(
|
||||
endpoint: &str,
|
||||
params: InitializeParams,
|
||||
initialize_timeout: Duration,
|
||||
) -> IoResult<(Vec<AppServerEvent>, Option<String>)>
|
||||
) -> IoResult<(Vec<AppServerEvent>, Option<String>, Option<String>)>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let initialize_request_id = RequestId::String("initialize".to_string());
|
||||
let mut pending_events = Vec::new();
|
||||
let mut server_version = None;
|
||||
let mut codex_home = None;
|
||||
write_jsonrpc_message(
|
||||
stream,
|
||||
JSONRPCMessage::Request(jsonrpc_request_from_client_request(
|
||||
@@ -838,6 +833,12 @@ where
|
||||
let (_, rest) = user_agent.split_once('/')?;
|
||||
rest.split_whitespace().next().map(str::to_string)
|
||||
});
|
||||
codex_home = response
|
||||
.result
|
||||
.get("codexHome")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|codex_home| !codex_home.is_empty())
|
||||
.map(str::to_string);
|
||||
break Ok(());
|
||||
}
|
||||
JSONRPCMessage::Error(error) if error.id == initialize_request_id => {
|
||||
@@ -929,7 +930,7 @@ where
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok((pending_events, server_version))
|
||||
Ok((pending_events, server_version, codex_home))
|
||||
}
|
||||
|
||||
fn app_server_event_from_notification(notification: JSONRPCNotification) -> Option<AppServerEvent> {
|
||||
@@ -951,10 +952,6 @@ fn deliver_event(
|
||||
})
|
||||
}
|
||||
|
||||
fn request_id_from_client_request(request: &ClientRequest) -> RequestId {
|
||||
jsonrpc_request_from_client_request(request.clone()).id
|
||||
}
|
||||
|
||||
fn jsonrpc_request_from_client_request(request: ClientRequest) -> JSONRPCRequest {
|
||||
let value = match serde_json::to_value(request) {
|
||||
Ok(value) => value,
|
||||
@@ -1024,6 +1021,7 @@ mod tests {
|
||||
event_rx,
|
||||
pending_events: VecDeque::new(),
|
||||
server_version: None,
|
||||
codex_home: None,
|
||||
worker_handle,
|
||||
};
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ use std::time::Duration;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
#[cfg(unix)]
|
||||
use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use tokio::fs;
|
||||
@@ -164,6 +166,9 @@ impl PidBackend {
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::from(stderr_log.into_std().await));
|
||||
if let Some((key, value)) = self.command_env() {
|
||||
command.env(key, value);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -407,6 +412,19 @@ impl PidBackend {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn command_env(&self) -> Option<(&'static str, &'static str)> {
|
||||
match self.command_kind {
|
||||
PidCommandKind::AppServer {
|
||||
remote_control_enabled: false,
|
||||
} => Some((REMOTE_CONTROL_DISABLED_ENV_VAR, "1")),
|
||||
PidCommandKind::AppServer {
|
||||
remote_control_enabled: true,
|
||||
}
|
||||
| PidCommandKind::UpdateLoop => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn terminate_process(&self, pid: u32) -> Result<()> {
|
||||
match self.command_kind {
|
||||
PidCommandKind::AppServer { .. } => terminate_process(pid),
|
||||
|
||||
@@ -3,6 +3,8 @@ use std::time::Duration;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
|
||||
use super::PidBackend;
|
||||
use super::PidCommandKind;
|
||||
use super::PidFileState;
|
||||
@@ -174,6 +176,24 @@ fn app_server_remote_control_uses_runtime_flag() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_disabled_remote_control_uses_compatible_args_and_runtime_env() {
|
||||
let backend = PidBackend::new(
|
||||
"codex".into(),
|
||||
"app-server.pid".into(),
|
||||
/*remote_control_enabled*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
backend.command_args(),
|
||||
vec!["app-server", "--listen", "unix://"]
|
||||
);
|
||||
assert_eq!(
|
||||
backend.command_env(),
|
||||
Some((REMOTE_CONTROL_DISABLED_ENV_VAR, "1"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_stderr_log_tail_returns_recent_complete_lines() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
|
||||
@@ -543,6 +543,16 @@ impl Daemon {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if info.is_some() {
|
||||
match mode {
|
||||
RemoteControlMode::Enabled => {
|
||||
remote_control_client::enable_remote_control(&self.socket_path).await?;
|
||||
}
|
||||
RemoteControlMode::Disabled => {
|
||||
remote_control_client::disable_remote_control(&self.socket_path).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(self.remote_control_output(
|
||||
already_remote_control_status(mode),
|
||||
backend.map(|_| BackendKind::Pid),
|
||||
|
||||
@@ -8,9 +8,13 @@ use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::JSONRPCNotification;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
||||
use codex_app_server_protocol::RemoteControlDisableParams;
|
||||
use codex_app_server_protocol::RemoteControlDisableResponse;
|
||||
use codex_app_server_protocol::RemoteControlEnableParams;
|
||||
use codex_app_server_protocol::RemoteControlEnableResponse;
|
||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::time::Instant;
|
||||
@@ -22,13 +26,33 @@ use crate::RemoteControlReadyStatus;
|
||||
use crate::client;
|
||||
|
||||
const REMOTE_CONTROL_READY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const REMOTE_CONTROL_ENABLE_REQUEST_ID: RequestId = RequestId::Integer(2);
|
||||
const REMOTE_CONTROL_REQUEST_ID: RequestId = RequestId::Integer(2);
|
||||
const INVALID_PARAMS_ERROR_CODE: i64 = -32602;
|
||||
|
||||
enum RemoteControlRpcResponse<T> {
|
||||
Success(T),
|
||||
InvalidParams,
|
||||
}
|
||||
|
||||
pub(crate) async fn enable_remote_control(socket_path: &Path) -> Result<RemoteControlReadyStatus> {
|
||||
let mut websocket = client::connect(socket_path).await?;
|
||||
enable_remote_control_with_timeout(&mut websocket, REMOTE_CONTROL_READY_TIMEOUT).await
|
||||
}
|
||||
|
||||
pub(crate) async fn disable_remote_control(socket_path: &Path) -> Result<RemoteControlReadyStatus> {
|
||||
let mut websocket = client::connect(socket_path).await?;
|
||||
initialize_client(&mut websocket).await?;
|
||||
let params = serde_json::to_value(RemoteControlDisableParams { ephemeral: true })?;
|
||||
let response: RemoteControlDisableResponse = request_remote_control_with_legacy_fallback(
|
||||
&mut websocket,
|
||||
"remoteControl/disable",
|
||||
params,
|
||||
)
|
||||
.await?;
|
||||
websocket.close(None).await.ok();
|
||||
Ok(RemoteControlReadyStatus::from(response))
|
||||
}
|
||||
|
||||
pub(crate) async fn enable_remote_control_with_connect_retry(
|
||||
socket_path: &Path,
|
||||
connect_timeout: Duration,
|
||||
@@ -43,6 +67,26 @@ async fn enable_remote_control_with_timeout<S>(
|
||||
websocket: &mut WebSocketStream<S>,
|
||||
ready_timeout: Duration,
|
||||
) -> Result<RemoteControlReadyStatus>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
initialize_client(websocket).await?;
|
||||
|
||||
let response: RemoteControlEnableResponse = request_remote_control_with_legacy_fallback(
|
||||
websocket,
|
||||
"remoteControl/enable",
|
||||
serde_json::to_value(RemoteControlEnableParams { ephemeral: true })?,
|
||||
)
|
||||
.await?;
|
||||
let mut latest = RemoteControlReadyStatus::from(response);
|
||||
if latest.status == RemoteControlConnectionStatus::Connecting {
|
||||
latest = wait_for_remote_control_status(websocket, latest, ready_timeout).await?;
|
||||
}
|
||||
websocket.close(None).await.ok();
|
||||
Ok(latest)
|
||||
}
|
||||
|
||||
async fn initialize_client<S>(websocket: &mut WebSocketStream<S>) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
@@ -53,24 +97,65 @@ where
|
||||
});
|
||||
client::send_message(websocket, &initialized)
|
||||
.await
|
||||
.context("failed to send initialized notification")?;
|
||||
.context("failed to send initialized notification")
|
||||
}
|
||||
|
||||
let enable = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: REMOTE_CONTROL_ENABLE_REQUEST_ID,
|
||||
method: "remoteControl/enable".to_string(),
|
||||
params: None,
|
||||
async fn send_remote_control_request<S>(
|
||||
websocket: &mut WebSocketStream<S>,
|
||||
request_id: RequestId,
|
||||
method: &str,
|
||||
params: Option<serde_json::Value>,
|
||||
) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let request = JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: request_id,
|
||||
method: method.to_string(),
|
||||
params,
|
||||
trace: None,
|
||||
});
|
||||
client::send_message(websocket, &enable)
|
||||
client::send_message(websocket, &request)
|
||||
.await
|
||||
.context("failed to send remoteControl/enable request")?;
|
||||
.with_context(|| format!("failed to send {method} request"))
|
||||
}
|
||||
|
||||
let mut latest = read_enable_response(websocket).await?;
|
||||
if latest.status == RemoteControlConnectionStatus::Connecting {
|
||||
latest = wait_for_remote_control_status(websocket, latest, ready_timeout).await?;
|
||||
async fn request_remote_control_with_legacy_fallback<S, T>(
|
||||
websocket: &mut WebSocketStream<S>,
|
||||
method: &str,
|
||||
params: serde_json::Value,
|
||||
) -> Result<T>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
send_remote_control_request(
|
||||
websocket,
|
||||
REMOTE_CONTROL_REQUEST_ID.clone(),
|
||||
method,
|
||||
Some(params),
|
||||
)
|
||||
.await?;
|
||||
match read_remote_control_response(websocket, &REMOTE_CONTROL_REQUEST_ID, method).await? {
|
||||
RemoteControlRpcResponse::Success(response) => Ok(response),
|
||||
RemoteControlRpcResponse::InvalidParams => {
|
||||
send_remote_control_request(
|
||||
websocket,
|
||||
REMOTE_CONTROL_REQUEST_ID.clone(),
|
||||
method,
|
||||
/*params*/ None,
|
||||
)
|
||||
.await?;
|
||||
match read_remote_control_response(websocket, &REMOTE_CONTROL_REQUEST_ID, method)
|
||||
.await?
|
||||
{
|
||||
RemoteControlRpcResponse::Success(response) => Ok(response),
|
||||
RemoteControlRpcResponse::InvalidParams => {
|
||||
Err(anyhow!("{method} rejected legacy params"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
websocket.close(None).await.ok();
|
||||
Ok(latest)
|
||||
}
|
||||
|
||||
async fn connect_with_retry(
|
||||
@@ -97,11 +182,14 @@ async fn connect_with_retry(
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_enable_response<S>(
|
||||
async fn read_remote_control_response<S, T>(
|
||||
websocket: &mut WebSocketStream<S>,
|
||||
) -> Result<RemoteControlReadyStatus>
|
||||
request_id: &RequestId,
|
||||
method: &str,
|
||||
) -> Result<RemoteControlRpcResponse<T>>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
loop {
|
||||
let message = timeout(
|
||||
@@ -109,21 +197,20 @@ where
|
||||
client::read_message(websocket),
|
||||
)
|
||||
.await
|
||||
.context("timed out waiting for remoteControl/enable response")??;
|
||||
.with_context(|| format!("timed out waiting for {method} response"))??;
|
||||
match message {
|
||||
JSONRPCMessage::Response(response)
|
||||
if response.id == REMOTE_CONTROL_ENABLE_REQUEST_ID =>
|
||||
{
|
||||
let response =
|
||||
serde_json::from_value::<RemoteControlEnableResponse>(response.result)
|
||||
.context("failed to parse remoteControl/enable response")?;
|
||||
return Ok(RemoteControlReadyStatus::from(response));
|
||||
JSONRPCMessage::Response(response) if response.id == *request_id => {
|
||||
let response = serde_json::from_value::<T>(response.result)
|
||||
.with_context(|| format!("failed to parse {method} response"))?;
|
||||
return Ok(RemoteControlRpcResponse::Success(response));
|
||||
}
|
||||
JSONRPCMessage::Error(err) if err.id == REMOTE_CONTROL_ENABLE_REQUEST_ID => {
|
||||
return Err(anyhow!(
|
||||
"remoteControl/enable failed: {}",
|
||||
err.error.message
|
||||
));
|
||||
JSONRPCMessage::Error(err)
|
||||
if err.id == *request_id && err.error.code == INVALID_PARAMS_ERROR_CODE =>
|
||||
{
|
||||
return Ok(RemoteControlRpcResponse::InvalidParams);
|
||||
}
|
||||
JSONRPCMessage::Error(err) if err.id == *request_id => {
|
||||
return Err(anyhow!("{method} failed: {}", err.error.message));
|
||||
}
|
||||
JSONRPCMessage::Notification(notification)
|
||||
if remote_control_status_notification(¬ification).is_some() =>
|
||||
@@ -196,6 +283,23 @@ impl From<RemoteControlEnableResponse> for RemoteControlReadyStatus {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RemoteControlDisableResponse> for RemoteControlReadyStatus {
|
||||
fn from(response: RemoteControlDisableResponse) -> Self {
|
||||
let RemoteControlDisableResponse {
|
||||
status,
|
||||
server_name,
|
||||
installation_id: _,
|
||||
environment_id,
|
||||
} = response;
|
||||
Self {
|
||||
status,
|
||||
server_name,
|
||||
environment_id,
|
||||
timed_out: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RemoteControlStatusChangedNotification> for RemoteControlReadyStatus {
|
||||
fn from(notification: RemoteControlStatusChangedNotification) -> Self {
|
||||
let RemoteControlStatusChangedNotification {
|
||||
@@ -216,6 +320,8 @@ impl From<RemoteControlStatusChangedNotification> for RemoteControlReadyStatus {
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use anyhow::Result;
|
||||
use codex_app_server_protocol::JSONRPCError;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
use codex_uds::UnixListener;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -243,6 +349,7 @@ mod tests {
|
||||
),
|
||||
after_enable_notification: None,
|
||||
ready_timeout: Duration::from_millis(20),
|
||||
reject_ephemeral_params: false,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -271,6 +378,7 @@ mod tests {
|
||||
Some("env_test"),
|
||||
)),
|
||||
ready_timeout: Duration::from_secs(1),
|
||||
reject_ephemeral_params: false,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -296,6 +404,7 @@ mod tests {
|
||||
),
|
||||
after_enable_notification: None,
|
||||
ready_timeout: Duration::from_millis(20),
|
||||
reject_ephemeral_params: false,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -321,6 +430,7 @@ mod tests {
|
||||
),
|
||||
after_enable_notification: None,
|
||||
ready_timeout: Duration::from_millis(20),
|
||||
reject_ephemeral_params: false,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -336,11 +446,104 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enable_remote_control_retries_without_params_for_older_servers() -> Result<()> {
|
||||
let status = run_enable_remote_control_scenario(EnableScenario {
|
||||
initial_notification: None,
|
||||
enable_response: remote_control_status(
|
||||
RemoteControlConnectionStatus::Connected,
|
||||
Some("env_test"),
|
||||
),
|
||||
after_enable_notification: None,
|
||||
ready_timeout: Duration::from_millis(20),
|
||||
reject_ephemeral_params: true,
|
||||
})
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
RemoteControlReadyStatus {
|
||||
status: RemoteControlConnectionStatus::Connected,
|
||||
server_name: TEST_SERVER_NAME.to_string(),
|
||||
environment_id: Some("env_test".to_string()),
|
||||
timed_out: false,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disable_remote_control_retries_without_params_for_older_servers() -> Result<()> {
|
||||
let dir = TempDir::new()?;
|
||||
let socket_path = dir.path().join("app-server.sock");
|
||||
let listener = UnixListener::bind(&socket_path).await?;
|
||||
let server_task = tokio::spawn(async move {
|
||||
let mut websocket = accept_initialized_client(listener).await?;
|
||||
let disable = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(disable) = disable else {
|
||||
panic!("expected remoteControl/disable request");
|
||||
};
|
||||
assert_eq!(disable.id, REMOTE_CONTROL_REQUEST_ID);
|
||||
assert_eq!(disable.method, "remoteControl/disable");
|
||||
assert_eq!(
|
||||
disable.params,
|
||||
Some(serde_json::json!({ "ephemeral": true }))
|
||||
);
|
||||
client::send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Error(JSONRPCError {
|
||||
id: REMOTE_CONTROL_REQUEST_ID,
|
||||
error: JSONRPCErrorError {
|
||||
code: INVALID_PARAMS_ERROR_CODE,
|
||||
message: "Invalid params".to_string(),
|
||||
data: None,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let fallback = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(fallback) = fallback else {
|
||||
panic!("expected fallback remoteControl/disable request");
|
||||
};
|
||||
assert_eq!(fallback.id, REMOTE_CONTROL_REQUEST_ID);
|
||||
assert_eq!(fallback.method, "remoteControl/disable");
|
||||
assert_eq!(fallback.params, None);
|
||||
client::send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Response(JSONRPCResponse {
|
||||
id: REMOTE_CONTROL_REQUEST_ID,
|
||||
result: serde_json::to_value(RemoteControlDisableResponse::from(
|
||||
remote_control_status(
|
||||
RemoteControlConnectionStatus::Disabled,
|
||||
/*environment_id*/ None,
|
||||
),
|
||||
))?,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
|
||||
let status = disable_remote_control(&socket_path).await?;
|
||||
server_task.await??;
|
||||
assert_eq!(
|
||||
status,
|
||||
RemoteControlReadyStatus {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: TEST_SERVER_NAME.to_string(),
|
||||
environment_id: None,
|
||||
timed_out: false,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct EnableScenario {
|
||||
initial_notification: Option<RemoteControlStatusChangedNotification>,
|
||||
enable_response: RemoteControlStatusChangedNotification,
|
||||
after_enable_notification: Option<RemoteControlStatusChangedNotification>,
|
||||
ready_timeout: Duration,
|
||||
reject_ephemeral_params: bool,
|
||||
}
|
||||
|
||||
async fn run_enable_remote_control_scenario(
|
||||
@@ -359,12 +562,70 @@ mod tests {
|
||||
}
|
||||
|
||||
async fn serve_enable_remote_control_scenario(
|
||||
mut listener: UnixListener,
|
||||
listener: UnixListener,
|
||||
scenario: EnableScenario,
|
||||
) -> Result<()> {
|
||||
let mut websocket = accept_initialized_client(listener).await?;
|
||||
if let Some(status) = scenario.initial_notification {
|
||||
send_remote_control_status(&mut websocket, status).await?;
|
||||
}
|
||||
|
||||
let enable = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(enable) = enable else {
|
||||
panic!("expected remoteControl/enable request");
|
||||
};
|
||||
assert_eq!(enable.id, REMOTE_CONTROL_REQUEST_ID);
|
||||
assert_eq!(enable.method, "remoteControl/enable");
|
||||
assert_eq!(
|
||||
enable.params,
|
||||
Some(serde_json::json!({ "ephemeral": true }))
|
||||
);
|
||||
if scenario.reject_ephemeral_params {
|
||||
client::send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Error(JSONRPCError {
|
||||
id: REMOTE_CONTROL_REQUEST_ID,
|
||||
error: JSONRPCErrorError {
|
||||
code: INVALID_PARAMS_ERROR_CODE,
|
||||
message: "Invalid params".to_string(),
|
||||
data: None,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let fallback = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(fallback) = fallback else {
|
||||
panic!("expected fallback remoteControl/enable request");
|
||||
};
|
||||
assert_eq!(fallback.id, REMOTE_CONTROL_REQUEST_ID);
|
||||
assert_eq!(fallback.method, "remoteControl/enable");
|
||||
assert_eq!(fallback.params, None);
|
||||
}
|
||||
client::send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Response(JSONRPCResponse {
|
||||
id: REMOTE_CONTROL_REQUEST_ID,
|
||||
result: serde_json::to_value(RemoteControlEnableResponse::from(
|
||||
scenario.enable_response,
|
||||
))?,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Some(status) = scenario.after_enable_notification {
|
||||
send_remote_control_status(&mut websocket, status).await?;
|
||||
} else {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn accept_initialized_client(
|
||||
mut listener: UnixListener,
|
||||
) -> Result<WebSocketStream<codex_uds::UnixStream>> {
|
||||
let stream = listener.accept().await?;
|
||||
let mut websocket = accept_async(stream).await?;
|
||||
|
||||
let initialize = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(initialize) = initialize else {
|
||||
panic!("expected initialize request");
|
||||
@@ -397,35 +658,7 @@ mod tests {
|
||||
panic!("expected initialized notification");
|
||||
};
|
||||
assert_eq!(initialized.method, "initialized");
|
||||
|
||||
if let Some(status) = scenario.initial_notification {
|
||||
send_remote_control_status(&mut websocket, status).await?;
|
||||
}
|
||||
|
||||
let enable = client::read_message(&mut websocket).await?;
|
||||
let JSONRPCMessage::Request(enable) = enable else {
|
||||
panic!("expected remoteControl/enable request");
|
||||
};
|
||||
assert_eq!(enable.id, REMOTE_CONTROL_ENABLE_REQUEST_ID);
|
||||
assert_eq!(enable.method, "remoteControl/enable");
|
||||
client::send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Response(JSONRPCResponse {
|
||||
id: REMOTE_CONTROL_ENABLE_REQUEST_ID,
|
||||
result: serde_json::to_value(RemoteControlEnableResponse::from(
|
||||
scenario.enable_response,
|
||||
))?,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Some(status) = scenario.after_enable_notification {
|
||||
send_remote_control_status(&mut websocket, status).await?;
|
||||
} else {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(websocket)
|
||||
}
|
||||
|
||||
async fn send_remote_control_status<S>(
|
||||
|
||||
@@ -2124,6 +2124,22 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"RemoteControlDisableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteControlEnableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RequestId": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
||||
@@ -532,6 +532,13 @@
|
||||
"personalAccessToken"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Amazon Bedrock bearer token managed by Codex.",
|
||||
"enum": [
|
||||
"bedrockApiKey"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -1690,6 +1690,15 @@
|
||||
"ToolRequestUserInputParams": {
|
||||
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
|
||||
"properties": {
|
||||
"autoResolutionMs": {
|
||||
"default": null,
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -57,6 +57,15 @@
|
||||
},
|
||||
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
|
||||
"properties": {
|
||||
"autoResolutionMs": {
|
||||
"default": null,
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
+55
-5
@@ -5626,6 +5626,15 @@
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "EXPERIMENTAL. Params sent with a request_user_input event.",
|
||||
"properties": {
|
||||
"autoResolutionMs": {
|
||||
"default": null,
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -6416,6 +6425,12 @@
|
||||
"AppSummary": {
|
||||
"description": "EXPERIMENTAL - app metadata summary for plugin responses.",
|
||||
"properties": {
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -6433,15 +6448,11 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"needsAuth": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"needsAuth"
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
@@ -6453,6 +6464,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -6567,6 +6584,16 @@
|
||||
},
|
||||
"AppsDefaultConfig": {
|
||||
"properties": {
|
||||
"approvals_reviewer": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/v2/ApprovalsReviewer"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
@@ -6728,6 +6755,13 @@
|
||||
"personalAccessToken"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Amazon Bedrock bearer token managed by Codex.",
|
||||
"enum": [
|
||||
"bedrockApiKey"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -14035,6 +14069,22 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"RemoteControlDisableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteControlEnableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteControlStatusChangedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Current remote-control connection status and remote identity exposed to clients.",
|
||||
|
||||
+46
-5
@@ -694,6 +694,12 @@
|
||||
"AppSummary": {
|
||||
"description": "EXPERIMENTAL - app metadata summary for plugin responses.",
|
||||
"properties": {
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -711,15 +717,11 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"needsAuth": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"needsAuth"
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
@@ -731,6 +733,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -845,6 +853,16 @@
|
||||
},
|
||||
"AppsDefaultConfig": {
|
||||
"properties": {
|
||||
"approvals_reviewer": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/ApprovalsReviewer"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
@@ -1006,6 +1024,13 @@
|
||||
"personalAccessToken"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Amazon Bedrock bearer token managed by Codex.",
|
||||
"enum": [
|
||||
"bedrockApiKey"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -10517,6 +10542,22 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"RemoteControlDisableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteControlEnableParams": {
|
||||
"properties": {
|
||||
"ephemeral": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteControlStatusChangedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Current remote-control connection status and remote identity exposed to clients.",
|
||||
|
||||
@@ -38,6 +38,13 @@
|
||||
"personalAccessToken"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Amazon Bedrock bearer token managed by Codex.",
|
||||
"enum": [
|
||||
"bedrockApiKey"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -133,6 +133,16 @@
|
||||
},
|
||||
"AppsDefaultConfig": {
|
||||
"properties": {
|
||||
"approvals_reviewer": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/ApprovalsReviewer"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
"AppSummary": {
|
||||
"description": "EXPERIMENTAL - app metadata summary for plugin responses.",
|
||||
"properties": {
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -21,15 +27,11 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"needsAuth": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"needsAuth"
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
|
||||
@@ -8,6 +8,12 @@
|
||||
"AppSummary": {
|
||||
"description": "EXPERIMENTAL - app metadata summary for plugin responses.",
|
||||
"properties": {
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -25,15 +31,11 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"needsAuth": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"needsAuth"
|
||||
"name"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
@@ -45,6 +47,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
"type": [
|
||||
"string",
|
||||
|
||||
+1
-1
@@ -5,4 +5,4 @@
|
||||
/**
|
||||
* Authentication mode for OpenAI-backed providers.
|
||||
*/
|
||||
export type AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens" | "agentIdentity" | "personalAccessToken";
|
||||
export type AuthMode = "apikey" | "chatgpt" | "chatgptAuthTokens" | "agentIdentity" | "personalAccessToken" | "bedrockApiKey";
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
/**
|
||||
* EXPERIMENTAL - app metadata summary for plugin responses.
|
||||
*/
|
||||
export type AppSummary = { id: string, name: string, description: string | null, installUrl: string | null, needsAuth: boolean, };
|
||||
export type AppSummary = { id: string, name: string, description: string | null, installUrl: string | null, category: string | null, };
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { AppTemplateUnavailableReason } from "./AppTemplateUnavailableReason";
|
||||
|
||||
export type AppTemplateSummary = { templateId: string, name: string, description: string | null, canonicalConnectorId: string | null, logoUrl: string | null, logoUrlDark: string | null, materializedAppIds: Array<string>, reason: AppTemplateUnavailableReason | null, };
|
||||
export type AppTemplateSummary = { templateId: string, name: string, description: string | null, category: string | null, canonicalConnectorId: string | null, logoUrl: string | null, logoUrlDark: string | null, materializedAppIds: Array<string>, reason: AppTemplateUnavailableReason | null, };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ApprovalsReviewer } from "./ApprovalsReviewer";
|
||||
|
||||
export type AppsDefaultConfig = { enabled: boolean, destructive_enabled: boolean, open_world_enabled: boolean, };
|
||||
export type AppsDefaultConfig = { enabled: boolean, approvals_reviewer: ApprovalsReviewer | null, destructive_enabled: boolean, open_world_enabled: boolean, };
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type RemoteControlDisableParams = { ephemeral?: boolean, };
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type RemoteControlEnableParams = { ephemeral?: boolean, };
|
||||
+1
-1
@@ -6,4 +6,4 @@ import type { ToolRequestUserInputQuestion } from "./ToolRequestUserInputQuestio
|
||||
/**
|
||||
* EXPERIMENTAL. Params sent with a request_user_input event.
|
||||
*/
|
||||
export type ToolRequestUserInputParams = { threadId: string, turnId: string, itemId: string, questions: Array<ToolRequestUserInputQuestion>, };
|
||||
export type ToolRequestUserInputParams = { threadId: string, turnId: string, itemId: string, questions: Array<ToolRequestUserInputQuestion>, autoResolutionMs: number | null, };
|
||||
|
||||
@@ -325,6 +325,8 @@ export type { ReasoningSummaryPartAddedNotification } from "./ReasoningSummaryPa
|
||||
export type { ReasoningSummaryTextDeltaNotification } from "./ReasoningSummaryTextDeltaNotification";
|
||||
export type { ReasoningTextDeltaNotification } from "./ReasoningTextDeltaNotification";
|
||||
export type { RemoteControlConnectionStatus } from "./RemoteControlConnectionStatus";
|
||||
export type { RemoteControlDisableParams } from "./RemoteControlDisableParams";
|
||||
export type { RemoteControlEnableParams } from "./RemoteControlEnableParams";
|
||||
export type { RemoteControlStatusChangedNotification } from "./RemoteControlStatusChangedNotification";
|
||||
export type { RequestPermissionProfile } from "./RequestPermissionProfile";
|
||||
export type { ResidencyRequirement } from "./ResidencyRequirement";
|
||||
|
||||
@@ -41,6 +41,11 @@ pub enum AuthMode {
|
||||
#[ts(rename = "personalAccessToken")]
|
||||
#[strum(serialize = "personalAccessToken")]
|
||||
PersonalAccessToken,
|
||||
/// Amazon Bedrock bearer token managed by Codex.
|
||||
#[serde(rename = "bedrockApiKey")]
|
||||
#[ts(rename = "bedrockApiKey")]
|
||||
#[strum(serialize = "bedrockApiKey")]
|
||||
BedrockApiKey,
|
||||
}
|
||||
|
||||
impl AuthMode {
|
||||
@@ -48,7 +53,7 @@ impl AuthMode {
|
||||
pub fn has_chatgpt_account(self) -> bool {
|
||||
match self {
|
||||
Self::Chatgpt | Self::ChatgptAuthTokens | Self::PersonalAccessToken => true,
|
||||
Self::ApiKey | Self::AgentIdentity => false,
|
||||
Self::ApiKey | Self::AgentIdentity | Self::BedrockApiKey => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -859,13 +864,13 @@ client_request_definitions! {
|
||||
},
|
||||
#[experimental("remoteControl/enable")]
|
||||
RemoteControlEnable => "remoteControl/enable" {
|
||||
params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
|
||||
params: #[serde(skip_serializing_if = "Option::is_none")] v2::NullableRemoteControlEnableParams,
|
||||
serialization: global("remote-control"),
|
||||
response: v2::RemoteControlEnableResponse,
|
||||
},
|
||||
#[experimental("remoteControl/disable")]
|
||||
RemoteControlDisable => "remoteControl/disable" {
|
||||
params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
|
||||
params: #[serde(skip_serializing_if = "Option::is_none")] v2::NullableRemoteControlDisableParams,
|
||||
serialization: global("remote-control"),
|
||||
response: v2::RemoteControlDisableResponse,
|
||||
},
|
||||
|
||||
@@ -124,6 +124,14 @@ impl ThreadHistoryBuilder {
|
||||
.or_else(|| self.turns.last().cloned())
|
||||
}
|
||||
|
||||
pub fn turn_snapshot(&self, turn_id: &str) -> Option<Turn> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.filter(|turn| turn.id == turn_id)
|
||||
.map(Turn::from)
|
||||
.or_else(|| self.turns.iter().find(|turn| turn.id == turn_id).cloned())
|
||||
}
|
||||
|
||||
/// Returns the index of the active turn snapshot within the finished turn list.
|
||||
///
|
||||
/// When a turn is still open, this is the index it will occupy after
|
||||
|
||||
@@ -102,6 +102,33 @@ pub struct AppInfo {
|
||||
pub plugin_display_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl AppInfo {
|
||||
pub fn category(&self) -> Option<String> {
|
||||
self.branding
|
||||
.as_ref()
|
||||
.and_then(|branding| non_empty_category(branding.category.as_deref()))
|
||||
.or_else(|| {
|
||||
self.app_metadata
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.categories.as_ref())
|
||||
.and_then(|categories| {
|
||||
categories
|
||||
.iter()
|
||||
.find_map(|category| non_empty_category(Some(category.as_str())))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_category(category: Option<&str>) -> Option<String> {
|
||||
let category = category?.trim();
|
||||
if category.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(category.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
@@ -111,17 +138,18 @@ pub struct AppSummary {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub install_url: Option<String>,
|
||||
pub needs_auth: bool,
|
||||
pub category: Option<String>,
|
||||
}
|
||||
|
||||
impl From<AppInfo> for AppSummary {
|
||||
fn from(value: AppInfo) -> Self {
|
||||
let category = value.category();
|
||||
Self {
|
||||
id: value.id,
|
||||
name: value.name,
|
||||
description: value.description,
|
||||
install_url: value.install_url,
|
||||
needs_auth: false,
|
||||
category,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,6 +172,7 @@ pub enum AppToolApproval {
|
||||
pub struct AppsDefaultConfig {
|
||||
#[serde(default = "default_enabled")]
|
||||
pub enabled: bool,
|
||||
pub approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
#[serde(default = "default_enabled")]
|
||||
pub destructive_enabled: bool,
|
||||
#[serde(default = "default_enabled")]
|
||||
|
||||
@@ -1464,6 +1464,9 @@ pub struct ToolRequestUserInputParams {
|
||||
pub turn_id: String,
|
||||
pub item_id: String,
|
||||
pub questions: Vec<ToolRequestUserInputQuestion>,
|
||||
#[serde(default)]
|
||||
#[ts(type = "number | null")]
|
||||
pub auto_resolution_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
|
||||
|
||||
@@ -661,6 +661,7 @@ pub struct AppTemplateSummary {
|
||||
pub template_id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub category: Option<String>,
|
||||
pub canonical_connector_id: Option<String>,
|
||||
pub logo_url: Option<String>,
|
||||
pub logo_url_dark: Option<String>,
|
||||
|
||||
@@ -3,6 +3,26 @@ use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use ts_rs::TS;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct RemoteControlEnableParams {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
pub type NullableRemoteControlEnableParams = Option<RemoteControlEnableParams>;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct RemoteControlDisableParams {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
pub type NullableRemoteControlDisableParams = Option<RemoteControlDisableParams>;
|
||||
|
||||
/// Current remote-control connection status and remote identity exposed to clients.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -68,7 +68,13 @@ pub struct TurnStartParams {
|
||||
#[ts(optional = nullable)]
|
||||
pub client_user_message_id: Option<String>,
|
||||
pub input: Vec<UserInput>,
|
||||
/// Optional turn-scoped Responses API client metadata.
|
||||
/// Optional metadata to enrich Codex's ResponsesAPI turn metadata.
|
||||
///
|
||||
/// Entries are flattened into the JSON string sent as
|
||||
/// `client_metadata["x-codex-turn-metadata"]` on ResponsesAPI HTTP and websocket requests.
|
||||
///
|
||||
/// They are not sent as top-level ResponsesAPI `client_metadata` keys, and reserved keys
|
||||
/// such as `session_id`, `thread_id`, `turn_id`, and `window_id` cannot be overridden.
|
||||
#[experimental("turn/start.responsesapiClientMetadata")]
|
||||
#[ts(optional = nullable)]
|
||||
pub responsesapi_client_metadata: Option<HashMap<String, String>>,
|
||||
@@ -161,7 +167,13 @@ pub struct TurnSteerParams {
|
||||
#[ts(optional = nullable)]
|
||||
pub client_user_message_id: Option<String>,
|
||||
pub input: Vec<UserInput>,
|
||||
/// Optional turn-scoped Responses API client metadata.
|
||||
/// Optional metadata to enrich Codex's ResponsesAPI turn metadata.
|
||||
///
|
||||
/// Entries are flattened into the JSON string sent as
|
||||
/// `client_metadata["x-codex-turn-metadata"]` on ResponsesAPI HTTP and websocket requests.
|
||||
///
|
||||
/// They are not sent as top-level ResponsesAPI `client_metadata` keys, and reserved keys
|
||||
/// such as `session_id`, `thread_id`, `turn_id`, and `window_id` cannot be overridden.
|
||||
#[experimental("turn/steer.responsesapiClientMetadata")]
|
||||
#[ts(optional = nullable)]
|
||||
pub responsesapi_client_metadata: Option<HashMap<String, String>>,
|
||||
|
||||
@@ -11,8 +11,10 @@ pub use transport::AppServerTransport;
|
||||
pub use transport::AppServerTransportParseError;
|
||||
pub use transport::CHANNEL_CAPACITY;
|
||||
pub use transport::ConnectionOrigin;
|
||||
pub use transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
pub use transport::RemoteControlHandle;
|
||||
pub use transport::RemoteControlStartConfig;
|
||||
pub use transport::RemoteControlStartupMode;
|
||||
pub use transport::RemoteControlUnavailable;
|
||||
pub use transport::TransportEvent;
|
||||
pub use transport::acquire_app_server_startup_lock;
|
||||
@@ -24,3 +26,4 @@ pub use transport::start_control_socket_acceptor;
|
||||
pub use transport::start_remote_control;
|
||||
pub use transport::start_stdio_connection;
|
||||
pub use transport::start_websocket_acceptor;
|
||||
pub use transport::take_remote_control_disabled_env;
|
||||
|
||||
@@ -30,10 +30,13 @@ mod unix_socket;
|
||||
mod unix_socket_tests;
|
||||
mod websocket;
|
||||
|
||||
pub use remote_control::REMOTE_CONTROL_DISABLED_ENV_VAR;
|
||||
pub use remote_control::RemoteControlHandle;
|
||||
pub use remote_control::RemoteControlStartConfig;
|
||||
pub use remote_control::RemoteControlStartupMode;
|
||||
pub use remote_control::RemoteControlUnavailable;
|
||||
pub use remote_control::start_remote_control;
|
||||
pub use remote_control::take_remote_control_disabled_env;
|
||||
pub use stdio::start_stdio_connection;
|
||||
pub use unix_socket::AppServerStartupLock;
|
||||
pub use unix_socket::acquire_app_server_startup_lock;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
use super::RemoteControlHandle;
|
||||
use super::RemoteControlUnavailable;
|
||||
use super::enroll::update_persisted_remote_control_enrollment;
|
||||
use super::protocol::normalize_remote_control_url;
|
||||
use super::publish_current_enrollment;
|
||||
use super::websocket::RemoteControlStatusPublisher;
|
||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use std::io;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RemoteControlDesiredState {
|
||||
// `Unknown` exists only on plain startup before auth and enrollment scope resolve. Persisted
|
||||
// `1` is `Enabled { persistence_preference: Some(true) }`; `0`, `NULL`, or no row are
|
||||
// `Disabled`. Runtime-only enable is `Enabled { persistence_preference: None }`, so new rows
|
||||
// keep `NULL`; durable RPC enable uses `Some(true)`, so new rows get `1`. Durable disable writes
|
||||
// `0` before entering `Disabled`; runtime-only disable does not write. `Disabled` carries no
|
||||
// preference because disabled sessions do not create enrollments.
|
||||
Unknown,
|
||||
Disabled,
|
||||
Enabled {
|
||||
persistence_preference: Option<bool>,
|
||||
},
|
||||
}
|
||||
impl RemoteControlDesiredState {
|
||||
pub(super) fn is_enabled(self) -> bool {
|
||||
matches!(self, Self::Enabled { .. })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn acquire_persistence_lock(lock: &Semaphore) -> SemaphorePermit<'_> {
|
||||
lock.acquire().await.unwrap_or_else(|_| unreachable!())
|
||||
}
|
||||
|
||||
pub(super) fn desired_state_from_persisted_enrollment(
|
||||
enrollment: Option<RemoteControlEnrollmentRecord>,
|
||||
) -> RemoteControlDesiredState {
|
||||
if enrollment.and_then(|enrollment| enrollment.remote_control_enabled) == Some(true) {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
}
|
||||
} else {
|
||||
RemoteControlDesiredState::Disabled
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<bool> {
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
if !matches!(
|
||||
*self.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Unknown
|
||||
) {
|
||||
return Ok(self.desired_state_tx.borrow().is_enabled());
|
||||
}
|
||||
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, RemoteControlUnavailable))?;
|
||||
let auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||
let enrollment = state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let desired_state = desired_state_from_persisted_enrollment(enrollment);
|
||||
self.desired_state_tx.send_if_modified(|state| {
|
||||
if !matches!(*state, RemoteControlDesiredState::Unknown) {
|
||||
return false;
|
||||
}
|
||||
*state = desired_state;
|
||||
true
|
||||
});
|
||||
Ok(self.desired_state_tx.borrow().is_enabled())
|
||||
}
|
||||
|
||||
pub async fn enable(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, RemoteControlUnavailable))?;
|
||||
let mut auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||
let app_server_client_name = app_server_client_name.as_deref();
|
||||
let status = self.status();
|
||||
let mut current_enrollment = self.current_enrollment.lock().await;
|
||||
let (enrollment, _) = self
|
||||
.load_or_enroll_server(
|
||||
¤t_enrollment,
|
||||
&mut auth,
|
||||
&status.installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
super::RemoteControlEnrollmentSelection::ReuseOrCreate,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let current_auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||
if current_auth.account_id != auth.account_id {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"remote control account changed during enrollment",
|
||||
));
|
||||
}
|
||||
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
let updated = state_db
|
||||
.set_remote_control_enabled(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
/*remote_control_enabled*/ true,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if updated == 0 {
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
Some(&enrollment),
|
||||
Some(true),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
publish_current_enrollment(&mut current_enrollment, &enrollment);
|
||||
self.enable_with_preference(Some(true))
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?;
|
||||
RemoteControlStatusPublisher::new(self.status_tx.as_ref().clone())
|
||||
.publish_environment_id(Some(enrollment.environment_id));
|
||||
Ok(self.status())
|
||||
}
|
||||
}
|
||||
@@ -286,6 +286,7 @@ pub(super) async fn update_persisted_remote_control_enrollment(
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
enrollment: Option<&RemoteControlEnrollment>,
|
||||
remote_control_enabled: Option<bool>,
|
||||
) -> io::Result<()> {
|
||||
let Some(state_db) = state_db else {
|
||||
return Err(io::Error::new(
|
||||
@@ -316,6 +317,7 @@ pub(super) async fn update_persisted_remote_control_enrollment(
|
||||
server_id: enrollment.server_id.clone(),
|
||||
environment_id: enrollment.environment_id.clone(),
|
||||
server_name: enrollment.server_name.clone(),
|
||||
remote_control_enabled,
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
@@ -648,6 +650,7 @@ mod tests {
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
Some(&first_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("first enrollment should persist");
|
||||
@@ -657,6 +660,7 @@ mod tests {
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
Some(&second_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("second enrollment should persist");
|
||||
@@ -730,6 +734,7 @@ mod tests {
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&first_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("first enrollment should persist");
|
||||
@@ -739,6 +744,7 @@ mod tests {
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&second_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("second enrollment should persist");
|
||||
@@ -749,6 +755,7 @@ mod tests {
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
/*enrollment*/ None,
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("matching enrollment should clear");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod auth;
|
||||
mod client_tracker;
|
||||
mod clients;
|
||||
mod desired_state;
|
||||
mod enroll;
|
||||
mod protocol;
|
||||
mod segment;
|
||||
@@ -8,6 +9,8 @@ mod websocket;
|
||||
|
||||
use self::auth::load_remote_control_auth;
|
||||
use self::auth::recover_remote_control_auth;
|
||||
use self::desired_state::RemoteControlDesiredState;
|
||||
use self::desired_state::acquire_persistence_lock;
|
||||
use self::enroll::RemoteControlEnrollment;
|
||||
use self::enroll::enroll_remote_control_server;
|
||||
use self::enroll::load_persisted_remote_control_enrollment;
|
||||
@@ -63,6 +66,26 @@ pub struct RemoteControlStartConfig {
|
||||
pub installation_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemoteControlStartupMode {
|
||||
ResolvePersisted,
|
||||
DisabledEphemeral,
|
||||
EnabledEphemeral,
|
||||
}
|
||||
|
||||
/// Internal marker used by the daemon to disable remote control without requiring a new CLI flag.
|
||||
pub const REMOTE_CONTROL_DISABLED_ENV_VAR: &str =
|
||||
"CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED";
|
||||
|
||||
/// Reads and removes the daemon's internal disabled-start marker before worker threads start.
|
||||
pub fn take_remote_control_disabled_env() -> bool {
|
||||
let disabled =
|
||||
std::env::var_os(REMOTE_CONTROL_DISABLED_ENV_VAR).is_some_and(|value| value == "1");
|
||||
// SAFETY: app-server calls this synchronously at process startup, before spawning threads.
|
||||
unsafe { std::env::remove_var(REMOTE_CONTROL_DISABLED_ENV_VAR) };
|
||||
disabled
|
||||
}
|
||||
|
||||
pub(super) struct QueuedServerEnvelope {
|
||||
pub(super) event: ServerEvent,
|
||||
pub(super) client_id: ClientId,
|
||||
@@ -72,9 +95,10 @@ pub(super) struct QueuedServerEnvelope {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RemoteControlHandle {
|
||||
enabled_tx: Arc<watch::Sender<bool>>,
|
||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||
desired_state_rpc_lock: Arc<Semaphore>,
|
||||
desired_state_persistence_lock: Arc<Semaphore>,
|
||||
status_tx: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
||||
state_db_available: bool,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
remote_control_url: String,
|
||||
current_enrollment: CurrentRemoteControlEnrollment,
|
||||
@@ -83,11 +107,17 @@ pub struct RemoteControlHandle {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
}
|
||||
|
||||
// Pairing and websocket connect share one selected server so they cannot enroll or clear
|
||||
// Pairing and websocket connect share one selected server so they cannot enroll or replace
|
||||
// different persisted rows while either path is awaiting backend I/O.
|
||||
type CurrentRemoteControlEnrollment = Arc<RemoteControlEnrollmentState>;
|
||||
type RemoteControlPairingPersistenceKey = watch::Sender<Option<String>>;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum RemoteControlEnrollmentSelection {
|
||||
ReuseOrCreate,
|
||||
ReplaceExisting,
|
||||
}
|
||||
|
||||
struct RemoteControlEnrollmentState {
|
||||
enrollment: StdMutex<Option<RemoteControlEnrollment>>,
|
||||
lock: Semaphore,
|
||||
@@ -166,23 +196,45 @@ impl fmt::Display for RemoteControlUnavailable {
|
||||
impl Error for RemoteControlUnavailable {}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
pub fn enable(
|
||||
pub fn enable_ephemeral(
|
||||
&self,
|
||||
) -> Result<RemoteControlStatusChangedNotification, RemoteControlUnavailable> {
|
||||
if !self.state_db_available {
|
||||
self.enable_with_preference(/*persistence_preference*/ None)
|
||||
}
|
||||
|
||||
fn enable_with_preference(
|
||||
&self,
|
||||
persistence_preference: Option<bool>,
|
||||
) -> Result<RemoteControlStatusChangedNotification, RemoteControlUnavailable> {
|
||||
if self.state_db.is_none() {
|
||||
warn!("remote control cannot be enabled because sqlite state db is unavailable");
|
||||
return Err(RemoteControlUnavailable);
|
||||
}
|
||||
|
||||
let enabled_changed = self.enabled_tx.send_if_modified(|state| {
|
||||
let changed = !*state;
|
||||
*state = true;
|
||||
let mut effective_persistence_preference = persistence_preference;
|
||||
let desired_state_changed = self.desired_state_tx.send_if_modified(|state| {
|
||||
if effective_persistence_preference.is_none()
|
||||
&& matches!(
|
||||
*state,
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true)
|
||||
}
|
||||
)
|
||||
{
|
||||
effective_persistence_preference = Some(true);
|
||||
}
|
||||
let next_state = RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: effective_persistence_preference,
|
||||
};
|
||||
let changed = *state != next_state;
|
||||
*state = next_state;
|
||||
changed
|
||||
});
|
||||
|
||||
let status = self.status();
|
||||
info!(
|
||||
enabled_changed,
|
||||
desired_state_changed,
|
||||
?effective_persistence_preference,
|
||||
current_status = ?status.status,
|
||||
environment_id = ?status.environment_id,
|
||||
installation_id = %status.installation_id,
|
||||
@@ -199,15 +251,43 @@ impl RemoteControlHandle {
|
||||
Ok(self.publish_status(RemoteControlConnectionStatus::Connecting))
|
||||
}
|
||||
|
||||
pub fn disable(&self) -> RemoteControlStatusChangedNotification {
|
||||
let enabled_changed = self.enabled_tx.send_if_modified(|state| {
|
||||
let changed = *state;
|
||||
*state = false;
|
||||
pub async fn disable(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
self.persist_preference(
|
||||
app_server_client_name,
|
||||
/*remote_control_enabled*/ false,
|
||||
)
|
||||
.await?;
|
||||
Ok(self.transition_disabled())
|
||||
}
|
||||
|
||||
pub async fn disable_ephemeral(&self) -> RemoteControlStatusChangedNotification {
|
||||
let _transition = self
|
||||
.desired_state_rpc_lock
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
self.transition_disabled()
|
||||
}
|
||||
|
||||
fn transition_disabled(&self) -> RemoteControlStatusChangedNotification {
|
||||
let desired_state_changed = self.desired_state_tx.send_if_modified(|state| {
|
||||
let changed = *state != RemoteControlDesiredState::Disabled;
|
||||
*state = RemoteControlDesiredState::Disabled;
|
||||
changed
|
||||
});
|
||||
let status = self.status();
|
||||
info!(
|
||||
enabled_changed,
|
||||
desired_state_changed,
|
||||
current_status = ?status.status,
|
||||
environment_id = ?status.environment_id,
|
||||
installation_id = %status.installation_id,
|
||||
@@ -217,6 +297,30 @@ impl RemoteControlHandle {
|
||||
self.publish_status(RemoteControlConnectionStatus::Disabled)
|
||||
}
|
||||
|
||||
async fn persist_preference(
|
||||
&self,
|
||||
app_server_client_name: Option<&str>,
|
||||
remote_control_enabled: bool,
|
||||
) -> io::Result<()> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, RemoteControlUnavailable))?;
|
||||
let auth = load_remote_control_auth(&self.auth_manager).await?;
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||
state_db
|
||||
.set_remote_control_enabled(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name.as_deref(),
|
||||
remote_control_enabled,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn status(&self) -> RemoteControlStatusChangedNotification {
|
||||
self.status_tx.borrow().clone()
|
||||
}
|
||||
@@ -230,6 +334,9 @@ impl RemoteControlHandle {
|
||||
params: RemoteControlPairingStartParams,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||
if !self.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(Self::pairing_disabled_error());
|
||||
}
|
||||
let mut auth = load_remote_control_auth(&self.auth_manager)
|
||||
.await
|
||||
.map_err(|_| pairing_unavailable_error())?;
|
||||
@@ -245,19 +352,35 @@ impl RemoteControlHandle {
|
||||
&installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
RemoteControlEnrollmentSelection::ReuseOrCreate,
|
||||
)
|
||||
.await?;
|
||||
if enrollment.should_refresh_server_token() {
|
||||
refresh_pairing_enrollment(
|
||||
let refresh_result = refresh_pairing_enrollment(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
app_server_client_name,
|
||||
&self.auth_manager,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&mut enrollment,
|
||||
)
|
||||
.await?;
|
||||
.await;
|
||||
if refresh_result
|
||||
.as_ref()
|
||||
.is_err_and(|err| err.kind() == io::ErrorKind::NotFound)
|
||||
{
|
||||
enrollment = self
|
||||
.load_or_enroll_pairing_server(
|
||||
&mut current_enrollment,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
refresh_result?;
|
||||
}
|
||||
}
|
||||
let pairing_request = || protocol::StartRemoteControlPairingRequest {
|
||||
manual_code: params.manual_code,
|
||||
@@ -267,8 +390,6 @@ impl RemoteControlHandle {
|
||||
clear_pairing_server_token(&mut current_enrollment, &mut enrollment)?;
|
||||
refresh_pairing_enrollment(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
app_server_client_name,
|
||||
&self.auth_manager,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
@@ -278,13 +399,6 @@ impl RemoteControlHandle {
|
||||
enrollment.start_pairing(pairing_request()).await
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
clear_pairing_enrollment(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
app_server_client_name,
|
||||
&enrollment,
|
||||
)
|
||||
.await;
|
||||
enrollment = self
|
||||
.load_or_enroll_pairing_server(
|
||||
&mut current_enrollment,
|
||||
@@ -292,6 +406,7 @@ impl RemoteControlHandle {
|
||||
&installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await?;
|
||||
enrollment.start_pairing(pairing_request()).await
|
||||
@@ -301,13 +416,15 @@ impl RemoteControlHandle {
|
||||
if let Err(err) = &pairing_response {
|
||||
match err.kind() {
|
||||
io::ErrorKind::NotFound => {
|
||||
clear_pairing_enrollment(
|
||||
self.load_or_enroll_pairing_server(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&status.server_name,
|
||||
app_server_client_name,
|
||||
&enrollment,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
io::ErrorKind::PermissionDenied => {
|
||||
@@ -323,6 +440,9 @@ impl RemoteControlHandle {
|
||||
if current_auth.account_id != auth.account_id {
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
if !self.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(Self::pairing_disabled_error());
|
||||
}
|
||||
pairing_response
|
||||
}
|
||||
|
||||
@@ -333,31 +453,86 @@ impl RemoteControlHandle {
|
||||
installation_id: &str,
|
||||
server_name: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
selection: RemoteControlEnrollmentSelection,
|
||||
) -> io::Result<RemoteControlEnrollment> {
|
||||
if let Some(enrollment) = current_enrollment
|
||||
.as_ref()
|
||||
.filter(|enrollment| enrollment.account_id == auth.account_id)
|
||||
.cloned()
|
||||
{
|
||||
let (enrollment, created) = self
|
||||
.load_or_enroll_server(
|
||||
current_enrollment,
|
||||
auth,
|
||||
installation_id,
|
||||
server_name,
|
||||
app_server_client_name,
|
||||
selection,
|
||||
)
|
||||
.await?;
|
||||
if !created {
|
||||
publish_current_enrollment(current_enrollment, &enrollment);
|
||||
return Ok(enrollment);
|
||||
}
|
||||
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
if let Some(mut enrollment) = load_persisted_remote_control_enrollment(
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
let persistence_preference = match *self.desired_state_tx.borrow() {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference,
|
||||
} => persistence_preference,
|
||||
RemoteControlDesiredState::Unknown | RemoteControlDesiredState::Disabled => {
|
||||
return Err(Self::pairing_disabled_error());
|
||||
}
|
||||
};
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
&remote_control_target,
|
||||
&enrollment.remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
Some(&enrollment),
|
||||
persistence_preference,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
enrollment.server_name = server_name.to_string();
|
||||
publish_current_enrollment(current_enrollment, &enrollment);
|
||||
return Ok(enrollment);
|
||||
.await?;
|
||||
publish_current_enrollment(current_enrollment, &enrollment);
|
||||
Ok(enrollment)
|
||||
}
|
||||
|
||||
async fn load_or_enroll_server(
|
||||
&self,
|
||||
current_enrollment: &Option<RemoteControlEnrollment>,
|
||||
auth: &mut auth::RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
server_name: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
selection: RemoteControlEnrollmentSelection,
|
||||
) -> io::Result<(RemoteControlEnrollment, bool)> {
|
||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||
match selection {
|
||||
RemoteControlEnrollmentSelection::ReuseOrCreate => {
|
||||
if let Some(enrollment) = current_enrollment
|
||||
.as_ref()
|
||||
.filter(|enrollment| enrollment.account_id == auth.account_id)
|
||||
.cloned()
|
||||
{
|
||||
return Ok((enrollment, false));
|
||||
}
|
||||
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
if let Some(mut enrollment) = load_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
enrollment.server_name = server_name.to_string();
|
||||
return Ok((enrollment, false));
|
||||
}
|
||||
}
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting => {}
|
||||
}
|
||||
|
||||
let enrollment = enroll_pairing_server(
|
||||
@@ -368,16 +543,7 @@ impl RemoteControlHandle {
|
||||
server_name,
|
||||
)
|
||||
.await?;
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
Some(&enrollment),
|
||||
)
|
||||
.await?;
|
||||
publish_current_enrollment(current_enrollment, &enrollment);
|
||||
Ok(enrollment)
|
||||
Ok((enrollment, true))
|
||||
}
|
||||
|
||||
fn pairing_persistence_key(
|
||||
@@ -398,7 +564,7 @@ impl RemoteControlHandle {
|
||||
&self,
|
||||
params: RemoteControlPairingStatusParams,
|
||||
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||
if !*self.enabled_tx.borrow() {
|
||||
if !self.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(Self::pairing_disabled_error());
|
||||
}
|
||||
let mut auth = load_remote_control_auth(&self.auth_manager)
|
||||
@@ -412,18 +578,34 @@ impl RemoteControlHandle {
|
||||
.filter(|enrollment| enrollment.account_id == auth.account_id)
|
||||
.cloned()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
let installation_id = self.status().installation_id;
|
||||
let status = self.status();
|
||||
let installation_id = status.installation_id;
|
||||
let server_name = status.server_name;
|
||||
if enrollment.should_refresh_server_token() {
|
||||
refresh_pairing_enrollment(
|
||||
let refresh_result = refresh_pairing_enrollment(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
app_server_client_name,
|
||||
&self.auth_manager,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&mut enrollment,
|
||||
)
|
||||
.await?;
|
||||
.await;
|
||||
if refresh_result
|
||||
.as_ref()
|
||||
.is_err_and(|err| err.kind() == io::ErrorKind::NotFound)
|
||||
{
|
||||
self.load_or_enroll_pairing_server(
|
||||
&mut current_enrollment,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&server_name,
|
||||
app_server_client_name,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await?;
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
refresh_result?;
|
||||
}
|
||||
let status_code = remote_control_pairing_status_code(¶ms)?;
|
||||
let pairing_status_request =
|
||||
@@ -434,8 +616,6 @@ impl RemoteControlHandle {
|
||||
clear_pairing_server_token(&mut current_enrollment, &mut enrollment)?;
|
||||
refresh_pairing_enrollment(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
app_server_client_name,
|
||||
&self.auth_manager,
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
@@ -449,13 +629,15 @@ impl RemoteControlHandle {
|
||||
if let Err(err) = &pairing_status_response {
|
||||
match err.kind() {
|
||||
io::ErrorKind::NotFound => {
|
||||
clear_pairing_enrollment(
|
||||
self.load_or_enroll_pairing_server(
|
||||
&mut current_enrollment,
|
||||
self.state_db.as_deref(),
|
||||
&mut auth,
|
||||
&installation_id,
|
||||
&server_name,
|
||||
app_server_client_name,
|
||||
&enrollment,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
io::ErrorKind::PermissionDenied => {
|
||||
@@ -465,7 +647,7 @@ impl RemoteControlHandle {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !*self.enabled_tx.borrow() {
|
||||
if !self.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(Self::pairing_disabled_error());
|
||||
}
|
||||
let current_auth = load_remote_control_auth(&self.auth_manager)
|
||||
@@ -580,8 +762,6 @@ fn remote_control_pairing_status_code(
|
||||
|
||||
async fn refresh_pairing_enrollment(
|
||||
current_enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
state_db: Option<&StateRuntime>,
|
||||
app_server_client_name: Option<&str>,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth: &mut auth::RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
@@ -589,14 +769,7 @@ async fn refresh_pairing_enrollment(
|
||||
) -> io::Result<()> {
|
||||
if let Err(err) = refresh_remote_control_server(auth, installation_id, enrollment).await {
|
||||
if err.kind() != io::ErrorKind::PermissionDenied {
|
||||
return handle_pairing_refresh_error(
|
||||
current_enrollment,
|
||||
state_db,
|
||||
app_server_client_name,
|
||||
enrollment,
|
||||
err,
|
||||
)
|
||||
.await;
|
||||
return Err(err);
|
||||
}
|
||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||
@@ -609,16 +782,7 @@ async fn refresh_pairing_enrollment(
|
||||
if auth.account_id != enrollment.account_id {
|
||||
return Err(pairing_unavailable_error());
|
||||
}
|
||||
if let Err(err) = refresh_remote_control_server(auth, installation_id, enrollment).await {
|
||||
return handle_pairing_refresh_error(
|
||||
current_enrollment,
|
||||
state_db,
|
||||
app_server_client_name,
|
||||
enrollment,
|
||||
err,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
refresh_remote_control_server(auth, installation_id, enrollment).await?
|
||||
}
|
||||
if replace_current_enrollment(current_enrollment, enrollment) {
|
||||
Ok(())
|
||||
@@ -627,52 +791,6 @@ async fn refresh_pairing_enrollment(
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_pairing_refresh_error(
|
||||
current_enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
state_db: Option<&StateRuntime>,
|
||||
app_server_client_name: Option<&str>,
|
||||
enrollment: &RemoteControlEnrollment,
|
||||
err: io::Error,
|
||||
) -> io::Result<()> {
|
||||
if err.kind() == io::ErrorKind::NotFound {
|
||||
clear_pairing_enrollment(
|
||||
current_enrollment,
|
||||
state_db,
|
||||
app_server_client_name,
|
||||
enrollment,
|
||||
)
|
||||
.await;
|
||||
Err(pairing_unavailable_error())
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
async fn clear_pairing_enrollment(
|
||||
current_enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
state_db: Option<&StateRuntime>,
|
||||
app_server_client_name: Option<&str>,
|
||||
enrollment: &RemoteControlEnrollment,
|
||||
) {
|
||||
if !clear_current_enrollment_if_matches(current_enrollment, enrollment) {
|
||||
return;
|
||||
}
|
||||
let Some(state_db) = state_db else {
|
||||
return;
|
||||
};
|
||||
if let Err(err) = update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
&enrollment.remote_control_target,
|
||||
&enrollment.account_id,
|
||||
app_server_client_name,
|
||||
/*enrollment*/ None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to clear stale pairing enrollment: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_pairing_server_token(
|
||||
current_enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
enrollment: &mut RemoteControlEnrollment,
|
||||
@@ -729,21 +847,6 @@ fn replace_current_enrollment(
|
||||
true
|
||||
}
|
||||
|
||||
fn clear_current_enrollment_if_matches(
|
||||
current_enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
enrollment: &RemoteControlEnrollment,
|
||||
) -> bool {
|
||||
if current_enrollment
|
||||
.as_ref()
|
||||
.is_some_and(|current| same_remote_control_enrollment(current, enrollment))
|
||||
{
|
||||
*current_enrollment = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn same_remote_control_enrollment(
|
||||
left: &RemoteControlEnrollment,
|
||||
right: &RemoteControlEnrollment,
|
||||
@@ -762,11 +865,22 @@ pub async fn start_remote_control(
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown_token: CancellationToken,
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
initial_enabled: bool,
|
||||
startup_mode: RemoteControlStartupMode,
|
||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||
let state_db_available = state_db.is_some();
|
||||
let requested_initial_enabled = initial_enabled;
|
||||
let initial_enabled = initial_enabled && state_db_available;
|
||||
let requested_initial_enabled = startup_mode == RemoteControlStartupMode::EnabledEphemeral;
|
||||
let desired_state = if !state_db_available {
|
||||
RemoteControlDesiredState::Disabled
|
||||
} else {
|
||||
match startup_mode {
|
||||
RemoteControlStartupMode::ResolvePersisted => RemoteControlDesiredState::Unknown,
|
||||
RemoteControlStartupMode::DisabledEphemeral => RemoteControlDesiredState::Disabled,
|
||||
RemoteControlStartupMode::EnabledEphemeral => RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
},
|
||||
}
|
||||
};
|
||||
let initial_enabled = desired_state.is_enabled();
|
||||
if requested_initial_enabled && !state_db_available {
|
||||
warn!("remote control disabled because sqlite state db is unavailable");
|
||||
}
|
||||
@@ -776,7 +890,12 @@ pub async fn start_remote_control(
|
||||
None
|
||||
};
|
||||
|
||||
let (enabled_tx, enabled_rx) = watch::channel(initial_enabled);
|
||||
let (desired_state_tx, _desired_state_rx) = watch::channel(desired_state);
|
||||
let desired_state_tx = Arc::new(desired_state_tx);
|
||||
let desired_state_rpc_lock = Arc::new(Semaphore::new(1));
|
||||
let desired_state_persistence_lock = Arc::new(Semaphore::new(1));
|
||||
let websocket_desired_state_tx = desired_state_tx.clone();
|
||||
let websocket_desired_state_persistence_lock = desired_state_persistence_lock.clone();
|
||||
let current_enrollment = Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None));
|
||||
let websocket_current_enrollment = current_enrollment.clone();
|
||||
let pairing_persistence_key_required = app_server_client_name_rx.is_some();
|
||||
@@ -804,7 +923,7 @@ pub async fn start_remote_control(
|
||||
installation_id = %installation_id,
|
||||
server_name = %server_name,
|
||||
state_db_available,
|
||||
initial_enabled,
|
||||
?desired_state,
|
||||
"starting app-server remote control websocket task"
|
||||
);
|
||||
let remote_control_url_for_log = remote_control_url.clone();
|
||||
@@ -817,7 +936,7 @@ pub async fn start_remote_control(
|
||||
remote_control_url = %remote_control_url_for_log,
|
||||
installation_id = %installation_id_for_log,
|
||||
server_name = %server_name_for_log,
|
||||
initial_enabled,
|
||||
?desired_state,
|
||||
"app-server remote control websocket task started"
|
||||
);
|
||||
let websocket_task = RemoteControlWebsocket::new(
|
||||
@@ -834,9 +953,10 @@ pub async fn start_remote_control(
|
||||
status_publisher,
|
||||
current_enrollment: websocket_current_enrollment,
|
||||
pairing_persistence_key: websocket_pairing_persistence_key,
|
||||
desired_state_persistence_lock: websocket_desired_state_persistence_lock,
|
||||
},
|
||||
shutdown_token,
|
||||
enabled_rx,
|
||||
websocket_desired_state_tx,
|
||||
)
|
||||
.run(app_server_client_name_rx);
|
||||
match AssertUnwindSafe(websocket_task).catch_unwind().await {
|
||||
@@ -875,9 +995,10 @@ pub async fn start_remote_control(
|
||||
Ok((
|
||||
join_handle,
|
||||
RemoteControlHandle {
|
||||
enabled_tx: Arc::new(enabled_tx),
|
||||
desired_state_tx,
|
||||
desired_state_rpc_lock,
|
||||
desired_state_persistence_lock,
|
||||
status_tx: Arc::new(status_tx),
|
||||
state_db_available,
|
||||
state_db: handle_state_db,
|
||||
remote_control_url: handle_remote_control_url,
|
||||
current_enrollment,
|
||||
|
||||
@@ -9,6 +9,8 @@ use super::protocol::ClientId;
|
||||
use super::protocol::StreamId;
|
||||
use super::protocol::normalize_remote_control_url;
|
||||
use super::websocket::REMOTE_CONTROL_PROTOCOL_VERSION;
|
||||
use super::websocket::RemoteControlWebsocket;
|
||||
use super::websocket::RemoteControlWebsocketConfig;
|
||||
use super::*;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::outgoing_message::QueuedOutgoingMessage;
|
||||
@@ -33,6 +35,7 @@ use codex_login::CodexAuth;
|
||||
use codex_login::save_auth;
|
||||
use codex_login::token_data::TokenData;
|
||||
use codex_login::token_data::parse_chatgpt_jwt_claims;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use codex_state::StateRuntime;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
@@ -116,6 +119,7 @@ fn remote_control_auth_dot_json(account_id: Option<&str>) -> AuthDotJson {
|
||||
last_refresh: Some(chrono::Utc::now()),
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +129,137 @@ async fn remote_control_state_runtime(codex_home: &TempDir) -> Arc<StateRuntime>
|
||||
.expect("state runtime should initialize")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plain_start_resolves_persisted_remote_control_preference() {
|
||||
let cases = [
|
||||
("enabled", Some(Some(true))),
|
||||
("disabled", Some(Some(false))),
|
||||
("unset", Some(None)),
|
||||
("missing", None),
|
||||
];
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let remote_control_target = normalize_remote_control_url(TEST_REMOTE_CONTROL_URL)
|
||||
.expect("remote control target should normalize");
|
||||
for (name, stored_preference) in cases {
|
||||
let Some(remote_control_enabled) = stored_preference else {
|
||||
continue;
|
||||
};
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url.clone(),
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: Some(name.to_string()),
|
||||
server_id: format!("server-{name}"),
|
||||
environment_id: format!("environment-{name}"),
|
||||
server_name: format!("server-name-{name}"),
|
||||
remote_control_enabled,
|
||||
})
|
||||
.await
|
||||
.expect("enrollment should persist");
|
||||
}
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: test_server_name(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
environment_id: None,
|
||||
});
|
||||
let (desired_state_tx, _desired_state_rx) = watch::channel(RemoteControlDesiredState::Unknown);
|
||||
let desired_state_tx = Arc::new(desired_state_tx);
|
||||
let mut websocket = RemoteControlWebsocket::new(
|
||||
RemoteControlWebsocketConfig {
|
||||
remote_control_url: TEST_REMOTE_CONTROL_URL.to_string(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
remote_control_target: None,
|
||||
server_name: test_server_name(),
|
||||
},
|
||||
Some(state_db),
|
||||
remote_control_auth_manager(),
|
||||
RemoteControlChannels {
|
||||
transport_event_tx,
|
||||
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
||||
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(
|
||||
/*enrollment*/ None,
|
||||
)),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
desired_state_tx.clone(),
|
||||
);
|
||||
|
||||
for (name, stored_preference) in cases {
|
||||
desired_state_tx.send_replace(RemoteControlDesiredState::Unknown);
|
||||
assert!(websocket.resolve_unknown_desired_state(Some(name)).await);
|
||||
let expected = if stored_preference == Some(Some(true)) {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
}
|
||||
} else {
|
||||
RemoteControlDesiredState::Disabled
|
||||
};
|
||||
assert_eq!(*desired_state_tx.borrow(), expected, "case {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_disabled_start_ignores_persisted_enable() {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let remote_control_target = normalize_remote_control_url(TEST_REMOTE_CONTROL_URL)
|
||||
.expect("remote control target should normalize");
|
||||
let enrollment = RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: "server-id".to_string(),
|
||||
environment_id: "environment-id".to_string(),
|
||||
server_name: "server-name".to_string(),
|
||||
remote_control_enabled: Some(true),
|
||||
};
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&enrollment)
|
||||
.await
|
||||
.expect("enrollment should persist");
|
||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
RemoteControlStartConfig {
|
||||
remote_control_url: TEST_REMOTE_CONTROL_URL.to_string(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
},
|
||||
Some(state_db.clone()),
|
||||
remote_control_auth_manager(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
RemoteControlStartupMode::DisabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start disabled");
|
||||
|
||||
assert_eq!(
|
||||
*remote_handle.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Disabled
|
||||
);
|
||||
assert_eq!(
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&enrollment.websocket_url,
|
||||
&enrollment.account_id,
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("enrollment should load"),
|
||||
Some(enrollment)
|
||||
);
|
||||
|
||||
shutdown_token.cancel();
|
||||
remote_task.await.expect("remote control task should join");
|
||||
}
|
||||
|
||||
fn remote_control_url_for_listener(listener: &TcpListener) -> String {
|
||||
let addr = listener
|
||||
.local_addr()
|
||||
@@ -140,7 +275,10 @@ fn remote_control_handle_with_current_enrollment(
|
||||
remote_control_url: &str,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> RemoteControlHandle {
|
||||
let (enabled_tx, _enabled_rx) = watch::channel(/*init*/ true);
|
||||
let (desired_state_tx, _desired_state_rx) =
|
||||
watch::channel(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
});
|
||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Connecting,
|
||||
server_name: test_server_name(),
|
||||
@@ -164,9 +302,10 @@ fn remote_control_handle_with_current_enrollment(
|
||||
},
|
||||
)));
|
||||
RemoteControlHandle {
|
||||
enabled_tx: Arc::new(enabled_tx),
|
||||
desired_state_tx: Arc::new(desired_state_tx),
|
||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
status_tx: Arc::new(status_tx),
|
||||
state_db_available: true,
|
||||
state_db: None,
|
||||
remote_control_url: remote_control_url.to_string(),
|
||||
current_enrollment,
|
||||
@@ -176,6 +315,44 @@ fn remote_control_handle_with_current_enrollment(
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ephemeral_enable_preserves_durable_preference() {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let mut remote_handle = remote_control_handle_with_current_enrollment(
|
||||
TEST_REMOTE_CONTROL_URL,
|
||||
remote_control_auth_manager(),
|
||||
);
|
||||
remote_handle.state_db = Some(remote_control_state_runtime(&codex_home).await);
|
||||
remote_handle
|
||||
.desired_state_tx
|
||||
.send_replace(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
});
|
||||
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect("ephemeral enable should succeed");
|
||||
assert_eq!(
|
||||
*remote_handle.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
}
|
||||
);
|
||||
|
||||
remote_handle
|
||||
.desired_state_tx
|
||||
.send_replace(RemoteControlDesiredState::Disabled);
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect("ephemeral enable should succeed");
|
||||
assert_eq!(
|
||||
*remote_handle.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn remote_control_server_token_response(
|
||||
server_id: &str,
|
||||
environment_id: &str,
|
||||
@@ -241,7 +418,10 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages()
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let remote_control_target = normalize_remote_control_url(&remote_control_url)
|
||||
.expect("remote control target should normalize");
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let (transport_event_tx, mut transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
@@ -250,12 +430,12 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages()
|
||||
remote_control_url,
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
},
|
||||
Some(remote_control_state_runtime(&codex_home).await),
|
||||
Some(state_db.clone()),
|
||||
remote_control_auth_manager(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -275,6 +455,16 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages()
|
||||
)
|
||||
.await;
|
||||
let mut websocket = accept_remote_control_connection(&listener).await;
|
||||
let enrollment = state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("new enrollment should load")
|
||||
.expect("new enrollment should exist");
|
||||
assert_eq!(enrollment.remote_control_enabled, None);
|
||||
expect_remote_control_status(
|
||||
&mut status_rx,
|
||||
/*expected_status*/ None,
|
||||
@@ -538,7 +728,7 @@ async fn remote_control_transport_reconnects_after_disconnect() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -639,7 +829,7 @@ async fn remote_control_transport_refreshes_server_token_after_websocket_unautho
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -719,7 +909,7 @@ async fn remote_control_start_allows_remote_control_invalid_url_when_disabled()
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ false,
|
||||
RemoteControlStartupMode::ResolvePersisted,
|
||||
)
|
||||
.await
|
||||
.expect("disabled remote control should not validate the URL at startup");
|
||||
@@ -758,7 +948,7 @@ async fn remote_control_start_allows_missing_auth_when_enabled() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start before ChatGPT auth is available");
|
||||
@@ -793,7 +983,7 @@ async fn remote_control_start_reports_missing_state_db_as_disabled_when_enabled(
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start disabled without sqlite state db");
|
||||
@@ -813,7 +1003,9 @@ async fn remote_control_start_reports_missing_state_db_as_disabled_when_enabled(
|
||||
.expect_err("remote control should not connect without sqlite state db");
|
||||
|
||||
assert_eq!(
|
||||
remote_handle.enable().expect_err("enable should fail"),
|
||||
remote_handle
|
||||
.enable_ephemeral()
|
||||
.expect_err("enable should fail"),
|
||||
super::RemoteControlUnavailable
|
||||
);
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
@@ -850,7 +1042,7 @@ async fn remote_control_handle_enable_disable_stops_and_restarts_connections() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -883,7 +1075,10 @@ async fn remote_control_handle_enable_disable_stops_and_restarts_connections() {
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
remote_handle.disable(),
|
||||
remote_handle
|
||||
.disable(Some("rpc-client"))
|
||||
.await
|
||||
.expect("disable should succeed"),
|
||||
RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: test_server_name(),
|
||||
@@ -909,12 +1104,15 @@ async fn remote_control_handle_enable_disable_stops_and_restarts_connections() {
|
||||
.expect_err("disabled remote control should not reconnect");
|
||||
|
||||
assert_eq!(
|
||||
remote_handle.enable().expect("enable should succeed"),
|
||||
remote_handle
|
||||
.enable(Some("rpc-client"))
|
||||
.await
|
||||
.expect("enable should succeed"),
|
||||
RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Connecting,
|
||||
server_name: test_server_name(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
environment_id: None,
|
||||
environment_id: Some("env_test".to_string()),
|
||||
}
|
||||
);
|
||||
expect_remote_control_status_snapshot(
|
||||
@@ -923,7 +1121,7 @@ async fn remote_control_handle_enable_disable_stops_and_restarts_connections() {
|
||||
status: RemoteControlConnectionStatus::Connecting,
|
||||
server_name: test_server_name(),
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
environment_id: None,
|
||||
environment_id: Some("env_test".to_string()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -963,7 +1161,7 @@ async fn remote_control_transport_clears_outgoing_buffer_when_backend_acks() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1145,7 +1343,7 @@ async fn remote_control_http_mode_enrolls_before_connecting() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1375,6 +1573,7 @@ async fn remote_control_http_mode_refreshes_persisted_enrollment_before_connecti
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&persisted_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("persisted enrollment should save");
|
||||
@@ -1392,7 +1591,7 @@ async fn remote_control_http_mode_refreshes_persisted_enrollment_before_connecti
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1481,6 +1680,7 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() {
|
||||
"account_id",
|
||||
Some(app_server_client_name),
|
||||
Some(&persisted_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("persisted enrollment should save");
|
||||
@@ -1499,7 +1699,7 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
Some(app_server_client_name_rx),
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1580,7 +1780,7 @@ async fn remote_control_waits_for_account_id_before_enrolling() {
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start before account id is available");
|
||||
@@ -1624,6 +1824,123 @@ async fn remote_control_waits_for_account_id_before_enrolling() {
|
||||
let _ = remote_task.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_enable_does_not_follow_auth_to_an_account_without_a_preference() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&remote_control_auth_dot_json(Some("account_a")),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)
|
||||
.expect("account A auth should save");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let auth_manager = AuthManager::shared(
|
||||
codex_home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*chatgpt_base_url*/ None,
|
||||
)
|
||||
.await;
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: remote_control_target.clone(),
|
||||
account_id: "account_a".to_string(),
|
||||
environment_id: "env_a".to_string(),
|
||||
server_id: "srv_e_a".to_string(),
|
||||
server_name: "server-a".to_string(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
};
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&remote_control_target,
|
||||
"account_a",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&enrollment),
|
||||
/*remote_control_enabled*/ Some(true),
|
||||
)
|
||||
.await
|
||||
.expect("account A enrollment should save");
|
||||
|
||||
let (transport_event_tx, _transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
RemoteControlStartConfig {
|
||||
remote_control_url,
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
},
|
||||
Some(state_db.clone()),
|
||||
auth_manager.clone(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
RemoteControlStartupMode::ResolvePersisted,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
|
||||
let refresh_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
refresh_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_json(
|
||||
refresh_request.stream,
|
||||
remote_control_server_token_response(
|
||||
&enrollment.server_id,
|
||||
&enrollment.environment_id,
|
||||
TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let (_handshake_request, mut websocket) =
|
||||
accept_remote_control_backend_connection(&listener).await;
|
||||
|
||||
save_auth(
|
||||
codex_home.path(),
|
||||
&remote_control_auth_dot_json(Some("account_b")),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)
|
||||
.expect("account B auth should save");
|
||||
auth_manager.reload().await;
|
||||
websocket
|
||||
.close(None)
|
||||
.await
|
||||
.expect("backend websocket should close");
|
||||
|
||||
let mut desired_state_rx = remote_handle.desired_state_tx.subscribe();
|
||||
timeout(
|
||||
Duration::from_secs(1),
|
||||
desired_state_rx.wait_for(|state| *state == RemoteControlDesiredState::Disabled),
|
||||
)
|
||||
.await
|
||||
.expect("account B missing preference should disable remote control")
|
||||
.expect("desired state channel should stay open");
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("disabled account B should not enroll");
|
||||
assert_eq!(
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_b",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("account B enrollment should load"),
|
||||
None
|
||||
);
|
||||
|
||||
shutdown_token.cancel();
|
||||
let _ = remote_task.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollment() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
@@ -1659,6 +1976,7 @@ async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollmen
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&stale_enrollment),
|
||||
/*remote_control_enabled*/ Some(true),
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should save");
|
||||
@@ -1676,7 +1994,7 @@ async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollmen
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::ResolvePersisted,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1694,12 +2012,6 @@ async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollmen
|
||||
)
|
||||
.await;
|
||||
respond_with_status(refresh_request.stream, "404 Not Found", "").await;
|
||||
expect_remote_control_status(
|
||||
&mut status_rx,
|
||||
/*expected_status*/ None,
|
||||
/*expected_environment_id*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let enroll_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
@@ -1728,15 +2040,23 @@ async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollmen
|
||||
Some(&refreshed_enrollment.server_id)
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&remote_control_target,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(refreshed_enrollment)
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url.clone(),
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: refreshed_enrollment.server_id.clone(),
|
||||
environment_id: refreshed_enrollment.environment_id.clone(),
|
||||
server_name: refreshed_enrollment.server_name.clone(),
|
||||
remote_control_enabled: Some(true),
|
||||
})
|
||||
);
|
||||
|
||||
shutdown_token.cancel();
|
||||
@@ -1778,6 +2098,7 @@ async fn remote_control_http_mode_reenrolls_after_explicit_missing_server_404()
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&stale_enrollment),
|
||||
/*remote_control_enabled*/ Some(true),
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should save");
|
||||
@@ -1795,7 +2116,7 @@ async fn remote_control_http_mode_reenrolls_after_explicit_missing_server_404()
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::ResolvePersisted,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
@@ -1837,12 +2158,6 @@ async fn remote_control_http_mode_reenrolls_after_explicit_missing_server_404()
|
||||
&json!({"detail": "Remote app server not found"}).to_string(),
|
||||
)
|
||||
.await;
|
||||
expect_remote_control_status(
|
||||
&mut status_rx,
|
||||
/*expected_status*/ None,
|
||||
/*expected_environment_id*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let enroll_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
@@ -1871,15 +2186,125 @@ async fn remote_control_http_mode_reenrolls_after_explicit_missing_server_404()
|
||||
Some(&refreshed_enrollment.server_id)
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&remote_control_target,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url.clone(),
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: refreshed_enrollment.server_id.clone(),
|
||||
environment_id: refreshed_enrollment.environment_id.clone(),
|
||||
server_name: refreshed_enrollment.server_name.clone(),
|
||||
remote_control_enabled: Some(true),
|
||||
})
|
||||
);
|
||||
|
||||
shutdown_token.cancel();
|
||||
let _ = remote_task.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_http_mode_preserves_stale_enrollment_when_reenrollment_fails() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(refreshed_enrollment)
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
let remote_control_target =
|
||||
normalize_remote_control_url(&remote_control_url).expect("target should parse");
|
||||
let stale_enrollment = RemoteControlEnrollment {
|
||||
remote_control_target: remote_control_target.clone(),
|
||||
account_id: "account_id".to_string(),
|
||||
environment_id: "env_stale".to_string(),
|
||||
server_id: "srv_e_stale".to_string(),
|
||||
server_name: test_server_name(),
|
||||
remote_control_token: None,
|
||||
expires_at: None,
|
||||
};
|
||||
update_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&remote_control_target,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&stale_enrollment),
|
||||
/*remote_control_enabled*/ Some(true),
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should save");
|
||||
|
||||
let (transport_event_tx, _transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
RemoteControlStartConfig {
|
||||
remote_control_url,
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
},
|
||||
Some(state_db.clone()),
|
||||
remote_control_auth_manager_with_home(&codex_home),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
RemoteControlStartupMode::ResolvePersisted,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
|
||||
let refresh_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
refresh_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_status(refresh_request.stream, "404 Not Found", "").await;
|
||||
|
||||
let enroll_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
enroll_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
respond_with_status(enroll_request.stream, "500 Internal Server Error", "failed").await;
|
||||
|
||||
let retry_refresh_request = accept_http_request(&listener).await;
|
||||
assert_eq!(
|
||||
retry_refresh_request.request_line,
|
||||
"POST /backend-api/wham/remote/control/server/refresh HTTP/1.1"
|
||||
);
|
||||
respond_with_status(
|
||||
retry_refresh_request.stream,
|
||||
"500 Internal Server Error",
|
||||
"failed",
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
*remote_handle.current_enrollment.lock().await,
|
||||
Some(stale_enrollment.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should load"),
|
||||
Some(RemoteControlEnrollmentRecord {
|
||||
websocket_url: remote_control_target.websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: stale_enrollment.server_id,
|
||||
environment_id: stale_enrollment.environment_id,
|
||||
server_name: stale_enrollment.server_name,
|
||||
remote_control_enabled: Some(true),
|
||||
})
|
||||
);
|
||||
|
||||
shutdown_token.cancel();
|
||||
@@ -1911,6 +2336,7 @@ async fn remote_control_http_mode_preserves_enrollment_after_generic_websocket_4
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&stale_enrollment),
|
||||
/*remote_control_enabled*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should save");
|
||||
@@ -1928,7 +2354,7 @@ async fn remote_control_http_mode_preserves_enrollment_after_generic_websocket_4
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
RemoteControlStartupMode::EnabledEphemeral,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start");
|
||||
|
||||
@@ -13,7 +13,7 @@ fn client_management_handle(
|
||||
remote_control_url: String,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> RemoteControlHandle {
|
||||
let (enabled_tx, _enabled_rx) = watch::channel(/*init*/ false);
|
||||
let desired_state_tx = watch::channel(RemoteControlDesiredState::Disabled).0;
|
||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
server_name: test_server_name(),
|
||||
@@ -21,9 +21,10 @@ fn client_management_handle(
|
||||
environment_id: None,
|
||||
});
|
||||
RemoteControlHandle {
|
||||
enabled_tx: Arc::new(enabled_tx),
|
||||
desired_state_tx: Arc::new(desired_state_tx),
|
||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
status_tx: Arc::new(status_tx),
|
||||
state_db_available: false,
|
||||
state_db: None,
|
||||
remote_control_url,
|
||||
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None)),
|
||||
|
||||
@@ -645,7 +645,9 @@ async fn remote_control_handle_disable_keeps_current_enrollment() {
|
||||
remote_control_auth_manager(),
|
||||
);
|
||||
|
||||
remote_handle.disable();
|
||||
remote_handle
|
||||
.desired_state_tx
|
||||
.send_replace(RemoteControlDesiredState::Disabled);
|
||||
assert!(
|
||||
remote_handle.current_enrollment.lock().await.is_some(),
|
||||
"disabled remote control should keep the selected pairing server"
|
||||
@@ -665,7 +667,6 @@ async fn remote_control_handle_reenrolls_after_stale_pairing_enrollment() {
|
||||
remote_control_auth_manager_with_home(&codex_home),
|
||||
);
|
||||
remote_handle.state_db = Some(state_db.clone());
|
||||
remote_handle.disable();
|
||||
let stale_enrollment = remote_handle
|
||||
.current_enrollment
|
||||
.lock()
|
||||
@@ -688,9 +689,15 @@ async fn remote_control_handle_reenrolls_after_stale_pairing_enrollment() {
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
Some(&stale_enrollment),
|
||||
/*remote_control_enabled*/ Some(true),
|
||||
)
|
||||
.await
|
||||
.expect("stale enrollment should save");
|
||||
remote_handle
|
||||
.desired_state_tx
|
||||
.send_replace(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
});
|
||||
let server_refreshed_enrollment = refreshed_enrollment.clone();
|
||||
let server_task = tokio::spawn(async move {
|
||||
let stale_pairing_request = accept_http_request(&listener).await;
|
||||
@@ -761,15 +768,17 @@ async fn remote_control_handle_reenrolls_after_stale_pairing_enrollment() {
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
load_persisted_remote_control_enrollment(
|
||||
Some(state_db.as_ref()),
|
||||
&remote_control_target,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(refreshed_enrollment)
|
||||
state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("refreshed enrollment should load")
|
||||
.expect("refreshed enrollment should exist")
|
||||
.remote_control_enabled,
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
use super::CurrentRemoteControlEnrollment;
|
||||
use super::RemoteControlEnrollmentSelection;
|
||||
use super::RemoteControlPairingPersistenceKey;
|
||||
use super::desired_state::RemoteControlDesiredState;
|
||||
use super::desired_state::acquire_persistence_lock;
|
||||
use super::desired_state::desired_state_from_persisted_enrollment;
|
||||
use super::protocol::ClientEnvelope;
|
||||
use super::protocol::ClientEvent;
|
||||
use super::protocol::ClientId;
|
||||
@@ -45,6 +49,7 @@ use std::io::ErrorKind;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
@@ -264,7 +269,9 @@ pub(crate) struct RemoteControlWebsocket {
|
||||
state: Arc<Mutex<WebsocketState>>,
|
||||
server_event_rx: Arc<Mutex<mpsc::Receiver<super::QueuedServerEnvelope>>>,
|
||||
used_rx: watch::Receiver<usize>,
|
||||
enabled_rx: watch::Receiver<bool>,
|
||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||
desired_state_rx: watch::Receiver<RemoteControlDesiredState>,
|
||||
desired_state_persistence_lock: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteControlWebsocketConfig {
|
||||
@@ -280,6 +287,11 @@ pub(super) struct RemoteControlAuthContext<'a> {
|
||||
auth_change_rx: &'a mut watch::Receiver<u64>,
|
||||
}
|
||||
|
||||
struct RemoteControlEnrollmentAuthContext<'a, 'b> {
|
||||
auth: &'a RemoteControlConnectionAuth,
|
||||
recovery: &'a mut RemoteControlAuthContext<'b>,
|
||||
}
|
||||
|
||||
enum ConnectOutcome {
|
||||
Connected(Box<WebSocketStream<MaybeTlsStream<TcpStream>>>),
|
||||
Disabled,
|
||||
@@ -299,6 +311,7 @@ pub(super) struct RemoteControlChannels {
|
||||
pub(super) status_publisher: RemoteControlStatusPublisher,
|
||||
pub(super) current_enrollment: CurrentRemoteControlEnrollment,
|
||||
pub(super) pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||
pub(super) desired_state_persistence_lock: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -341,7 +354,7 @@ impl RemoteControlStatusPublisher {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_environment_id(&self, environment_id: Option<String>) {
|
||||
pub(super) fn publish_environment_id(&self, environment_id: Option<String>) {
|
||||
let mut status_change = None;
|
||||
self.tx.send_if_modified(|status| {
|
||||
if status.status == RemoteControlConnectionStatus::Disabled {
|
||||
@@ -380,6 +393,8 @@ pub(super) struct RemoteControlConnectOptions<'a> {
|
||||
server_name: &'a str,
|
||||
subscribe_cursor: Option<&'a str>,
|
||||
app_server_client_name: Option<&'a str>,
|
||||
desired_state_tx: &'a watch::Sender<RemoteControlDesiredState>,
|
||||
desired_state_persistence_lock: &'a Semaphore,
|
||||
}
|
||||
|
||||
impl RemoteControlWebsocket {
|
||||
@@ -389,7 +404,7 @@ impl RemoteControlWebsocket {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
channels: RemoteControlChannels,
|
||||
shutdown_token: CancellationToken,
|
||||
enabled_rx: watch::Receiver<bool>,
|
||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||
) -> Self {
|
||||
let shutdown_token = shutdown_token.child_token();
|
||||
let (server_event_tx, server_event_rx) = mpsc::channel(super::CHANNEL_CAPACITY);
|
||||
@@ -402,6 +417,7 @@ impl RemoteControlWebsocket {
|
||||
let auth_recovery = auth_manager.unauthorized_recovery();
|
||||
let auth_change_rx = auth_manager.auth_change_receiver();
|
||||
|
||||
let desired_state_rx = desired_state_tx.subscribe();
|
||||
Self {
|
||||
remote_control_url: config.remote_control_url,
|
||||
installation_id: config.installation_id,
|
||||
@@ -426,7 +442,9 @@ impl RemoteControlWebsocket {
|
||||
})),
|
||||
server_event_rx: Arc::new(Mutex::new(server_event_rx)),
|
||||
used_rx,
|
||||
enabled_rx,
|
||||
desired_state_tx,
|
||||
desired_state_rx,
|
||||
desired_state_persistence_lock: channels.desired_state_persistence_lock,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,7 +460,7 @@ impl RemoteControlWebsocket {
|
||||
remote_control_url = %self.remote_control_url,
|
||||
installation_id = %self.installation_id,
|
||||
server_name = %self.server_name,
|
||||
initial_enabled = *self.enabled_rx.borrow(),
|
||||
initial_desired_state = ?*self.desired_state_rx.borrow(),
|
||||
"app-server remote control websocket loop started"
|
||||
);
|
||||
let app_server_client_name = match self
|
||||
@@ -464,6 +482,16 @@ impl RemoteControlWebsocket {
|
||||
};
|
||||
self.pairing_persistence_key
|
||||
.send_replace(app_server_client_name.clone());
|
||||
if matches!(
|
||||
*self.desired_state_rx.borrow(),
|
||||
RemoteControlDesiredState::Unknown
|
||||
) && !self
|
||||
.resolve_unknown_desired_state(app_server_client_name.as_deref())
|
||||
.await
|
||||
{
|
||||
self.client_tracker.lock().await.shutdown().await;
|
||||
return;
|
||||
}
|
||||
|
||||
loop {
|
||||
if !self.wait_until_enabled().await {
|
||||
@@ -513,7 +541,7 @@ impl RemoteControlWebsocket {
|
||||
connection_end_reason = ?connection_end_reason,
|
||||
current_status = ?status.status,
|
||||
environment_id = ?status.environment_id,
|
||||
enabled = *self.enabled_rx.borrow(),
|
||||
desired_state = ?*self.desired_state_rx.borrow(),
|
||||
"app-server remote control websocket connection cycle ended"
|
||||
);
|
||||
}
|
||||
@@ -546,10 +574,96 @@ impl RemoteControlWebsocket {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_unknown_desired_state(
|
||||
&mut self,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> bool {
|
||||
let remote_control_target = match super::protocol::normalize_remote_control_url(
|
||||
&self.remote_control_url,
|
||||
) {
|
||||
Ok(remote_control_target) => remote_control_target,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"remote control preference cannot be resolved because the URL is invalid: {err}"
|
||||
);
|
||||
self.transition_unknown_to(RemoteControlDesiredState::Disabled);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
self.remote_control_target = Some(remote_control_target.clone());
|
||||
let Some(state_db) = self.state_db.clone() else {
|
||||
self.transition_unknown_to(RemoteControlDesiredState::Disabled);
|
||||
return true;
|
||||
};
|
||||
|
||||
loop {
|
||||
if !matches!(
|
||||
*self.desired_state_rx.borrow(),
|
||||
RemoteControlDesiredState::Unknown
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
let auth = match load_remote_control_auth(&self.auth_manager).await {
|
||||
Ok(auth) => auth,
|
||||
Err(err) => {
|
||||
info!(
|
||||
error = %err,
|
||||
"waiting to resolve remote control preference until authentication is available"
|
||||
);
|
||||
if !self.wait_for_preference_resolution_retry().await {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let enrollment = match state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(enrollment) => enrollment,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
error = %err,
|
||||
"failed to resolve persisted remote control preference; retrying"
|
||||
);
|
||||
if !self.wait_for_preference_resolution_retry().await {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let desired_state = desired_state_from_persisted_enrollment(enrollment);
|
||||
self.transition_unknown_to(desired_state);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
fn transition_unknown_to(&self, desired_state: RemoteControlDesiredState) {
|
||||
self.desired_state_tx.send_if_modified(|state| {
|
||||
if !matches!(*state, RemoteControlDesiredState::Unknown) {
|
||||
return false;
|
||||
}
|
||||
*state = desired_state;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
async fn wait_for_preference_resolution_retry(&mut self) -> bool {
|
||||
tokio::select! {
|
||||
_ = self.shutdown_token.cancelled() => false,
|
||||
changed = self.desired_state_rx.changed() => changed.is_ok(),
|
||||
_ = tokio::time::sleep(REMOTE_CONTROL_ACCOUNT_ID_RETRY_INTERVAL) => true,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_until_enabled(&mut self) -> bool {
|
||||
tokio::select! {
|
||||
_ = self.shutdown_token.cancelled() => false,
|
||||
enabled = self.enabled_rx.wait_for(|enabled| *enabled) => enabled.is_ok(),
|
||||
desired_state = self.desired_state_rx.wait_for(|state| state.is_enabled()) => desired_state.is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -573,7 +687,7 @@ impl RemoteControlWebsocket {
|
||||
warn!("remote control is enabled but the URL is invalid: {err}");
|
||||
tokio::select! {
|
||||
_ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown,
|
||||
changed = self.enabled_rx.wait_for(|enabled| !*enabled) => {
|
||||
changed = self.desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
||||
if changed.is_err() {
|
||||
return ConnectOutcome::Shutdown;
|
||||
}
|
||||
@@ -604,15 +718,18 @@ impl RemoteControlWebsocket {
|
||||
server_name: &self.server_name,
|
||||
subscribe_cursor: subscribe_cursor.as_deref(),
|
||||
app_server_client_name,
|
||||
desired_state_tx: &self.desired_state_tx,
|
||||
desired_state_persistence_lock: &self.desired_state_persistence_lock,
|
||||
};
|
||||
let auth_context = RemoteControlAuthContext {
|
||||
auth_manager: &self.auth_manager,
|
||||
auth_recovery: &mut self.auth_recovery,
|
||||
auth_change_rx: &mut self.auth_change_rx,
|
||||
};
|
||||
let mut disabled_rx = self.desired_state_rx.clone();
|
||||
let connect_result = tokio::select! {
|
||||
_ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown,
|
||||
changed = self.enabled_rx.wait_for(|enabled| !*enabled) => {
|
||||
changed = disabled_rx.wait_for(|state| !state.is_enabled()) => {
|
||||
if changed.is_err() {
|
||||
return ConnectOutcome::Shutdown;
|
||||
}
|
||||
@@ -633,7 +750,7 @@ impl RemoteControlWebsocket {
|
||||
|
||||
match connect_result {
|
||||
Ok((websocket_connection, response)) => {
|
||||
if !*self.enabled_rx.borrow() {
|
||||
if !self.desired_state_rx.borrow().is_enabled() {
|
||||
return ConnectOutcome::Disabled;
|
||||
}
|
||||
self.reconnect_attempt = 0;
|
||||
@@ -654,7 +771,7 @@ impl RemoteControlWebsocket {
|
||||
return ConnectOutcome::Connected(Box::new(websocket_connection));
|
||||
}
|
||||
Err(err) => {
|
||||
if !*self.enabled_rx.borrow() {
|
||||
if !self.desired_state_rx.borrow().is_enabled() {
|
||||
return ConnectOutcome::Disabled;
|
||||
}
|
||||
let reconnect_delay = if err.kind() == ErrorKind::WouldBlock {
|
||||
@@ -691,7 +808,7 @@ impl RemoteControlWebsocket {
|
||||
};
|
||||
tokio::select! {
|
||||
_ = shutdown_token.cancelled() => return ConnectOutcome::Shutdown,
|
||||
changed = self.enabled_rx.wait_for(|enabled| !*enabled) => {
|
||||
changed = self.desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
||||
if changed.is_err() {
|
||||
return ConnectOutcome::Shutdown;
|
||||
}
|
||||
@@ -736,10 +853,10 @@ impl RemoteControlWebsocket {
|
||||
shutdown_token.clone(),
|
||||
));
|
||||
|
||||
let mut enabled_rx = self.enabled_rx.clone();
|
||||
let mut desired_state_rx = self.desired_state_rx.clone();
|
||||
let connection_end_reason = tokio::select! {
|
||||
_ = shutdown_token.cancelled() => ConnectionEndReason::Shutdown,
|
||||
changed = enabled_rx.wait_for(|enabled| !*enabled) => {
|
||||
changed = desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
||||
if changed.is_ok() {
|
||||
self.status_publisher
|
||||
.publish_status(RemoteControlConnectionStatus::Disabled);
|
||||
@@ -1253,22 +1370,25 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
if websocket_response_reports_missing_remote_app_server(response) =>
|
||||
{
|
||||
info!(
|
||||
"remote control websocket returned HTTP 404; clearing stale enrollment before re-enrolling: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
"remote control websocket returned HTTP 404; replacing stale enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
remote_control_target.websocket_url,
|
||||
auth.account_id,
|
||||
enrollment.server_id,
|
||||
enrollment.environment_id
|
||||
);
|
||||
clear_remote_control_enrollment_if_matches(
|
||||
replace_remote_control_enrollment_if_matches(
|
||||
state_db,
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
connect_options.app_server_client_name,
|
||||
RemoteControlEnrollmentAuthContext {
|
||||
auth: &auth,
|
||||
recovery: &mut auth_context,
|
||||
},
|
||||
current_enrollment,
|
||||
&enrollment,
|
||||
connect_options,
|
||||
status_publisher,
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
}
|
||||
tungstenite::Error::Http(response) if response.status().as_u16() == 404 => {
|
||||
let response_body = response
|
||||
@@ -1337,6 +1457,14 @@ async fn prepare_remote_control_enrollment(
|
||||
};
|
||||
let enrollment_account_id = enrollment.as_ref().map(|enrollment| &enrollment.account_id);
|
||||
if enrollment_account_id.is_some_and(|account_id| account_id != &auth.account_id) {
|
||||
resolve_desired_state_after_account_change(
|
||||
state_db,
|
||||
remote_control_target,
|
||||
auth_context.auth_manager,
|
||||
&auth.account_id,
|
||||
connect_options,
|
||||
)
|
||||
.await?;
|
||||
info!(
|
||||
"clearing in-memory remote control enrollment because account id changed: websocket_url={}, previous_account_id={:?}, current_account_id={:?}",
|
||||
remote_control_target.websocket_url,
|
||||
@@ -1347,6 +1475,12 @@ async fn prepare_remote_control_enrollment(
|
||||
);
|
||||
*enrollment = None;
|
||||
status_publisher.publish_environment_id(/*environment_id*/ None);
|
||||
if !connect_options.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::Interrupted,
|
||||
"remote control disabled after account changed",
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(enrollment) = enrollment.as_mut() {
|
||||
enrollment.remote_control_target = remote_control_target.clone();
|
||||
@@ -1373,14 +1507,17 @@ async fn prepare_remote_control_enrollment(
|
||||
});
|
||||
}
|
||||
|
||||
enroll_remote_control_server_if_missing(
|
||||
enroll_and_persist_remote_control_server(
|
||||
remote_control_target,
|
||||
state_db,
|
||||
&auth,
|
||||
auth_context,
|
||||
RemoteControlEnrollmentAuthContext {
|
||||
auth: &auth,
|
||||
recovery: auth_context,
|
||||
},
|
||||
enrollment,
|
||||
connect_options,
|
||||
status_publisher,
|
||||
RemoteControlEnrollmentSelection::ReuseOrCreate,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1412,26 +1549,20 @@ async fn prepare_remote_control_enrollment(
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
info!(
|
||||
"remote control server refresh returned HTTP 404; clearing stale enrollment before re-enrolling: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
"remote control server refresh returned HTTP 404; replacing stale enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
remote_control_target.websocket_url, auth.account_id, server_id, environment_id
|
||||
);
|
||||
clear_remote_control_enrollment(
|
||||
state_db,
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
connect_options.app_server_client_name,
|
||||
enrollment,
|
||||
status_publisher,
|
||||
)
|
||||
.await;
|
||||
enroll_remote_control_server_if_missing(
|
||||
enroll_and_persist_remote_control_server(
|
||||
remote_control_target,
|
||||
state_db,
|
||||
&auth,
|
||||
auth_context,
|
||||
RemoteControlEnrollmentAuthContext {
|
||||
auth: &auth,
|
||||
recovery: auth_context,
|
||||
},
|
||||
enrollment,
|
||||
connect_options,
|
||||
status_publisher,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
@@ -1454,6 +1585,51 @@ async fn prepare_remote_control_enrollment(
|
||||
Ok(auth)
|
||||
}
|
||||
|
||||
async fn resolve_desired_state_after_account_change(
|
||||
state_db: &StateRuntime,
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
account_id: &str,
|
||||
connect_options: RemoteControlConnectOptions<'_>,
|
||||
) -> io::Result<()> {
|
||||
let durable_enabled = RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: Some(true),
|
||||
};
|
||||
if *connect_options.desired_state_tx.borrow() != durable_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let _persistence =
|
||||
acquire_persistence_lock(connect_options.desired_state_persistence_lock).await;
|
||||
if *connect_options.desired_state_tx.borrow() != durable_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
let enrollment = state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
account_id,
|
||||
connect_options.app_server_client_name,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let current_auth = load_remote_control_auth(auth_manager).await?;
|
||||
if current_auth.account_id != account_id {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::WouldBlock,
|
||||
"remote control account changed while resolving persisted preference",
|
||||
));
|
||||
}
|
||||
let resolved_state = desired_state_from_persisted_enrollment(enrollment);
|
||||
connect_options.desired_state_tx.send_if_modified(|state| {
|
||||
if *state != durable_enabled || *state == resolved_state {
|
||||
return false;
|
||||
}
|
||||
*state = resolved_state;
|
||||
true
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn websocket_response_reports_missing_remote_app_server(
|
||||
response: &tungstenite::http::Response<Option<Vec<u8>>>,
|
||||
) -> bool {
|
||||
@@ -1466,57 +1642,38 @@ fn websocket_response_reports_missing_remote_app_server(
|
||||
})
|
||||
}
|
||||
|
||||
async fn clear_remote_control_enrollment(
|
||||
state_db: &StateRuntime,
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
status_publisher: &RemoteControlStatusPublisher,
|
||||
) {
|
||||
if let Err(clear_err) = update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
/*enrollment*/ None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to clear stale remote control enrollment in sqlite state db: {clear_err}");
|
||||
}
|
||||
*enrollment = None;
|
||||
status_publisher.publish_environment_id(/*environment_id*/ None);
|
||||
}
|
||||
|
||||
async fn clear_remote_control_enrollment_if_matches(
|
||||
async fn replace_remote_control_enrollment_if_matches(
|
||||
state_db: Option<&StateRuntime>,
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
auth_context: RemoteControlEnrollmentAuthContext<'_, '_>,
|
||||
current_enrollment: &CurrentRemoteControlEnrollment,
|
||||
enrollment: &RemoteControlEnrollment,
|
||||
connect_options: RemoteControlConnectOptions<'_>,
|
||||
status_publisher: &RemoteControlStatusPublisher,
|
||||
) {
|
||||
) -> io::Result<()> {
|
||||
let Some(state_db) = state_db else {
|
||||
return;
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"remote control requires sqlite state db",
|
||||
));
|
||||
};
|
||||
let mut current_enrollment = current_enrollment.lock().await;
|
||||
if !current_enrollment
|
||||
.as_ref()
|
||||
.is_some_and(|current| same_remote_control_enrollment(current, enrollment))
|
||||
{
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
clear_remote_control_enrollment(
|
||||
state_db,
|
||||
enroll_and_persist_remote_control_server(
|
||||
remote_control_target,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
state_db,
|
||||
auth_context,
|
||||
&mut current_enrollment,
|
||||
connect_options,
|
||||
status_publisher,
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting,
|
||||
)
|
||||
.await;
|
||||
.await
|
||||
}
|
||||
|
||||
async fn clear_remote_control_server_token_if_matches(
|
||||
@@ -1534,26 +1691,39 @@ async fn clear_remote_control_server_token_if_matches(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn enroll_remote_control_server_if_missing(
|
||||
async fn enroll_and_persist_remote_control_server(
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
state_db: &StateRuntime,
|
||||
auth: &RemoteControlConnectionAuth,
|
||||
auth_context: &mut RemoteControlAuthContext<'_>,
|
||||
auth_context: RemoteControlEnrollmentAuthContext<'_, '_>,
|
||||
enrollment: &mut Option<RemoteControlEnrollment>,
|
||||
connect_options: RemoteControlConnectOptions<'_>,
|
||||
status_publisher: &RemoteControlStatusPublisher,
|
||||
selection: RemoteControlEnrollmentSelection,
|
||||
) -> io::Result<()> {
|
||||
if enrollment.is_some() {
|
||||
return Ok(());
|
||||
match selection {
|
||||
RemoteControlEnrollmentSelection::ReuseOrCreate => {
|
||||
if enrollment.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
RemoteControlEnrollmentSelection::ReplaceExisting => {}
|
||||
}
|
||||
if !connect_options.desired_state_tx.borrow().is_enabled() {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::Interrupted,
|
||||
"remote control disabled before enrollment",
|
||||
));
|
||||
}
|
||||
|
||||
info!(
|
||||
"creating new remote control enrollment: websocket_url={}, enroll_url={}, account_id={}",
|
||||
remote_control_target.websocket_url, remote_control_target.enroll_url, auth.account_id
|
||||
remote_control_target.websocket_url,
|
||||
remote_control_target.enroll_url,
|
||||
auth_context.auth.account_id
|
||||
);
|
||||
let new_enrollment = match enroll_remote_control_server(
|
||||
remote_control_target,
|
||||
auth,
|
||||
auth_context.auth,
|
||||
connect_options.installation_id,
|
||||
connect_options.server_name,
|
||||
)
|
||||
@@ -1563,8 +1733,8 @@ async fn enroll_remote_control_server_if_missing(
|
||||
Err(err)
|
||||
if err.kind() == ErrorKind::PermissionDenied
|
||||
&& recover_remote_control_auth(
|
||||
auth_context.auth_recovery,
|
||||
auth_context.auth_change_rx,
|
||||
auth_context.recovery.auth_recovery,
|
||||
auth_context.recovery.auth_change_rx,
|
||||
)
|
||||
.await =>
|
||||
{
|
||||
@@ -1574,12 +1744,26 @@ async fn enroll_remote_control_server_if_missing(
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let _persistence =
|
||||
acquire_persistence_lock(connect_options.desired_state_persistence_lock).await;
|
||||
let persistence_preference = match *connect_options.desired_state_tx.borrow() {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference,
|
||||
} => persistence_preference,
|
||||
RemoteControlDesiredState::Unknown | RemoteControlDesiredState::Disabled => {
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::Interrupted,
|
||||
"remote control disabled during enrollment",
|
||||
));
|
||||
}
|
||||
};
|
||||
if let Err(err) = update_persisted_remote_control_enrollment(
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
&auth_context.auth.account_id,
|
||||
connect_options.app_server_client_name,
|
||||
Some(&new_enrollment),
|
||||
persistence_preference,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -1758,6 +1942,13 @@ mod tests {
|
||||
(RemoteControlStatusPublisher::new(status_tx), status_rx)
|
||||
}
|
||||
|
||||
fn enabled_desired_state_sender() -> watch::Sender<RemoteControlDesiredState> {
|
||||
watch::channel(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
})
|
||||
.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_recovery_auth_change_seen_marks_only_recovery_revision_seen() {
|
||||
let (auth_change_tx, mut auth_change_rx) = watch::channel(0u64);
|
||||
@@ -1842,6 +2033,7 @@ mod tests {
|
||||
last_refresh: Some(Utc::now()),
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1895,6 +2087,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -1959,6 +2153,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2041,6 +2237,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2135,6 +2333,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2200,6 +2400,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2250,6 +2452,8 @@ mod tests {
|
||||
server_name: "test-server",
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2287,7 +2491,10 @@ mod tests {
|
||||
drop(transport_event_rx);
|
||||
let (status_publisher, _status_rx) = remote_control_status_channel();
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (_enabled_tx, enabled_rx) = watch::channel(true);
|
||||
let (desired_state_tx, _desired_state_rx) =
|
||||
watch::channel(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
});
|
||||
let websocket_task = tokio::spawn({
|
||||
let shutdown_token = shutdown_token.clone();
|
||||
async move {
|
||||
@@ -2305,9 +2512,10 @@ mod tests {
|
||||
status_publisher,
|
||||
current_enrollment: test_current_enrollment(/*enrollment*/ None),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
},
|
||||
shutdown_token,
|
||||
enabled_rx,
|
||||
Arc::new(desired_state_tx),
|
||||
)
|
||||
.run(/*app_server_client_name_rx*/ None)
|
||||
.await
|
||||
|
||||
@@ -22,7 +22,6 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
axum = { workspace = true, default-features = false, features = [
|
||||
"http1",
|
||||
@@ -36,6 +35,7 @@ codex-cloud-config = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-core-plugins = { workspace = true }
|
||||
codex-home = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-external-agent-migration = { workspace = true }
|
||||
@@ -76,6 +76,7 @@ codex-thread-store = { workspace = true }
|
||||
codex-tools = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-json-to-toml = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
futures = { workspace = true }
|
||||
|
||||
@@ -206,12 +206,12 @@ Example with notification opt-out:
|
||||
- `marketplace/upgrade` — upgrade all configured Git plugin marketplaces, or one named marketplace when `marketplaceName` is provided. Returns selected marketplace names, upgraded roots, and per-marketplace errors.
|
||||
- `plugin/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, plugin `availability` (`AVAILABLE` by default or `DISABLED_BY_ADMIN` for remote plugins blocked upstream), fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. `interface.category` uses the marketplace category when present; otherwise it falls back to the plugin manifest category (**under development; do not call from production clients yet**).
|
||||
- `plugin/installed` — list installed plugin rows plus any explicitly requested local install-suggestion plugin names, without fetching the broader remote catalog. Mention surfaces can use this narrower view when they need plugin mention payloads rather than plugin-page discovery data (**under development; do not call from production clients yet**).
|
||||
- `plugin/read` — read one plugin by `marketplacePath` plus `pluginName`, returning marketplace info, a list-style `summary`, manifest descriptions/interface metadata, and bundled skills/hooks/apps/MCP server names. Returned plugin skills include their current `enabled` state after local config filtering; bundled hooks are returned as lightweight declaration summaries keyed for correlation with `hooks/list`. Plugin app summaries also include `needsAuth` when the server can determine connector accessibility (**under development; do not call from production clients yet**).
|
||||
- `plugin/read` — read one plugin by `marketplacePath` plus `pluginName`, returning marketplace info, a list-style `summary`, manifest descriptions/interface metadata, and bundled skills/hooks/apps/MCP server names. Returned plugin skills include their current `enabled` state after local config filtering; bundled hooks are returned as lightweight declaration summaries keyed for correlation with `hooks/list`. Use `plugin/install`'s `appsNeedingAuth` to drive post-install authentication and `app/list`'s `isAccessible` to determine current connector accessibility (**under development; do not call from production clients yet**).
|
||||
- `plugin/skill/read` — read remote plugin skill markdown on demand by `remoteMarketplaceName`, `remotePluginId`, and `skillName`. This lets clients preview uninstalled remote plugin skills without downloading the plugin bundle.
|
||||
- `skills/changed` — notification emitted when watched local skill files change.
|
||||
- `app/list` — list available apps.
|
||||
- `remoteControl/enable` — experimental; enable remote control for the current app-server process and return the current remote-control status snapshot. The caller is responsible for persisting the desired setting outside app-server.
|
||||
- `remoteControl/disable` — experimental; disable remote control for the current app-server process and return the current remote-control status snapshot. This does not revoke already enrolled controller devices.
|
||||
- `remoteControl/enable` — experimental; enable remote control for the current app-server process and return the current remote-control status snapshot. By default, any missing enrollment is completed before the response and the preference is persisted for the current app-server client scope. Pass `ephemeral: true` to enable remote control only for the current process without changing the persisted preference.
|
||||
- `remoteControl/disable` — experimental; disable remote control for the current app-server process and return the current remote-control status snapshot. By default, the disabled preference is persisted for the current app-server client scope. Pass `ephemeral: true` to disable only for the current process without changing the persisted preference. This does not revoke already enrolled controller devices.
|
||||
- `remoteControl/status/read` — experimental; read the current remote-control status snapshot. `status` is one of `disabled`, `connecting`, `connected`, or `errored`; `serverName` is the local machine name used by this app-server process; `environmentId` is a string when the app-server has a current enrollment and `null` when that enrollment is cleared, invalidated, or remote control is disabled.
|
||||
- `remoteControl/pairing/start` — experimental; start a short-lived remote-control pairing artifact for the current app-server process. Pass `manualCode: true` to also request a manual pairing code. Returns `pairingCode`, `manualPairingCode`, `environmentId`, and Unix-seconds `expiresAt`; app-server intentionally does not expose the backend `serverId`.
|
||||
- `remoteControl/pairing/status` — experimental; poll whether a remote-control `pairingCode` or `manualPairingCode` has been claimed. Pass exactly one of the two fields. Returns `claimed`.
|
||||
@@ -1775,13 +1775,18 @@ The server also emits `app/list/updated` notifications whenever either source (a
|
||||
```
|
||||
|
||||
Connected apps may override the thread's approval reviewer in `config.toml`.
|
||||
When omitted, the app inherits the top-level `approvals_reviewer` value:
|
||||
Use `apps._default.approvals_reviewer` to set the reviewer for all apps, and a
|
||||
per-app value to override that default. When both are omitted, the app inherits
|
||||
the top-level `approvals_reviewer` value:
|
||||
|
||||
```toml
|
||||
approvals_reviewer = "auto_review"
|
||||
|
||||
[apps.demo-app]
|
||||
[apps._default]
|
||||
approvals_reviewer = "user"
|
||||
|
||||
[apps.demo-app]
|
||||
approvals_reviewer = "auto_review"
|
||||
```
|
||||
|
||||
Setting the app value to `"user"` routes its approval prompts to the user
|
||||
|
||||
@@ -687,6 +687,7 @@ pub(crate) async fn apply_bespoke_event_handling(
|
||||
turn_id: request.turn_id,
|
||||
item_id: request.call_id,
|
||||
questions,
|
||||
auto_resolution_ms: request.auto_resolution_ms,
|
||||
};
|
||||
let (pending_request_id, rx) = outgoing
|
||||
.send_request(ServerRequestPayload::ToolRequestUserInput(params))
|
||||
|
||||
@@ -1147,7 +1147,7 @@ fn configured_marketplace_plugins(
|
||||
) -> io::Result<BTreeMap<String, HashSet<String>>> {
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let marketplaces = plugins_manager
|
||||
.list_marketplaces_for_config(&plugins_input, &[])
|
||||
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
|
||||
.map_err(|err| {
|
||||
invalid_data_error(format!("failed to list configured marketplaces: {err}"))
|
||||
})?;
|
||||
|
||||
@@ -21,11 +21,15 @@ use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_rollout::state_db::StateDbHandle;
|
||||
use codex_thread_store::ThreadStore;
|
||||
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use crate::thread_state::ThreadListenerCommand;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
|
||||
// TODO(jif): Enable once /ps/mcp serves complete hosted skill packages.
|
||||
const ORCHESTRATOR_SKILLS_ENABLED: bool = false;
|
||||
|
||||
pub(crate) struct ThreadExtensionDependencies {
|
||||
pub(crate) event_sink: Arc<dyn ExtensionEventSink>,
|
||||
pub(crate) auth_manager: Arc<AuthManager>,
|
||||
@@ -34,6 +38,8 @@ pub(crate) struct ThreadExtensionDependencies {
|
||||
pub(crate) thread_manager: Weak<ThreadManager>,
|
||||
pub(crate) goal_service: Arc<GoalService>,
|
||||
pub(crate) executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
|
||||
/// Process-scoped persistence backend for extensions that need stored thread history.
|
||||
pub(crate) thread_store: Arc<dyn ThreadStore>,
|
||||
}
|
||||
|
||||
pub(crate) fn thread_extensions<S>(
|
||||
@@ -51,6 +57,7 @@ where
|
||||
thread_manager,
|
||||
goal_service,
|
||||
executor_skill_provider,
|
||||
thread_store: _thread_store,
|
||||
} = dependencies;
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(event_sink);
|
||||
if let Some(state_db) = state_db {
|
||||
@@ -69,10 +76,20 @@ where
|
||||
codex_mcp_extension::install(&mut builder);
|
||||
codex_web_search_extension::install(&mut builder, auth_manager.clone());
|
||||
codex_image_generation_extension::install(&mut builder, auth_manager);
|
||||
let mut skill_providers = codex_skills_extension::SkillProviders::new()
|
||||
.with_executor_provider(executor_skill_provider);
|
||||
if ORCHESTRATOR_SKILLS_ENABLED {
|
||||
skill_providers = skill_providers.with_orchestrator_provider(Arc::new(
|
||||
codex_skills_extension::OrchestratorSkillProvider::new(),
|
||||
));
|
||||
}
|
||||
codex_skills_extension::install_with_providers(
|
||||
&mut builder,
|
||||
codex_skills_extension::SkillProviders::new()
|
||||
.with_executor_provider(executor_skill_provider),
|
||||
skill_providers,
|
||||
|config: &Config| codex_skills_extension::SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
bundled_skills_enabled: config.bundled_skills_enabled(),
|
||||
},
|
||||
);
|
||||
Arc::new(builder.build())
|
||||
}
|
||||
|
||||
@@ -104,7 +104,9 @@ type PendingClientRequestResponse = std::result::Result<Result, JSONRPCErrorErro
|
||||
fn server_notification_requires_delivery(notification: &ServerNotification) -> bool {
|
||||
matches!(
|
||||
notification,
|
||||
ServerNotification::TurnCompleted(_) | ServerNotification::ThreadSettingsUpdated(_)
|
||||
ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
| ServerNotification::ExternalAgentConfigImportCompleted(_)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -729,6 +731,7 @@ mod tests {
|
||||
use super::*;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::ConfigRequirementsReadResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::SessionSource as ApiSessionSource;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
@@ -893,5 +896,10 @@ mod tests {
|
||||
},
|
||||
})
|
||||
));
|
||||
assert!(server_notification_requires_delivery(
|
||||
&ServerNotification::ExternalAgentConfigImportCompleted(
|
||||
ExternalAgentConfigImportCompletedNotification {},
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Result as IoResult;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
@@ -109,10 +110,12 @@ mod transport;
|
||||
pub use crate::error_code::INPUT_TOO_LARGE_ERROR_CODE;
|
||||
pub use crate::error_code::INVALID_PARAMS_ERROR_CODE;
|
||||
pub use crate::transport::AppServerTransport;
|
||||
pub use crate::transport::RemoteControlStartupMode;
|
||||
pub use crate::transport::app_server_control_socket_path;
|
||||
pub use crate::transport::auth::AppServerWebsocketAuthArgs;
|
||||
pub use crate::transport::auth::AppServerWebsocketAuthSettings;
|
||||
pub use crate::transport::auth::WebsocketAuthCliMode;
|
||||
pub use crate::transport::take_remote_control_disabled_env;
|
||||
|
||||
const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT";
|
||||
const OTEL_SERVICE_NAME: &str = "codex-app-server";
|
||||
@@ -407,7 +410,7 @@ pub enum PluginStartupTasks {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AppServerRuntimeOptions {
|
||||
pub plugin_startup_tasks: PluginStartupTasks,
|
||||
pub remote_control_enabled: bool,
|
||||
pub remote_control_startup_mode: RemoteControlStartupMode,
|
||||
pub install_shutdown_signal_handler: bool,
|
||||
}
|
||||
|
||||
@@ -415,7 +418,7 @@ impl Default for AppServerRuntimeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
plugin_startup_tasks: PluginStartupTasks::Start,
|
||||
remote_control_enabled: false,
|
||||
remote_control_startup_mode: RemoteControlStartupMode::ResolvePersisted,
|
||||
install_shutdown_signal_handler: true,
|
||||
}
|
||||
}
|
||||
@@ -716,15 +719,21 @@ pub async fn run_main_with_transport_options(
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await;
|
||||
|
||||
let remote_control_requested = runtime_options.remote_control_enabled;
|
||||
let remote_control_enabled = remote_control_requested && state_db.is_some();
|
||||
if remote_control_requested && state_db.is_none() {
|
||||
let remote_control_startup_mode = runtime_options.remote_control_startup_mode;
|
||||
let remote_control_explicitly_requested =
|
||||
remote_control_startup_mode == RemoteControlStartupMode::EnabledEphemeral;
|
||||
let remote_control_enabled = remote_control_explicitly_requested && state_db.is_some();
|
||||
if remote_control_explicitly_requested && state_db.is_none() {
|
||||
error!("remote control disabled because sqlite state db is unavailable");
|
||||
}
|
||||
if transport_accept_handles.is_empty() && !remote_control_enabled {
|
||||
let no_local_transport = transport_accept_handles.is_empty();
|
||||
if no_local_transport
|
||||
&& remote_control_startup_mode != RemoteControlStartupMode::ResolvePersisted
|
||||
&& !remote_control_enabled
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
if remote_control_requested && state_db.is_none() {
|
||||
if remote_control_explicitly_requested && state_db.is_none() {
|
||||
"no transport configured; remote control disabled because sqlite state db is unavailable"
|
||||
} else {
|
||||
"no transport configured; use --listen or enable remote control"
|
||||
@@ -742,9 +751,31 @@ pub async fn run_main_with_transport_options(
|
||||
transport_event_tx.clone(),
|
||||
transport_shutdown_token.clone(),
|
||||
app_server_client_name_rx,
|
||||
remote_control_enabled,
|
||||
remote_control_startup_mode,
|
||||
)
|
||||
.await?;
|
||||
if no_local_transport
|
||||
&& remote_control_startup_mode == RemoteControlStartupMode::ResolvePersisted
|
||||
{
|
||||
let persisted_enabled = match remote_control_handle
|
||||
.resolve_persisted_preference(/*app_server_client_name*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(persisted_enabled) => persisted_enabled,
|
||||
Err(err) => {
|
||||
warn!("failed to resolve persisted remote control preference: {err}");
|
||||
false
|
||||
}
|
||||
};
|
||||
if !persisted_enabled {
|
||||
transport_shutdown_token.cancel();
|
||||
let _ = remote_control_accept_handle.await;
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"no transport configured; use --listen or enable remote control",
|
||||
));
|
||||
}
|
||||
}
|
||||
transport_accept_handles.push(remote_control_accept_handle);
|
||||
|
||||
let outbound_handle = tokio::spawn(async move {
|
||||
@@ -1154,12 +1185,14 @@ async fn init_sqlite_state_db_with_fresh_start_on_corruption(
|
||||
}
|
||||
Err(err) => err,
|
||||
};
|
||||
if !codex_state::is_sqlite_corruption_error(&err) {
|
||||
let database_path = codex_state::runtime_db_path_for_corruption_error(&err)
|
||||
.unwrap_or_else(|| codex_state::state_db_path(config.sqlite_home.as_path()));
|
||||
if !codex_state::is_sqlite_corruption_error(&err)
|
||||
&& !sqlite_home_is_blocking_file(database_path.as_path())
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let database_path = codex_state::runtime_db_path_for_corruption_error(&err)
|
||||
.unwrap_or_else(|| codex_state::state_db_path(config.sqlite_home.as_path()));
|
||||
if !attempted_backups.insert(database_path.clone()) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"failed to initialize sqlite state runtime after moving damaged database file into a backup folder: {err}"
|
||||
@@ -1196,6 +1229,13 @@ async fn init_sqlite_state_db_with_fresh_start_on_corruption(
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_home_is_blocking_file(database_path: &Path) -> bool {
|
||||
database_path
|
||||
.parent()
|
||||
.and_then(|path| std::fs::metadata(path).ok())
|
||||
.is_some_and(|metadata| metadata.is_file())
|
||||
}
|
||||
|
||||
fn sqlite_recovery_notice(
|
||||
recovered_databases: &[RecoveredSqliteDatabase],
|
||||
) -> Option<SqliteRecoveryNotice> {
|
||||
|
||||
@@ -53,13 +53,14 @@ struct AppServerArgs {
|
||||
#[arg(long = "disable-plugin-startup-tasks-for-tests", hide = true)]
|
||||
disable_plugin_startup_tasks_for_tests: bool,
|
||||
|
||||
/// Enable remote control for this app-server process.
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
let AppServerArgs {
|
||||
config_overrides,
|
||||
listen,
|
||||
@@ -84,7 +85,12 @@ fn main() -> anyhow::Result<()> {
|
||||
if disable_plugin_startup_tasks_for_tests {
|
||||
runtime_options.plugin_startup_tasks = PluginStartupTasks::Skip;
|
||||
}
|
||||
runtime_options.remote_control_enabled = remote_control;
|
||||
runtime_options.remote_control_startup_mode =
|
||||
match (remote_control, remote_control_disabled) {
|
||||
(true, _) => codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
(false, true) => codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
(false, false) => codex_app_server::RemoteControlStartupMode::ResolvePersisted,
|
||||
};
|
||||
|
||||
run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::config_manager::ConfigManager;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::McpServerRefreshConfig;
|
||||
use codex_protocol::protocol::Op;
|
||||
@@ -22,8 +21,7 @@ pub(crate) async fn queue_strict_refresh(
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|err| io::Error::other(format!("failed to load thread {thread_id}: {err}")))?;
|
||||
let config =
|
||||
build_refresh_config(thread_manager, config_manager, thread.config().await).await?;
|
||||
let config = build_refresh_config(thread.as_ref(), config_manager).await?;
|
||||
refreshes.push((thread_id, thread, config));
|
||||
}
|
||||
for (thread_id, thread, config) in refreshes {
|
||||
@@ -44,15 +42,13 @@ pub(crate) async fn queue_best_effort_refresh(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let config =
|
||||
match build_refresh_config(thread_manager, config_manager, thread.config().await).await
|
||||
{
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
warn!("failed to build MCP refresh config for thread {thread_id}: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let config = match build_refresh_config(thread.as_ref(), config_manager).await {
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
warn!("failed to build MCP refresh config for thread {thread_id}: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Err(err) = queue_refresh(thread_id, thread, config).await {
|
||||
warn!("{err}");
|
||||
}
|
||||
@@ -60,14 +56,15 @@ pub(crate) async fn queue_best_effort_refresh(
|
||||
}
|
||||
|
||||
async fn build_refresh_config(
|
||||
thread_manager: &ThreadManager,
|
||||
thread: &CodexThread,
|
||||
config_manager: &ConfigManager,
|
||||
thread_config: Arc<Config>,
|
||||
) -> io::Result<McpServerRefreshConfig> {
|
||||
let thread_config = thread.config().await;
|
||||
let config = config_manager
|
||||
.load_latest_config_for_thread(thread_config.as_ref())
|
||||
.await?;
|
||||
let mcp_servers = thread_manager.mcp_manager().runtime_servers(&config).await;
|
||||
let mcp_config = thread.runtime_mcp_config(&config).await;
|
||||
let mcp_servers = codex_mcp::configured_mcp_servers(&mcp_config);
|
||||
Ok(McpServerRefreshConfig {
|
||||
mcp_servers: serde_json::to_value(mcp_servers).map_err(io::Error::other)?,
|
||||
mcp_oauth_credentials_store_mode: serde_json::to_value(
|
||||
@@ -99,7 +96,6 @@ mod tests {
|
||||
use crate::extensions::ThreadExtensionDependencies;
|
||||
use crate::extensions::guardian_agent_spawner;
|
||||
use crate::extensions::thread_extensions;
|
||||
use async_trait::async_trait;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
@@ -113,6 +109,7 @@ mod tests {
|
||||
use codex_core::thread_store_from_config;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::NoopExtensionEventSink;
|
||||
use codex_home::CodexHomeUserInstructionsProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
@@ -202,8 +199,12 @@ mod tests {
|
||||
thread_manager: thread_manager.clone(),
|
||||
goal_service: Arc::new(codex_goal_extension::GoalService::new()),
|
||||
executor_skill_provider: Arc::clone(&executor_skill_provider),
|
||||
thread_store: Arc::clone(&thread_store),
|
||||
},
|
||||
),
|
||||
Arc::new(CodexHomeUserInstructionsProvider::new(
|
||||
good_config.codex_home.clone(),
|
||||
)),
|
||||
/*analytics_events_client*/ None,
|
||||
Arc::clone(&thread_store),
|
||||
Some(state_db.clone()),
|
||||
@@ -240,8 +241,7 @@ mod tests {
|
||||
bad_loads: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ThreadConfigLoader for CountingThreadConfigLoader {
|
||||
impl CountingThreadConfigLoader {
|
||||
async fn load(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
@@ -260,4 +260,13 @@ mod tests {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadConfigLoader for CountingThreadConfigLoader {
|
||||
fn load(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
) -> codex_config::ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>> {
|
||||
Box::pin(CountingThreadConfigLoader::load(self, context))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,6 @@ use crate::thread_state::ConnectionCapabilities;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
use crate::transport::AppServerTransport;
|
||||
use crate::transport::RemoteControlHandle;
|
||||
use async_trait::async_trait;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::AppServerRpcTransport;
|
||||
use codex_app_server_protocol::AuthMode as LoginAuthMode;
|
||||
@@ -72,6 +71,7 @@ use codex_core::config::Config;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_goal_extension::GoalService;
|
||||
use codex_home::CodexHomeUserInstructionsProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::auth::ExternalAuth;
|
||||
use codex_login::auth::ExternalAuthRefreshContext;
|
||||
@@ -105,13 +105,6 @@ impl ExternalAuthRefreshBridge {
|
||||
ExternalAuthRefreshReason::Unauthorized => ChatgptAuthTokensRefreshReason::Unauthorized,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExternalAuth for ExternalAuthRefreshBridge {
|
||||
fn auth_mode(&self) -> LoginAuthMode {
|
||||
LoginAuthMode::Chatgpt
|
||||
}
|
||||
|
||||
async fn refresh(
|
||||
&self,
|
||||
@@ -162,6 +155,19 @@ impl ExternalAuth for ExternalAuthRefreshBridge {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalAuth for ExternalAuthRefreshBridge {
|
||||
fn auth_mode(&self) -> LoginAuthMode {
|
||||
LoginAuthMode::Chatgpt
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
context: ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> {
|
||||
Box::pin(ExternalAuthRefreshBridge::refresh(self, context))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct MessageProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
@@ -336,8 +342,12 @@ impl MessageProcessor {
|
||||
thread_manager: thread_manager.clone(),
|
||||
goal_service: Arc::clone(&goal_service),
|
||||
executor_skill_provider: Arc::clone(&executor_skill_provider),
|
||||
thread_store: Arc::clone(&thread_store),
|
||||
},
|
||||
),
|
||||
Arc::new(CodexHomeUserInstructionsProvider::new(
|
||||
config.codex_home.clone(),
|
||||
)),
|
||||
Some(analytics_events_client.clone()),
|
||||
Arc::clone(&thread_store),
|
||||
state_db.clone(),
|
||||
@@ -941,13 +951,21 @@ impl MessageProcessor {
|
||||
.experimental_feature_enablement_set(request_id.clone(), params)
|
||||
.await
|
||||
}
|
||||
ClientRequest::RemoteControlEnable { .. } => self
|
||||
ClientRequest::RemoteControlEnable { params, .. } => self
|
||||
.remote_control_processor
|
||||
.enable()
|
||||
.enable(
|
||||
params.is_some_and(|params| params.ephemeral),
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::RemoteControlDisable { .. } => self
|
||||
ClientRequest::RemoteControlDisable { params, .. } => self
|
||||
.remote_control_processor
|
||||
.disable()
|
||||
.disable(
|
||||
params.is_some_and(|params| params.ephemeral),
|
||||
app_server_client_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::RemoteControlStatusRead { .. } => self
|
||||
.remote_control_processor
|
||||
|
||||
@@ -1259,6 +1259,7 @@ mod tests {
|
||||
turn_id: "turn-1".to_string(),
|
||||
item_id: "call-1".to_string(),
|
||||
questions: vec![],
|
||||
auto_resolution_ms: None,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
@@ -1321,6 +1322,7 @@ mod tests {
|
||||
turn_id: "turn-1".to_string(),
|
||||
item_id: "call-1".to_string(),
|
||||
questions: vec![],
|
||||
auto_resolution_ms: None,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
|
||||
@@ -158,6 +158,9 @@ impl AccountRequestProcessor {
|
||||
|
||||
pub(crate) fn clear_external_auth(&self) {
|
||||
self.auth_manager.clear_external_auth();
|
||||
self.thread_manager
|
||||
.plugins_manager()
|
||||
.set_auth_mode(self.auth_manager.get_api_auth_mode());
|
||||
}
|
||||
|
||||
fn current_account_updated_notification(&self) -> AccountUpdatedNotification {
|
||||
@@ -173,6 +176,10 @@ impl AccountRequestProcessor {
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
auth: Option<CodexAuth>,
|
||||
) {
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.set_auth_mode(auth.as_ref().map(CodexAuth::api_auth_mode));
|
||||
|
||||
match config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
|
||||
@@ -29,6 +29,7 @@ use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -64,9 +65,10 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsReadFileParams,
|
||||
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
let bytes = self
|
||||
.file_system()?
|
||||
.read_file(¶ms.path, /*sandbox*/ None)
|
||||
.read_file(&path, /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadFileResponse {
|
||||
@@ -83,8 +85,9 @@ impl FsRequestProcessor {
|
||||
"fs/writeFile requires valid base64 dataBase64: {err}"
|
||||
))
|
||||
})?;
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
self.file_system()?
|
||||
.write_file(¶ms.path, bytes, /*sandbox*/ None)
|
||||
.write_file(&path, bytes, /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsWriteFileResponse {})
|
||||
@@ -94,9 +97,10 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsCreateDirectoryParams,
|
||||
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
self.file_system()?
|
||||
.create_directory(
|
||||
¶ms.path,
|
||||
&path,
|
||||
CreateDirectoryOptions {
|
||||
recursive: params.recursive.unwrap_or(true),
|
||||
},
|
||||
@@ -111,9 +115,10 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsGetMetadataParams,
|
||||
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
let metadata = self
|
||||
.file_system()?
|
||||
.get_metadata(¶ms.path, /*sandbox*/ None)
|
||||
.get_metadata(&path, /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsGetMetadataResponse {
|
||||
@@ -129,9 +134,10 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsReadDirectoryParams,
|
||||
) -> Result<FsReadDirectoryResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
let entries = self
|
||||
.file_system()?
|
||||
.read_directory(¶ms.path, /*sandbox*/ None)
|
||||
.read_directory(&path, /*sandbox*/ None)
|
||||
.await
|
||||
.map_err(map_fs_error)?;
|
||||
Ok(FsReadDirectoryResponse {
|
||||
@@ -150,9 +156,10 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsRemoveParams,
|
||||
) -> Result<FsRemoveResponse, JSONRPCErrorError> {
|
||||
let path = PathUri::from_abs_path(¶ms.path).map_err(map_fs_error)?;
|
||||
self.file_system()?
|
||||
.remove(
|
||||
¶ms.path,
|
||||
&path,
|
||||
RemoveOptions {
|
||||
recursive: params.recursive.unwrap_or(true),
|
||||
force: params.force.unwrap_or(true),
|
||||
@@ -168,10 +175,13 @@ impl FsRequestProcessor {
|
||||
&self,
|
||||
params: FsCopyParams,
|
||||
) -> Result<FsCopyResponse, JSONRPCErrorError> {
|
||||
let source_path = PathUri::from_abs_path(¶ms.source_path).map_err(map_fs_error)?;
|
||||
let destination_path =
|
||||
PathUri::from_abs_path(¶ms.destination_path).map_err(map_fs_error)?;
|
||||
self.file_system()?
|
||||
.copy(
|
||||
¶ms.source_path,
|
||||
¶ms.destination_path,
|
||||
&source_path,
|
||||
&destination_path,
|
||||
CopyOptions {
|
||||
recursive: params.recursive,
|
||||
},
|
||||
|
||||
@@ -203,22 +203,28 @@ impl McpRequestProcessor {
|
||||
let request = request_id.clone();
|
||||
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let config = match params.thread_id.as_deref() {
|
||||
let (config, thread) = match params.thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let thread_config = thread.config().await;
|
||||
self.config_manager
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config_for_thread(thread_config.as_ref())
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?;
|
||||
(config, Some(thread))
|
||||
}
|
||||
None => (self.load_latest_config(/*fallback_cwd*/ None).await?, None),
|
||||
};
|
||||
let mcp_config = match thread {
|
||||
Some(thread) => thread.runtime_mcp_config(&config).await,
|
||||
None => {
|
||||
self.thread_manager
|
||||
.mcp_manager()
|
||||
.runtime_config(&config)
|
||||
.await
|
||||
}
|
||||
None => self.load_latest_config(/*fallback_cwd*/ None).await?,
|
||||
};
|
||||
let mcp_config = self
|
||||
.thread_manager
|
||||
.mcp_manager()
|
||||
.runtime_config(&config)
|
||||
.await;
|
||||
let auth = self.auth_manager.auth().await;
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
// This status path has no turn-selected environment. Use config cwd
|
||||
|
||||
@@ -573,6 +573,7 @@ impl PluginRequestProcessor {
|
||||
.list_marketplaces_for_config(
|
||||
&config_for_marketplace_listing,
|
||||
&roots_for_marketplace_listing,
|
||||
/*include_openai_curated*/ true,
|
||||
)?;
|
||||
Ok::<
|
||||
(
|
||||
@@ -837,8 +838,11 @@ impl PluginRequestProcessor {
|
||||
let config_for_marketplace_listing = plugins_input.clone();
|
||||
let shared_plugin_ids_by_local_path = load_shared_plugin_ids_by_local_path(config)?;
|
||||
match tokio::task::spawn_blocking(move || {
|
||||
let outcome = plugins_manager
|
||||
.list_marketplaces_for_config(&config_for_marketplace_listing, &roots)?;
|
||||
let outcome = plugins_manager.list_marketplaces_for_config(
|
||||
&config_for_marketplace_listing,
|
||||
&roots,
|
||||
/*include_openai_curated*/ true,
|
||||
)?;
|
||||
Ok::<
|
||||
(
|
||||
Vec<PluginMarketplaceEntry>,
|
||||
@@ -1031,12 +1035,10 @@ impl PluginRequestProcessor {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
let app_summaries = load_plugin_app_summaries(
|
||||
&config,
|
||||
&outcome.plugin.apps,
|
||||
Arc::clone(&environment_manager),
|
||||
self.thread_manager.mcp_manager(),
|
||||
&outcome.plugin.app_category_by_id,
|
||||
)
|
||||
.await;
|
||||
let visible_skills = outcome
|
||||
@@ -1114,14 +1116,13 @@ impl PluginRequestProcessor {
|
||||
.cloned()
|
||||
.map(codex_plugin::AppConnectorId)
|
||||
.collect::<Vec<_>>();
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
let app_summaries = load_plugin_app_summaries(
|
||||
&config,
|
||||
&plugin_apps,
|
||||
Arc::clone(&environment_manager),
|
||||
self.thread_manager.mcp_manager(),
|
||||
)
|
||||
.await;
|
||||
let app_category_by_id = remote_detail
|
||||
.app_manifest
|
||||
.as_ref()
|
||||
.map(plugin_app_category_by_id_from_value)
|
||||
.unwrap_or_default();
|
||||
let app_summaries =
|
||||
load_plugin_app_summaries(&config, &plugin_apps, &app_category_by_id).await;
|
||||
remote_plugin_detail_to_info(remote_detail, app_summaries)
|
||||
}
|
||||
};
|
||||
@@ -1568,17 +1569,28 @@ impl PluginRequestProcessor {
|
||||
.into_iter()
|
||||
.map(codex_plugin::AppConnectorId)
|
||||
.collect::<Vec<_>>();
|
||||
let app_category_by_id = remote_detail
|
||||
.app_manifest
|
||||
.as_ref()
|
||||
.map(plugin_app_category_by_id_from_value)
|
||||
.unwrap_or_default();
|
||||
let all_connectors = connectors::list_cached_all_connectors(&config)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
connectors::connectors_for_plugin_apps(all_connectors, &plugin_apps)
|
||||
.into_iter()
|
||||
.map(|connector| AppSummary {
|
||||
id: connector.id,
|
||||
name: connector.name,
|
||||
description: connector.description,
|
||||
install_url: connector.install_url,
|
||||
needs_auth: true,
|
||||
.map(|connector| {
|
||||
let category = app_category_by_id
|
||||
.get(&connector.id)
|
||||
.cloned()
|
||||
.or_else(|| connector.category());
|
||||
AppSummary {
|
||||
category,
|
||||
id: connector.id,
|
||||
name: connector.name,
|
||||
description: connector.description,
|
||||
install_url: connector.install_url,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1883,8 +1895,7 @@ impl PluginRequestProcessor {
|
||||
async fn load_plugin_app_summaries(
|
||||
config: &Config,
|
||||
plugin_apps: &[codex_plugin::AppConnectorId],
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
app_category_by_id: &HashMap<String, String>,
|
||||
) -> Vec<AppSummary> {
|
||||
if plugin_apps.is_empty() {
|
||||
return Vec::new();
|
||||
@@ -1903,51 +1914,31 @@ async fn load_plugin_app_summaries(
|
||||
|
||||
let plugin_connectors = connectors::connectors_for_plugin_apps(connectors, plugin_apps);
|
||||
|
||||
let accessible_connectors =
|
||||
match connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
config,
|
||||
/*force_refetch*/ false,
|
||||
environment_manager,
|
||||
mcp_manager,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(status) if status.codex_apps_ready => status.connectors,
|
||||
Ok(_) => {
|
||||
return plugin_connectors
|
||||
.into_iter()
|
||||
.map(AppSummary::from)
|
||||
.collect();
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("failed to load app auth state for plugin/read: {err:#}");
|
||||
return plugin_connectors
|
||||
.into_iter()
|
||||
.map(AppSummary::from)
|
||||
.collect();
|
||||
}
|
||||
};
|
||||
|
||||
let accessible_ids = accessible_connectors
|
||||
.iter()
|
||||
.map(|connector| connector.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
plugin_connectors
|
||||
.into_iter()
|
||||
.map(|connector| {
|
||||
let needs_auth = !accessible_ids.contains(connector.id.as_str());
|
||||
let category = app_category_by_id
|
||||
.get(&connector.id)
|
||||
.cloned()
|
||||
.or_else(|| connector.category());
|
||||
AppSummary {
|
||||
id: connector.id,
|
||||
name: connector.name,
|
||||
description: connector.description,
|
||||
install_url: connector.install_url,
|
||||
needs_auth,
|
||||
category,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plugin_app_category_by_id_from_value(value: &serde_json::Value) -> HashMap<String, String> {
|
||||
codex_core_plugins::loader::plugin_app_metadata_from_value(value)
|
||||
.into_iter()
|
||||
.filter_map(|app| app.category.map(|category| (app.id.0, category)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plugin_apps_needing_auth(
|
||||
all_connectors: &[AppInfo],
|
||||
accessible_connectors: &[AppInfo],
|
||||
@@ -1974,12 +1965,15 @@ fn plugin_apps_needing_auth(
|
||||
&& !accessible_ids.contains(connector.id.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.map(|connector| AppSummary {
|
||||
id: connector.id,
|
||||
name: connector.name,
|
||||
description: connector.description,
|
||||
install_url: connector.install_url,
|
||||
needs_auth: true,
|
||||
.map(|connector| {
|
||||
let category = connector.category();
|
||||
AppSummary {
|
||||
category,
|
||||
id: connector.id,
|
||||
name: connector.name,
|
||||
description: connector.description,
|
||||
install_url: connector.install_url,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -2067,6 +2061,7 @@ fn remote_plugin_detail_to_info(
|
||||
template_id: template.template_id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
category: template.category,
|
||||
canonical_connector_id: template.canonical_connector_id,
|
||||
logo_url: template.logo_url,
|
||||
logo_url_dark: template.logo_url_dark,
|
||||
|
||||
@@ -28,17 +28,38 @@ impl RemoteControlRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enable(&self) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
|
||||
pub(crate) async fn enable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
handle
|
||||
.enable()
|
||||
.map(RemoteControlEnableResponse::from)
|
||||
.map_err(map_unavailable)
|
||||
let status = if ephemeral {
|
||||
handle.enable_ephemeral().map_err(map_unavailable)?
|
||||
} else {
|
||||
handle
|
||||
.enable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
Ok(RemoteControlEnableResponse::from(status))
|
||||
}
|
||||
|
||||
pub(crate) fn disable(&self) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
|
||||
pub(crate) async fn disable(
|
||||
&self,
|
||||
ephemeral: bool,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Result<RemoteControlDisableResponse, JSONRPCErrorError> {
|
||||
let handle = self.handle()?;
|
||||
Ok(RemoteControlDisableResponse::from(handle.disable()))
|
||||
let status = if ephemeral {
|
||||
handle.disable_ephemeral().await
|
||||
} else {
|
||||
handle
|
||||
.disable(app_server_client_name)
|
||||
.await
|
||||
.map_err(map_update_error)?
|
||||
};
|
||||
Ok(RemoteControlDisableResponse::from(status))
|
||||
}
|
||||
|
||||
pub(crate) fn status_read(&self) -> Result<RemoteControlStatusReadResponse, JSONRPCErrorError> {
|
||||
@@ -104,6 +125,14 @@ fn map_unavailable(err: RemoteControlUnavailable) -> JSONRPCErrorError {
|
||||
invalid_request(err.to_string())
|
||||
}
|
||||
|
||||
fn map_update_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::NotFound {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn map_pairing_start_error(err: io::Error) -> JSONRPCErrorError {
|
||||
if err.kind() == io::ErrorKind::InvalidInput {
|
||||
invalid_request(err.to_string())
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn environment_selection_error_message(err: CodexErr) -> String {
|
||||
pub(super) fn environment_selection_error(err: CodexErr) -> JSONRPCErrorError {
|
||||
match err {
|
||||
CodexErr::InvalidRequest(message) => message,
|
||||
err => err.to_string(),
|
||||
CodexErr::InvalidRequest(message) => invalid_request(message),
|
||||
err => internal_error(format!("failed to validate environment selections: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1299,7 +1299,7 @@ impl ThreadRequestProcessor {
|
||||
if let Some(environment_selections) = environment_selections.as_ref() {
|
||||
self.thread_manager
|
||||
.validate_environment_selections(environment_selections)
|
||||
.map_err(|err| invalid_request(environment_selection_error_message(err)))?;
|
||||
.map_err(environment_selection_error)?;
|
||||
}
|
||||
Ok(environment_selections)
|
||||
}
|
||||
|
||||
@@ -1140,6 +1140,7 @@ mod thread_processor_behavior_tests {
|
||||
turn_id: "turn-1".to_string(),
|
||||
item_id: "call-1".to_string(),
|
||||
questions: vec![],
|
||||
auto_resolution_ms: None,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
|
||||
@@ -346,7 +346,7 @@ impl TurnRequestProcessor {
|
||||
if let Some(environment_selections) = environment_selections.as_ref() {
|
||||
self.thread_manager
|
||||
.validate_environment_selections(environment_selections)
|
||||
.map_err(|err| invalid_request(environment_selection_error_message(err)))?;
|
||||
.map_err(environment_selection_error)?;
|
||||
}
|
||||
Ok(environment_selections)
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(crate) use codex_app_server_transport::OutgoingMessage;
|
||||
pub(crate) use codex_app_server_transport::QueuedOutgoingMessage;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlHandle;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlStartConfig;
|
||||
pub use codex_app_server_transport::RemoteControlStartupMode;
|
||||
pub(crate) use codex_app_server_transport::RemoteControlUnavailable;
|
||||
pub(crate) use codex_app_server_transport::TransportEvent;
|
||||
pub(crate) use codex_app_server_transport::acquire_app_server_startup_lock;
|
||||
@@ -31,6 +32,7 @@ pub(crate) use codex_app_server_transport::start_control_socket_acceptor;
|
||||
pub(crate) use codex_app_server_transport::start_remote_control;
|
||||
pub(crate) use codex_app_server_transport::start_stdio_connection;
|
||||
pub(crate) use codex_app_server_transport::start_websocket_acceptor;
|
||||
pub use codex_app_server_transport::take_remote_control_disabled_env;
|
||||
|
||||
pub(crate) struct ConnectionState {
|
||||
pub(crate) outbound_initialized: Arc<AtomicBool>,
|
||||
|
||||
@@ -165,6 +165,7 @@ pub fn write_chatgpt_auth(
|
||||
last_refresh,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
};
|
||||
|
||||
save_auth(codex_home, &auth, cli_auth_credentials_store_mode).context("write auth.json")
|
||||
|
||||
@@ -47,6 +47,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo {
|
||||
context_window: Some(272_000),
|
||||
max_context_window: None,
|
||||
auto_compact_token_limit: None,
|
||||
comp_hash: None,
|
||||
effective_context_window_percent: 95,
|
||||
experimental_supported_tools: Vec::new(),
|
||||
input_modalities: default_input_modalities(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::process::ExitStatus;
|
||||
use std::process::Stdio;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -128,6 +129,10 @@ pub const DISABLE_PLUGIN_STARTUP_TASKS_ARG: &str = "--disable-plugin-startup-tas
|
||||
const DISABLE_MANAGED_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_DISABLE_MANAGED_CONFIG";
|
||||
|
||||
impl TestAppServer {
|
||||
pub async fn wait_for_exit(&mut self) -> std::io::Result<ExitStatus> {
|
||||
self.process.wait().await
|
||||
}
|
||||
|
||||
pub async fn new(codex_home: &Path) -> anyhow::Result<Self> {
|
||||
Self::new_with_env_and_args(codex_home, &[], &[DISABLE_PLUGIN_STARTUP_TASKS_ARG]).await
|
||||
}
|
||||
@@ -645,12 +650,30 @@ impl TestAppServer {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a runtime-only `remoteControl/enable` JSON-RPC request.
|
||||
pub async fn send_remote_control_ephemeral_enable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request(
|
||||
"remoteControl/enable",
|
||||
Some(serde_json::json!({ "ephemeral": true })),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a `remoteControl/disable` JSON-RPC request.
|
||||
pub async fn send_remote_control_disable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request("remoteControl/disable", /*params*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a runtime-only `remoteControl/disable` JSON-RPC request.
|
||||
pub async fn send_remote_control_ephemeral_disable_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request(
|
||||
"remoteControl/disable",
|
||||
Some(serde_json::json!({ "ephemeral": true })),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Send a `remoteControl/status/read` JSON-RPC request.
|
||||
pub async fn send_remote_control_status_read_request(&mut self) -> anyhow::Result<i64> {
|
||||
self.send_request("remoteControl/status/read", /*params*/ None)
|
||||
|
||||
@@ -119,6 +119,7 @@ async fn list_apps_returns_empty_with_api_key_auth() -> Result<()> {
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
},
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
|
||||
@@ -112,6 +112,7 @@ async fn turn_start_forwards_client_metadata_to_responses_request_v2() -> Result
|
||||
assert_eq!(metadata["origin"].as_str(), Some("gaas"));
|
||||
assert_eq!(metadata["thread_source"].as_str(), Some("client-supplied"));
|
||||
assert_eq!(metadata["turn_id"].as_str(), Some(turn.id.as_str()));
|
||||
assert!(metadata.get("installation_id").is_some());
|
||||
assert!(metadata.get("session_id").is_some());
|
||||
assert_eq!(
|
||||
metadata["window_id"].as_str(),
|
||||
|
||||
@@ -29,6 +29,7 @@ use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use core_test_support::responses;
|
||||
@@ -150,7 +151,7 @@ async fn auto_compaction_remote_emits_started_and_completed_items() -> Result<()
|
||||
write_mock_responses_config_toml(
|
||||
codex_home.path(),
|
||||
&server.uri(),
|
||||
&BTreeMap::default(),
|
||||
&BTreeMap::from([(Feature::RemoteCompactionV2, false)]),
|
||||
REMOTE_AUTO_COMPACT_LIMIT,
|
||||
Some(true),
|
||||
"mock_provider",
|
||||
|
||||
@@ -7,6 +7,7 @@ use codex_app_server_protocol::AppConfig;
|
||||
use codex_app_server_protocol::AppToolApproval;
|
||||
use codex_app_server_protocol::ApprovalsReviewer;
|
||||
use codex_app_server_protocol::AppsConfig;
|
||||
use codex_app_server_protocol::AppsDefaultConfig;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
@@ -332,6 +333,9 @@ async fn config_read_includes_apps() -> Result<()> {
|
||||
write_config(
|
||||
&codex_home,
|
||||
r#"
|
||||
[apps._default]
|
||||
approvals_reviewer = "auto_review"
|
||||
|
||||
[apps.app1]
|
||||
enabled = false
|
||||
approvals_reviewer = "user"
|
||||
@@ -365,7 +369,12 @@ default_tools_approval_mode = "prompt"
|
||||
assert_eq!(
|
||||
config.apps,
|
||||
Some(AppsConfig {
|
||||
default: None,
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: true,
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
apps: std::collections::HashMap::from([(
|
||||
"app1".to_string(),
|
||||
AppConfig {
|
||||
@@ -380,6 +389,16 @@ default_tools_approval_mode = "prompt"
|
||||
)]),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
origins
|
||||
.get("apps._default.approvals_reviewer")
|
||||
.expect("origin")
|
||||
.name,
|
||||
ConfigLayerSource::User {
|
||||
file: user_file.clone(),
|
||||
profile: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
origins.get("apps.app1.enabled").expect("origin").name,
|
||||
ConfigLayerSource::User {
|
||||
|
||||
@@ -34,6 +34,7 @@ const TINY_PNG_BYTES: &[u8] = &[
|
||||
0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 0, 2, 0, 0, 5, 0, 1,
|
||||
122, 94, 171, 63, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
|
||||
];
|
||||
const TINY_PNG_DATA_URL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ImagegenTestMode {
|
||||
@@ -170,11 +171,7 @@ async fn standalone_image_edit_uses_attached_model_visible_image() -> Result<()>
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(edit_request["prompt"], "add a red hat");
|
||||
assert!(
|
||||
edit_request["images"][0]["image_url"]
|
||||
.as_str()
|
||||
.is_some_and(|image_url| image_url.starts_with("data:image/png;base64,"))
|
||||
);
|
||||
assert_eq!(edit_request["images"][0]["image_url"], TINY_PNG_DATA_URL);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ use codex_app_server_protocol::McpResourceReadResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
@@ -30,9 +32,14 @@ use codex_protocol::protocol::SessionSource;
|
||||
use core_test_support::responses;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rmcp::handler::server::ServerHandler;
|
||||
use rmcp::model::ListResourcesResult;
|
||||
use rmcp::model::Meta;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ProtocolVersion;
|
||||
use rmcp::model::RawResource;
|
||||
use rmcp::model::ReadResourceRequestParams;
|
||||
use rmcp::model::ReadResourceResult;
|
||||
use rmcp::model::Resource;
|
||||
use rmcp::model::ResourceContents;
|
||||
use rmcp::model::ServerCapabilities;
|
||||
use rmcp::model::ServerInfo;
|
||||
@@ -41,6 +48,7 @@ use rmcp::service::RoleServer;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use rmcp::transport::StreamableHttpService;
|
||||
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::JoinHandle;
|
||||
@@ -51,49 +59,34 @@ const TEST_RESOURCE_URI: &str = "test://codex/resource";
|
||||
const TEST_BLOB_RESOURCE_URI: &str = "test://codex/resource.bin";
|
||||
const TEST_RESOURCE_BLOB: &str = "YmluYXJ5LXJlc291cmNl";
|
||||
const TEST_RESOURCE_TEXT: &str = "Resource body from the MCP server.";
|
||||
const SKILL_NAME: &str = "demo-plugin:deploy";
|
||||
const RAW_SKILL_DESCRIPTION: &str = "Deploy\nthrough the <hosted> orchestrator.";
|
||||
const SKILL_DESCRIPTION: &str = "Deploy through the <hosted> orchestrator.";
|
||||
const SKILL_RESOURCE_URI: &str = "skill://plugin_demo/deploy";
|
||||
const SKILL_MAIN_PROMPT_URI: &str = "skill://plugin_demo/deploy/SKILL.md";
|
||||
const SKILL_REFERENCE_URI: &str = "skill://plugin_demo/deploy/references/deploy.md";
|
||||
const SKILL_MARKER: &str = "ORCHESTRATOR_SKILL_BODY_MARKER";
|
||||
const SKILL_CONTENTS: &str = concat!(
|
||||
"---\n",
|
||||
"name: deploy\n",
|
||||
"description: Deploy through the orchestrator.\n",
|
||||
"---\n\n",
|
||||
"# Deploy\n\n",
|
||||
"ORCHESTRATOR_SKILL_BODY_MARKER\n\n",
|
||||
"Read the [deployment reference](skill://plugin_demo/deploy/references/deploy.md).\n",
|
||||
);
|
||||
const SKILL_REFERENCE_CONTENTS: &str =
|
||||
"# Deploy reference\n\nUse the orchestrator deployment API.\n";
|
||||
const SKILLS_LIST_CALL_ID: &str = "skills-list";
|
||||
const SKILLS_READ_CALL_ID: &str = "skills-read";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn mcp_resource_read_returns_resource_contents() -> Result<()> {
|
||||
let responses_server = responses::start_mock_server().await;
|
||||
let (apps_server_url, apps_server_handle) = start_resource_apps_mcp_server().await?;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
let responses_server_uri = responses_server.uri();
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model = "mock-model"
|
||||
approval_policy = "untrusted"
|
||||
sandbox_mode = "read-only"
|
||||
|
||||
model_provider = "mock_provider"
|
||||
chatgpt_base_url = "{apps_server_url}"
|
||||
mcp_oauth_credentials_store = "file"
|
||||
|
||||
[features]
|
||||
apps = true
|
||||
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider for test"
|
||||
base_url = "{responses_server_uri}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("chatgpt-token")
|
||||
.account_id("account-123")
|
||||
.chatgpt_user_id("user-123")
|
||||
.chatgpt_account_id("account-123"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
|
||||
let (_codex_home, mut mcp) =
|
||||
start_resource_test_app_server(&apps_server_url, &responses_server_uri).await?;
|
||||
|
||||
let thread_start_id = mcp
|
||||
.send_thread_start_request(ThreadStartParams {
|
||||
@@ -120,7 +113,6 @@ stream_max_retries = 0
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(read_request_id)),
|
||||
)
|
||||
.await??;
|
||||
|
||||
assert_eq!(
|
||||
to_response::<McpResourceReadResponse>(read_response)?,
|
||||
expected_resource_read_response()
|
||||
@@ -131,6 +123,165 @@ stream_max_retries = 0
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "orchestrator skills are disabled until /ps/mcp serves complete skill packages"]
|
||||
async fn orchestrator_skill_can_read_referenced_resource_without_an_executor() -> Result<()> {
|
||||
let responses_server = responses::start_mock_server().await;
|
||||
let (apps_server_url, apps_server_handle) = start_resource_apps_mcp_server().await?;
|
||||
let responses_server_uri = responses_server.uri();
|
||||
let (_codex_home, mut mcp) =
|
||||
start_resource_test_app_server(&apps_server_url, &responses_server_uri).await?;
|
||||
|
||||
let thread_start_id = mcp
|
||||
.send_thread_start_request(ThreadStartParams {
|
||||
model: Some("mock-model".to_string()),
|
||||
environments: Some(Vec::new()),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let thread_start_resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(thread_start_id)),
|
||||
)
|
||||
.await??;
|
||||
let ThreadStartResponse { thread, .. } = to_response(thread_start_resp)?;
|
||||
|
||||
let response_mock = responses::mount_sse_sequence(
|
||||
&responses_server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-list"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_LIST_CALL_ID,
|
||||
"skills",
|
||||
"list",
|
||||
&json!({
|
||||
"authority": {
|
||||
"kind": "orchestrator",
|
||||
},
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-list"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-read"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_READ_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"authority": {
|
||||
"kind": "orchestrator",
|
||||
},
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
"resource": SKILL_REFERENCE_URI,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-read"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-orchestrator-skill"),
|
||||
responses::ev_assistant_message("msg-orchestrator-skill", "Done"),
|
||||
responses::ev_completed("resp-orchestrator-skill"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let turn_start_id = mcp
|
||||
.send_turn_start_request(TurnStartParams {
|
||||
thread_id: thread.id,
|
||||
input: vec![UserInput::Text {
|
||||
text: format!("Use ${SKILL_NAME}"),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(turn_start_id)),
|
||||
)
|
||||
.await??;
|
||||
timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_notification_message("turn/completed"),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let requests = response_mock.requests();
|
||||
assert_eq!(requests.len(), 3);
|
||||
let first_request = &requests[0];
|
||||
assert!(first_request.tool_by_name("skills", "list").is_some());
|
||||
assert!(first_request.tool_by_name("skills", "read").is_some());
|
||||
assert!(first_request.tool_by_name("skills", "search").is_none());
|
||||
|
||||
let developer_messages = first_request.message_input_texts("developer");
|
||||
let catalog_line = format!(
|
||||
"- {SKILL_NAME}: {SKILL_DESCRIPTION} (orchestrator resource: {SKILL_RESOURCE_URI})"
|
||||
);
|
||||
assert_eq!(
|
||||
1,
|
||||
developer_messages
|
||||
.iter()
|
||||
.filter(|text| text.contains(&catalog_line))
|
||||
.count()
|
||||
);
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.all(|text| !text.contains("ignored-plugin:ignored"))
|
||||
);
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.any(|text| text.contains("do not treat `skill://` identifiers as filesystem paths"))
|
||||
);
|
||||
let skill_fragments = first_request
|
||||
.message_input_texts("user")
|
||||
.into_iter()
|
||||
.filter(|text| text.starts_with("<skill>"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(1, skill_fragments.len());
|
||||
assert!(skill_fragments[0].contains(&format!("<name>{SKILL_NAME}</name>")));
|
||||
assert!(skill_fragments[0].contains(SKILL_MARKER));
|
||||
assert!(skill_fragments[0].contains(SKILL_REFERENCE_URI));
|
||||
|
||||
let list_output = requests[1]
|
||||
.function_call_output_text(SKILLS_LIST_CALL_ID)
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.list output should be sent to the model"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&list_output)?,
|
||||
json!({
|
||||
"skills": [{
|
||||
"authority": {
|
||||
"kind": "orchestrator",
|
||||
},
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
"name": SKILL_NAME,
|
||||
"description": SKILL_DESCRIPTION,
|
||||
"main_resource": SKILL_MAIN_PROMPT_URI,
|
||||
}],
|
||||
"warnings": ["Orchestrator skill discovery stopped after 2 resource pages: failed to list orchestrator skill resources: resources/list failed for `codex_apps`: Mcp error: -32603: simulated later-page failure"],
|
||||
})
|
||||
);
|
||||
|
||||
let read_output = requests[2]
|
||||
.function_call_output_text(SKILLS_READ_CALL_ID)
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.read output should be sent to the model"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&read_output)?,
|
||||
json!({
|
||||
"resource": SKILL_REFERENCE_URI,
|
||||
"contents": SKILL_REFERENCE_CONTENTS,
|
||||
})
|
||||
);
|
||||
apps_server_handle.abort();
|
||||
let _ = apps_server_handle.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn mcp_resource_read_returns_resource_contents_without_thread() -> Result<()> {
|
||||
let (apps_server_url, apps_server_handle) = start_resource_apps_mcp_server().await?;
|
||||
@@ -246,6 +397,52 @@ async fn mcp_resource_read_returns_error_for_unknown_thread() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn start_resource_test_app_server(
|
||||
apps_server_url: &str,
|
||||
responses_server_uri: &str,
|
||||
) -> Result<(TempDir, TestAppServer)> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
model = "mock-model"
|
||||
approval_policy = "untrusted"
|
||||
sandbox_mode = "read-only"
|
||||
|
||||
model_provider = "mock_provider"
|
||||
chatgpt_base_url = "{apps_server_url}"
|
||||
mcp_oauth_credentials_store = "file"
|
||||
|
||||
[features]
|
||||
apps = true
|
||||
|
||||
[skills]
|
||||
include_instructions = true
|
||||
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider for test"
|
||||
base_url = "{responses_server_uri}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("chatgpt-token")
|
||||
.account_id("account-123")
|
||||
.chatgpt_user_id("user-123")
|
||||
.chatgpt_account_id("account-123"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
|
||||
Ok((codex_home, mcp))
|
||||
}
|
||||
|
||||
async fn start_resource_apps_mcp_server() -> Result<(String, JoinHandle<()>)> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let addr = listener.local_addr()?;
|
||||
@@ -292,12 +489,79 @@ impl ServerHandler for ResourceAppsMcpServer {
|
||||
.with_protocol_version(ProtocolVersion::V_2025_06_18)
|
||||
}
|
||||
|
||||
async fn list_resources(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ListResourcesResult, rmcp::ErrorData> {
|
||||
let cursor = request.and_then(|request| request.cursor);
|
||||
if cursor.is_none() {
|
||||
return Ok(ListResourcesResult {
|
||||
resources: vec![skill_resource(
|
||||
"skill://plugin_ignored/ignored",
|
||||
"plugin_ignored/ignored",
|
||||
"Not an MCP skill resource.",
|
||||
"text/plain",
|
||||
"ignored-plugin",
|
||||
"ignored",
|
||||
)],
|
||||
next_cursor: Some("skills-page".to_string()),
|
||||
meta: None,
|
||||
});
|
||||
}
|
||||
if cursor.as_deref() == Some("failing-page") {
|
||||
return Err(rmcp::ErrorData::internal_error(
|
||||
"simulated later-page failure",
|
||||
/*data*/ None,
|
||||
));
|
||||
}
|
||||
if cursor.as_deref() != Some("skills-page") {
|
||||
return Err(rmcp::ErrorData::invalid_params(
|
||||
"unexpected resources/list cursor",
|
||||
/*data*/ None,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(ListResourcesResult {
|
||||
resources: vec![skill_resource(
|
||||
SKILL_RESOURCE_URI,
|
||||
"plugin_demo/deploy",
|
||||
RAW_SKILL_DESCRIPTION,
|
||||
"mcp/skill",
|
||||
"demo-plugin",
|
||||
"deploy",
|
||||
)],
|
||||
next_cursor: Some("failing-page".to_string()),
|
||||
meta: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_resource(
|
||||
&self,
|
||||
request: ReadResourceRequestParams,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ReadResourceResult, rmcp::ErrorData> {
|
||||
let uri = request.uri;
|
||||
if uri == SKILL_MAIN_PROMPT_URI {
|
||||
return Ok(ReadResourceResult::new(vec![
|
||||
ResourceContents::TextResourceContents {
|
||||
uri: SKILL_MAIN_PROMPT_URI.to_string(),
|
||||
mime_type: Some("text/markdown".to_string()),
|
||||
text: SKILL_CONTENTS.to_string(),
|
||||
meta: None,
|
||||
},
|
||||
]));
|
||||
}
|
||||
if uri == SKILL_REFERENCE_URI {
|
||||
return Ok(ReadResourceResult::new(vec![
|
||||
ResourceContents::TextResourceContents {
|
||||
uri: SKILL_REFERENCE_URI.to_string(),
|
||||
mime_type: Some("text/markdown".to_string()),
|
||||
text: SKILL_REFERENCE_CONTENTS.to_string(),
|
||||
meta: None,
|
||||
},
|
||||
]));
|
||||
}
|
||||
if uri != TEST_RESOURCE_URI {
|
||||
return Err(rmcp::ErrorData::resource_not_found(
|
||||
format!("resource not found: {uri}"),
|
||||
@@ -321,3 +585,27 @@ impl ServerHandler for ResourceAppsMcpServer {
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
fn skill_resource(
|
||||
uri: &str,
|
||||
name: &str,
|
||||
description: &str,
|
||||
mime_type: &str,
|
||||
plugin_name: &str,
|
||||
skill_name: &str,
|
||||
) -> Resource {
|
||||
Resource::new(
|
||||
RawResource::new(uri, name)
|
||||
.with_description(description)
|
||||
.with_mime_type(mime_type)
|
||||
.with_meta(skill_resource_meta(plugin_name, skill_name)),
|
||||
/*annotations*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn skill_resource_meta(plugin_name: &str, skill_name: &str) -> Meta {
|
||||
Meta(serde_json::Map::from_iter([
|
||||
("plugin_name".to_string(), json!(plugin_name)),
|
||||
("skill_name".to_string(), json!(skill_name)),
|
||||
]))
|
||||
}
|
||||
|
||||
@@ -292,6 +292,14 @@ async fn plugin_install_writes_remote_plugin_to_cloud_and_cache() -> Result<()>
|
||||
async fn plugin_install_uses_remote_apps_needing_auth_response() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let server = MockServer::start().await;
|
||||
let remote_app_manifest = json!({
|
||||
"apps": {
|
||||
"alpha": {
|
||||
"id": "alpha",
|
||||
"category": "Developer Tools"
|
||||
}
|
||||
}
|
||||
});
|
||||
let bundle_url = mount_remote_plugin_bundle(
|
||||
&server,
|
||||
/*status_code*/ 200,
|
||||
@@ -299,7 +307,14 @@ async fn plugin_install_uses_remote_apps_needing_auth_response() -> Result<()> {
|
||||
)
|
||||
.await;
|
||||
configure_remote_plugin_with_apps_test(codex_home.path(), &server)?;
|
||||
mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await;
|
||||
mount_remote_plugin_detail_with_app_manifest(
|
||||
&server,
|
||||
REMOTE_PLUGIN_ID,
|
||||
"1.2.3",
|
||||
Some(&bundle_url),
|
||||
remote_app_manifest,
|
||||
)
|
||||
.await;
|
||||
mount_empty_remote_installed_plugins(&server).await;
|
||||
mount_remote_plugin_install_with_apps_needing_auth(&server, REMOTE_PLUGIN_ID, &["alpha"]).await;
|
||||
|
||||
@@ -327,7 +342,7 @@ async fn plugin_install_uses_remote_apps_needing_auth_response() -> Result<()> {
|
||||
name: "alpha".to_string(),
|
||||
description: None,
|
||||
install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()),
|
||||
needs_auth: true,
|
||||
category: Some("Developer Tools".to_string()),
|
||||
}],
|
||||
}
|
||||
);
|
||||
@@ -1001,7 +1016,7 @@ async fn plugin_install_returns_apps_needing_auth() -> Result<()> {
|
||||
name: "Alpha".to_string(),
|
||||
description: Some("Alpha connector".to_string()),
|
||||
install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()),
|
||||
needs_auth: true,
|
||||
category: None,
|
||||
}],
|
||||
}
|
||||
);
|
||||
@@ -1089,7 +1104,7 @@ async fn plugin_install_filters_disallowed_apps_needing_auth() -> Result<()> {
|
||||
name: "Alpha".to_string(),
|
||||
description: Some("Alpha connector".to_string()),
|
||||
install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()),
|
||||
needs_auth: true,
|
||||
category: None,
|
||||
}],
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::time::Duration;
|
||||
@@ -17,6 +16,7 @@ use axum::http::Uri;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::routing::get;
|
||||
use codex_app_server_protocol::AppInfo;
|
||||
use codex_app_server_protocol::AppMetadata;
|
||||
use codex_app_server_protocol::AppTemplateSummary;
|
||||
use codex_app_server_protocol::AppTemplateUnavailableReason;
|
||||
use codex_app_server_protocol::HookEventName;
|
||||
@@ -37,17 +37,6 @@ use codex_app_server_protocol::RequestId;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rmcp::handler::server::ServerHandler;
|
||||
use rmcp::model::JsonObject;
|
||||
use rmcp::model::ListToolsResult;
|
||||
use rmcp::model::Meta;
|
||||
use rmcp::model::ServerCapabilities;
|
||||
use rmcp::model::ServerInfo;
|
||||
use rmcp::model::Tool;
|
||||
use rmcp::model::ToolAnnotations;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use rmcp::transport::StreamableHttpService;
|
||||
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::net::TcpListener;
|
||||
@@ -434,6 +423,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() ->
|
||||
"template_id": "templated_apps_GitHubEnterprise",
|
||||
"name": "GitHub Enterprise",
|
||||
"description": "Connect GitHub Enterprise",
|
||||
"category": "Developer Tools",
|
||||
"canonical_connector_id": "github_enterprise",
|
||||
"logo_url": "https://example.com/ghe-light.png",
|
||||
"logo_url_dark": "https://example.com/ghe-dark.png",
|
||||
@@ -595,6 +585,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() ->
|
||||
template_id: "templated_apps_GitHubEnterprise".to_string(),
|
||||
name: "GitHub Enterprise".to_string(),
|
||||
description: Some("Connect GitHub Enterprise".to_string()),
|
||||
category: Some("Developer Tools".to_string()),
|
||||
canonical_connector_id: Some("github_enterprise".to_string()),
|
||||
logo_url: Some("https://example.com/ghe-light.png".to_string()),
|
||||
logo_url_dark: Some("https://example.com/ghe-dark.png".to_string()),
|
||||
@@ -605,6 +596,7 @@ async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() ->
|
||||
template_id: "templated_apps_Databricks".to_string(),
|
||||
name: "Databricks".to_string(),
|
||||
description: None,
|
||||
category: None,
|
||||
canonical_connector_id: None,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
@@ -1313,7 +1305,8 @@ description: Visible only for ChatGPT
|
||||
r#"{
|
||||
"apps": {
|
||||
"gmail": {
|
||||
"id": "gmail"
|
||||
"id": "gmail",
|
||||
"category": "Communication"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
@@ -1483,14 +1476,17 @@ enabled = false
|
||||
response.plugin.apps[0].install_url.as_deref(),
|
||||
Some("https://chatgpt.com/apps/gmail/gmail")
|
||||
);
|
||||
assert_eq!(response.plugin.apps[0].needs_auth, true);
|
||||
assert_eq!(
|
||||
response.plugin.apps[0].category.as_deref(),
|
||||
Some("Communication")
|
||||
);
|
||||
assert_eq!(response.plugin.mcp_servers.len(), 1);
|
||||
assert_eq!(response.plugin.mcp_servers[0], "demo");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_read_returns_app_needs_auth() -> Result<()> {
|
||||
async fn plugin_read_returns_app_metadata_category() -> Result<()> {
|
||||
let connectors = vec![
|
||||
AppInfo {
|
||||
id: "alpha".to_string(),
|
||||
@@ -1500,7 +1496,20 @@ async fn plugin_read_returns_app_needs_auth() -> Result<()> {
|
||||
logo_url_dark: None,
|
||||
distribution_channel: Some("featured".to_string()),
|
||||
branding: None,
|
||||
app_metadata: None,
|
||||
app_metadata: Some(AppMetadata {
|
||||
review: None,
|
||||
categories: Some(vec!["Productivity".to_string()]),
|
||||
sub_categories: None,
|
||||
seo_description: None,
|
||||
screenshots: None,
|
||||
developer: None,
|
||||
version: None,
|
||||
version_id: None,
|
||||
version_notes: None,
|
||||
first_party_type: None,
|
||||
first_party_requires_install: None,
|
||||
show_in_composer_when_unlinked: None,
|
||||
}),
|
||||
labels: None,
|
||||
install_url: None,
|
||||
is_accessible: false,
|
||||
@@ -1523,8 +1532,7 @@ async fn plugin_read_returns_app_needs_auth() -> Result<()> {
|
||||
plugin_display_names: Vec::new(),
|
||||
},
|
||||
];
|
||||
let tools = vec![connector_tool("beta", "Beta App")?];
|
||||
let (server_url, server_handle) = start_apps_server(connectors, tools).await?;
|
||||
let (server_url, server_handle) = start_apps_server(connectors).await?;
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
write_connectors_config(codex_home.path(), &server_url)?;
|
||||
@@ -1571,9 +1579,9 @@ async fn plugin_read_returns_app_needs_auth() -> Result<()> {
|
||||
.plugin
|
||||
.apps
|
||||
.iter()
|
||||
.map(|app| (app.id.as_str(), app.needs_auth))
|
||||
.map(|app| (app.id.as_str(), app.category.as_deref()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![("alpha", true), ("beta", false)]
|
||||
vec![("alpha", Some("Productivity")), ("beta", None)]
|
||||
);
|
||||
|
||||
server_handle.abort();
|
||||
@@ -1851,70 +1859,22 @@ struct AppsServerState {
|
||||
response: Arc<StdMutex<serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PluginReadMcpServer {
|
||||
tools: Arc<StdMutex<Vec<Tool>>>,
|
||||
}
|
||||
|
||||
impl ServerHandler for PluginReadMcpServer {
|
||||
fn get_info(&self) -> ServerInfo {
|
||||
ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
|
||||
}
|
||||
|
||||
fn list_tools(
|
||||
&self,
|
||||
_request: Option<rmcp::model::PaginatedRequestParams>,
|
||||
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
|
||||
) -> impl std::future::Future<Output = Result<ListToolsResult, rmcp::ErrorData>> + Send + '_
|
||||
{
|
||||
let tools = self.tools.clone();
|
||||
async move {
|
||||
let tools = tools
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
Ok(ListToolsResult {
|
||||
tools,
|
||||
next_cursor: None,
|
||||
meta: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_apps_server(
|
||||
connectors: Vec<AppInfo>,
|
||||
tools: Vec<Tool>,
|
||||
) -> Result<(String, JoinHandle<()>)> {
|
||||
async fn start_apps_server(connectors: Vec<AppInfo>) -> Result<(String, JoinHandle<()>)> {
|
||||
let state = Arc::new(AppsServerState {
|
||||
response: Arc::new(StdMutex::new(
|
||||
json!({ "apps": connectors, "next_token": null }),
|
||||
)),
|
||||
});
|
||||
let tools = Arc::new(StdMutex::new(tools));
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let addr = listener.local_addr()?;
|
||||
let mcp_service = StreamableHttpService::new(
|
||||
{
|
||||
let tools = tools.clone();
|
||||
move || {
|
||||
Ok(PluginReadMcpServer {
|
||||
tools: tools.clone(),
|
||||
})
|
||||
}
|
||||
},
|
||||
Arc::new(LocalSessionManager::default()),
|
||||
StreamableHttpServerConfig::default(),
|
||||
);
|
||||
let router = Router::new()
|
||||
.route("/connectors/directory/list", get(list_directory_connectors))
|
||||
.route(
|
||||
"/connectors/directory/list_workspace",
|
||||
get(list_directory_connectors),
|
||||
)
|
||||
.with_state(state)
|
||||
.nest_service("/api/codex/ps/mcp", mcp_service);
|
||||
.with_state(state);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, router).await;
|
||||
@@ -1954,27 +1914,6 @@ async fn list_directory_connectors(
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_tool(connector_id: &str, connector_name: &str) -> Result<Tool> {
|
||||
let schema: JsonObject = serde_json::from_value(json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}))?;
|
||||
let mut tool = Tool::new(
|
||||
Cow::Owned(format!("connector_{connector_id}")),
|
||||
Cow::Borrowed("Connector test tool"),
|
||||
Arc::new(schema),
|
||||
);
|
||||
tool.annotations = Some(ToolAnnotations::new().read_only(true));
|
||||
|
||||
let mut meta = Meta::new();
|
||||
meta.0
|
||||
.insert("connector_id".to_string(), json!(connector_id));
|
||||
meta.0
|
||||
.insert("connector_name".to_string(), json!(connector_name));
|
||||
tool.meta = Some(meta);
|
||||
Ok(tool)
|
||||
}
|
||||
|
||||
fn write_connectors_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> {
|
||||
std::fs::write(
|
||||
codex_home.join("config.toml"),
|
||||
|
||||
@@ -36,7 +36,10 @@ use codex_app_server_protocol::ThreadRealtimeTranscriptDoneNotification;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::TurnCompletedNotification;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStartResponse;
|
||||
use codex_app_server_protocol::TurnStartedNotification;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_features::FEATURES;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::protocol::RealtimeConversationVersion;
|
||||
@@ -1342,6 +1345,136 @@ async fn webrtc_v1_handoff_request_delegates_and_appends_result() -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn webrtc_assistant_output_without_handoff_reaches_realtime() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let final_answer = "long output ".repeat(1_000);
|
||||
for (version, expected_version, preamble) in [
|
||||
(
|
||||
RealtimeTestVersion::V1,
|
||||
RealtimeConversationVersion::V1,
|
||||
"direct preamble from v1",
|
||||
),
|
||||
(
|
||||
RealtimeTestVersion::V2,
|
||||
RealtimeConversationVersion::V2,
|
||||
"direct preamble from v2",
|
||||
),
|
||||
] {
|
||||
let mut harness = RealtimeE2eHarness::new(
|
||||
version,
|
||||
main_loop_responses(vec![responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"item": {
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"id": "msg-preamble",
|
||||
"phase": "commentary",
|
||||
"content": [{"type": "output_text", "text": preamble}]
|
||||
}
|
||||
}),
|
||||
responses::ev_assistant_message("msg-final", &final_answer),
|
||||
responses::ev_completed("resp-1"),
|
||||
])]),
|
||||
realtime_sideband(vec![realtime_sideband_connection(vec![
|
||||
vec![session_updated("sess_standalone_output")],
|
||||
vec![],
|
||||
match version {
|
||||
RealtimeTestVersion::V1 => vec![],
|
||||
RealtimeTestVersion::V2 => vec![
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": { "id": "resp_preamble" }
|
||||
}),
|
||||
json!({
|
||||
"type": "response.done",
|
||||
"response": { "id": "resp_preamble" }
|
||||
}),
|
||||
],
|
||||
},
|
||||
vec![],
|
||||
vec![],
|
||||
])]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let started = harness.start_webrtc_realtime("v=offer\r\n").await?;
|
||||
assert_eq!(started.started.version, expected_version);
|
||||
|
||||
let request_id = harness
|
||||
.mcp
|
||||
.send_turn_start_request(TurnStartParams {
|
||||
thread_id: harness.thread_id.clone(),
|
||||
input: vec![V2UserInput::Text {
|
||||
text: "direct text turn".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let response: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
harness
|
||||
.mcp
|
||||
.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
let _: TurnStartResponse = to_response(response)?;
|
||||
let _ = harness
|
||||
.read_notification::<TurnCompletedNotification>("turn/completed")
|
||||
.await?;
|
||||
|
||||
let preamble_request = harness.sideband_outbound_request(/*request_index*/ 1).await;
|
||||
let output_text = match version {
|
||||
RealtimeTestVersion::V1 => {
|
||||
let final_request = harness.sideband_outbound_request(/*request_index*/ 2).await;
|
||||
assert_eq!(
|
||||
preamble_request,
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "codex",
|
||||
"output_text": preamble,
|
||||
})
|
||||
);
|
||||
assert_eq!(final_request["type"], "conversation.handoff.append");
|
||||
assert_eq!(final_request["handoff_id"], "codex");
|
||||
final_request["output_text"]
|
||||
.as_str()
|
||||
.expect("output text")
|
||||
.to_string()
|
||||
}
|
||||
RealtimeTestVersion::V2 => {
|
||||
assert_v2_progress_update(&preamble_request, preamble);
|
||||
assert_v2_response_create(
|
||||
&harness.sideband_outbound_request(/*request_index*/ 2).await,
|
||||
);
|
||||
let final_request = harness.sideband_outbound_request(/*request_index*/ 3).await;
|
||||
assert_eq!(final_request["type"], "conversation.item.create");
|
||||
assert_eq!(final_request["item"]["type"], "message");
|
||||
assert_eq!(final_request["item"]["role"], "user");
|
||||
assert_eq!(final_request["item"]["content"][0]["type"], "input_text");
|
||||
let output_text = final_request["item"]["content"][0]["text"]
|
||||
.as_str()
|
||||
.expect("output text");
|
||||
assert!(output_text.starts_with("[BACKEND] "));
|
||||
assert_v2_response_create(
|
||||
&harness.sideband_outbound_request(/*request_index*/ 4).await,
|
||||
);
|
||||
output_text.to_string()
|
||||
}
|
||||
};
|
||||
assert!(output_text.contains("tokens truncated"));
|
||||
assert!(output_text.len() <= 4_000);
|
||||
|
||||
harness.shutdown().await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn webrtc_v2_forwards_audio_and_text_between_client_and_sideband() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::time::Duration;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::DEFAULT_CLIENT_NAME;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::to_response;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
@@ -24,6 +25,8 @@ use codex_app_server_protocol::RemoteControlPairingStatusResponse;
|
||||
use codex_app_server_protocol::RemoteControlStatusReadResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use codex_state::StateRuntime;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
@@ -37,10 +40,92 @@ use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
async fn remote_control_preference(
|
||||
state_db: &StateRuntime,
|
||||
websocket_url: &str,
|
||||
) -> Result<Option<bool>> {
|
||||
Ok(state_db
|
||||
.get_remote_control_enrollment(websocket_url, "account_id", Some(DEFAULT_CLIENT_NAME))
|
||||
.await?
|
||||
.context("enrollment should exist")?
|
||||
.remote_control_enabled)
|
||||
}
|
||||
|
||||
async fn wait_for_response(mcp: &mut TestAppServer, request_id: i64) -> Result<JSONRPCResponse> {
|
||||
timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await?
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listen_off_honors_persisted_remote_control_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: "server-id".to_string(),
|
||||
environment_id: "environment-id".to_string(),
|
||||
server_name: "server-name".to_string(),
|
||||
remote_control_enabled: Some(true),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let _app_server = TestAppServer::new_with_args(codex_home.path(), &["--listen", "off"]).await?;
|
||||
timeout(STARTUP_TIMEOUT, listener.accept()).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listen_off_exits_without_persisted_remote_control_enable() -> Result<()> {
|
||||
for persisted_preference in [None, Some(false)] {
|
||||
let codex_home = TempDir::new()?;
|
||||
let listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
if let Some(remote_control_enabled) = persisted_preference {
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string())
|
||||
.await?;
|
||||
state_db
|
||||
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
|
||||
websocket_url,
|
||||
account_id: "account_id".to_string(),
|
||||
app_server_client_name: None,
|
||||
server_id: "server-id".to_string(),
|
||||
environment_id: "environment-id".to_string(),
|
||||
server_name: "server-name".to_string(),
|
||||
remote_control_enabled: Some(remote_control_enabled),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
|
||||
let mut app_server =
|
||||
TestAppServer::new_with_args(codex_home.path(), &["--listen", "off"]).await?;
|
||||
let status = timeout(STARTUP_TIMEOUT, app_server.wait_for_exit()).await??;
|
||||
assert!(!status.success());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_disable_returns_disabled_status() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let _listener = configured_remote_control_listener(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
@@ -83,11 +168,22 @@ async fn remote_control_status_read_returns_disabled_status() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn remote_control_enable_returns_connecting_status() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let _backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
assert_eq!(
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
timeout(
|
||||
Duration::from_millis(100),
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await
|
||||
.expect_err("enable response should wait for enrollment");
|
||||
backend.complete_enrollment()?;
|
||||
let response: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
@@ -97,11 +193,103 @@ async fn remote_control_enable_returns_connecting_status() -> Result<()> {
|
||||
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Connecting);
|
||||
assert!(!received.server_name.is_empty());
|
||||
assert_eq!(received.environment_id, None);
|
||||
assert_eq!(received.environment_id.as_deref(), Some("environment-id"));
|
||||
assert!(!received.installation_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disable_waits_for_in_flight_durable_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let websocket_url = backend.websocket_url().to_string();
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
mcp.send_remote_control_enable_request().await?;
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??;
|
||||
let disable_request_id = mcp.send_remote_control_disable_request().await?;
|
||||
timeout(
|
||||
Duration::from_millis(100),
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(disable_request_id)),
|
||||
)
|
||||
.await
|
||||
.expect_err("disable response should wait for the in-flight enable");
|
||||
|
||||
backend.complete_enrollment()?;
|
||||
let response = wait_for_response(&mut mcp, disable_request_id).await?;
|
||||
let received: RemoteControlDisableResponse = to_response(response)?;
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Disabled);
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rpc_updates_durable_preference_but_ephemeral_does_not() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let websocket_url = backend.websocket_url().to_string();
|
||||
let state_db =
|
||||
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
|
||||
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
assert_eq!(
|
||||
timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
backend.complete_enrollment()?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_ephemeral_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_disable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
let request_id = mcp.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
assert_eq!(
|
||||
remote_control_preference(&state_db, &websocket_url).await?,
|
||||
Some(false)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_status_read_returns_connecting_status_after_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -110,17 +298,17 @@ async fn remote_control_status_read_returns_connecting_status_after_enable() ->
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_enable_request().await?;
|
||||
let _: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let enroll_request = timeout(DEFAULT_TIMEOUT, backend.wait_for_enroll_request()).await??;
|
||||
assert_eq!(
|
||||
enroll_request,
|
||||
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||
);
|
||||
backend.complete_enrollment()?;
|
||||
let _: JSONRPCResponse = timeout(
|
||||
DEFAULT_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let request_id = mcp.send_remote_control_status_read_request().await?;
|
||||
let response: JSONRPCResponse = timeout(
|
||||
@@ -132,7 +320,7 @@ async fn remote_control_status_read_returns_connecting_status_after_enable() ->
|
||||
|
||||
assert_eq!(received.status, RemoteControlConnectionStatus::Connecting);
|
||||
assert!(!received.server_name.is_empty());
|
||||
assert_eq!(received.environment_id, None);
|
||||
assert_eq!(received.environment_id.as_deref(), Some("environment-id"));
|
||||
assert!(!received.installation_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
@@ -235,11 +423,13 @@ async fn remote_control_pairing_start_returns_pairing_artifacts() -> Result<()>
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_pairing_start_returns_pairing_artifacts_while_disabled() -> Result<()> {
|
||||
async fn pairing_start_works_after_ephemeral_enable() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut backend = PairingRemoteControlBackend::start(codex_home.path()).await?;
|
||||
let mut mcp = TestAppServer::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
|
||||
let request_id = mcp.send_remote_control_ephemeral_enable_request().await?;
|
||||
wait_for_response(&mut mcp, request_id).await?;
|
||||
|
||||
let request_id = mcp
|
||||
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||
@@ -333,6 +523,8 @@ async fn remote_control_client_management_works_while_disabled() -> Result<()> {
|
||||
|
||||
struct BlockingRemoteControlBackend {
|
||||
enroll_request_rx: Option<oneshot::Receiver<Result<String>>>,
|
||||
enroll_response_tx: Option<oneshot::Sender<()>>,
|
||||
websocket_url: String,
|
||||
server_task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
@@ -397,12 +589,37 @@ impl ClientManagementRemoteControlBackend {
|
||||
impl BlockingRemoteControlBackend {
|
||||
async fn start(codex_home: &std::path::Path) -> Result<Self> {
|
||||
let listener = configured_remote_control_listener(codex_home).await?;
|
||||
let websocket_url = format!(
|
||||
"ws://{}/backend-api/wham/remote/control/server",
|
||||
listener.local_addr()?
|
||||
);
|
||||
|
||||
let (enroll_request_tx, enroll_request_rx) = oneshot::channel();
|
||||
let (enroll_response_tx, enroll_response_rx) = oneshot::channel();
|
||||
let server_task = tokio::spawn(async move {
|
||||
match read_enroll_request(listener).await {
|
||||
Ok((request_line, _reader)) => {
|
||||
match read_enroll_request(&listener).await {
|
||||
Ok((request_line, reader)) => {
|
||||
let _ = enroll_request_tx.send(Ok(request_line));
|
||||
if enroll_response_rx.await.is_err() {
|
||||
return;
|
||||
}
|
||||
if respond_with_json(
|
||||
reader.into_inner(),
|
||||
serde_json::json!({
|
||||
"server_id": "server-id",
|
||||
"environment_id": "environment-id",
|
||||
"remote_control_token": "remote-control-token",
|
||||
"expires_at": "3026-05-22T12:34:56Z",
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Ok(_websocket) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -413,6 +630,8 @@ impl BlockingRemoteControlBackend {
|
||||
|
||||
Ok(Self {
|
||||
enroll_request_rx: Some(enroll_request_rx),
|
||||
enroll_response_tx: Some(enroll_response_tx),
|
||||
websocket_url,
|
||||
server_task,
|
||||
})
|
||||
}
|
||||
@@ -424,6 +643,18 @@ impl BlockingRemoteControlBackend {
|
||||
.context("enroll request should only be awaited once")?;
|
||||
rx.await?
|
||||
}
|
||||
|
||||
fn complete_enrollment(&mut self) -> Result<()> {
|
||||
self.enroll_response_tx
|
||||
.take()
|
||||
.context("enrollment should only complete once")?
|
||||
.send(())
|
||||
.map_err(|()| anyhow::anyhow!("enrollment response receiver dropped"))
|
||||
}
|
||||
|
||||
fn websocket_url(&self) -> &str {
|
||||
&self.websocket_url
|
||||
}
|
||||
}
|
||||
|
||||
struct PairingRemoteControlBackend {
|
||||
@@ -558,8 +789,8 @@ async fn configured_remote_control_listener(codex_home: &std::path::Path) -> Res
|
||||
Ok(listener)
|
||||
}
|
||||
|
||||
async fn read_enroll_request(listener: TcpListener) -> Result<(String, BufReader<TcpStream>)> {
|
||||
let request = read_http_request(&listener).await?;
|
||||
async fn read_enroll_request(listener: &TcpListener) -> Result<(String, BufReader<TcpStream>)> {
|
||||
let request = read_http_request(listener).await?;
|
||||
Ok((request.request_line, request.reader))
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::create_final_assistant_message_sse_response;
|
||||
use app_test_support::create_mock_responses_server_sequence;
|
||||
use app_test_support::create_request_user_input_sse_response;
|
||||
use app_test_support::to_response;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
@@ -18,15 +17,46 @@ use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use core_test_support::responses;
|
||||
use serde_json::json;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
fn create_request_user_input_sse_response_with_auto_resolution(
|
||||
call_id: &str,
|
||||
auto_resolution_ms: u64,
|
||||
) -> anyhow::Result<String> {
|
||||
let tool_call_arguments = serde_json::to_string(&json!({
|
||||
"questions": [{
|
||||
"id": "confirm_path",
|
||||
"header": "Confirm",
|
||||
"question": "Proceed with the plan?",
|
||||
"options": [{
|
||||
"label": "Yes (Recommended)",
|
||||
"description": "Continue the current plan."
|
||||
}, {
|
||||
"label": "No",
|
||||
"description": "Stop and revisit the approach."
|
||||
}]
|
||||
}],
|
||||
"autoResolutionMs": auto_resolution_ms
|
||||
}))?;
|
||||
|
||||
Ok(responses::sse(vec![
|
||||
responses::ev_response_created("resp-1"),
|
||||
responses::ev_function_call(call_id, "request_user_input", &tool_call_arguments),
|
||||
responses::ev_completed("resp-1"),
|
||||
]))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn request_user_input_round_trip() -> Result<()> {
|
||||
let codex_home = tempfile::TempDir::new()?;
|
||||
let responses = vec![
|
||||
create_request_user_input_sse_response("call1")?,
|
||||
create_request_user_input_sse_response_with_auto_resolution(
|
||||
"call1", /*auto_resolution_ms*/ 60_000,
|
||||
)?,
|
||||
create_final_assistant_message_sse_response("done")?,
|
||||
];
|
||||
let server = create_mock_responses_server_sequence(responses).await;
|
||||
@@ -89,6 +119,7 @@ async fn request_user_input_round_trip() -> Result<()> {
|
||||
assert_eq!(params.turn_id, turn.id);
|
||||
assert_eq!(params.item_id, "call1");
|
||||
assert_eq!(params.questions.len(), 1);
|
||||
assert_eq!(params.auto_resolution_ms, Some(60_000));
|
||||
let resolved_request_id = request_id.clone();
|
||||
|
||||
mcp.send_response(
|
||||
@@ -128,7 +159,6 @@ async fn request_user_input_round_trip() -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io::Result<()> {
|
||||
let config_toml = codex_home.join("config.toml");
|
||||
std::fs::write(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::PathBufExt;
|
||||
@@ -21,6 +22,8 @@ use codex_app_server_protocol::ThreadStartedNotification;
|
||||
use codex_app_server_protocol::ThreadStatus;
|
||||
use codex_app_server_protocol::ThreadStatusChangedNotification;
|
||||
use codex_app_server_protocol::TurnEnvironmentParams;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::UserInput as V2UserInput;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_core::config::set_project_trust_level;
|
||||
@@ -400,11 +403,13 @@ async fn thread_start_response_excludes_empty_project_instruction_source() -> Re
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_without_selected_environment_excludes_instruction_sources() -> Result<()> {
|
||||
async fn thread_start_without_selected_environment_includes_only_global_instruction_source()
|
||||
-> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml_without_approval_policy(codex_home.path(), &server.uri())?;
|
||||
std::fs::write(codex_home.path().join("AGENTS.md"), "global instructions")?;
|
||||
let global_agents_path = codex_home.path().join("AGENTS.md");
|
||||
std::fs::write(&global_agents_path, "global instructions")?;
|
||||
let workspace = TempDir::new()?;
|
||||
std::fs::write(workspace.path().join("AGENTS.md"), "project instructions")?;
|
||||
|
||||
@@ -424,11 +429,56 @@ async fn thread_start_without_selected_environment_excludes_instruction_sources(
|
||||
)
|
||||
.await??;
|
||||
let ThreadStartResponse {
|
||||
thread,
|
||||
instruction_sources,
|
||||
..
|
||||
} = to_response::<ThreadStartResponse>(response)?;
|
||||
|
||||
assert!(instruction_sources.is_empty());
|
||||
assert_eq!(
|
||||
instruction_sources
|
||||
.into_iter()
|
||||
.map(normalize_path_for_comparison)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![normalize_path_for_comparison(std::fs::canonicalize(
|
||||
global_agents_path,
|
||||
)?)]
|
||||
);
|
||||
|
||||
let turn_request_id = mcp
|
||||
.send_turn_start_request(TurnStartParams {
|
||||
thread_id: thread.id,
|
||||
input: vec![V2UserInput::Text {
|
||||
text: "inspect instructions".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(turn_request_id)),
|
||||
)
|
||||
.await??;
|
||||
timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_notification_message("turn/completed"),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let requests = server
|
||||
.received_requests()
|
||||
.await
|
||||
.context("failed to fetch received requests")?;
|
||||
let model_request = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path().ends_with("/responses"))
|
||||
.context("expected model request")?;
|
||||
let model_request_body = model_request
|
||||
.body_json::<Value>()
|
||||
.context("model request body should be JSON")?
|
||||
.to_string();
|
||||
assert!(model_request_body.contains("global instructions"));
|
||||
assert!(!model_request_body.contains("project instructions"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ workspace = true
|
||||
anyhow = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
similar = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
|
||||
@@ -21,6 +21,7 @@ use crate::parser::Hunk;
|
||||
use crate::parser::ParseError;
|
||||
use crate::parser::parse_patch;
|
||||
use crate::unified_diff_from_chunks;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::str::Utf8Error;
|
||||
use tree_sitter::LanguageError;
|
||||
|
||||
@@ -185,7 +186,18 @@ pub async fn verify_apply_patch_args(
|
||||
);
|
||||
}
|
||||
Hunk::DeleteFile { .. } => {
|
||||
let content = match fs.read_file_text(&path, sandbox).await {
|
||||
let path_uri = match PathUri::from_abs_path(&path) {
|
||||
Ok(path_uri) => path_uri,
|
||||
Err(e) => {
|
||||
return MaybeApplyPatchVerified::CorrectnessError(
|
||||
ApplyPatchError::IoError(IoError {
|
||||
context: format!("Failed to read {}", path.display()),
|
||||
source: e,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
let content = match fs.read_file_text(&path_uri, sandbox).await {
|
||||
Ok(content) => content,
|
||||
Err(e) => {
|
||||
return MaybeApplyPatchVerified::CorrectnessError(
|
||||
|
||||
@@ -16,6 +16,7 @@ use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
pub use parser::Hunk;
|
||||
pub use parser::ParseError;
|
||||
use parser::ParseError::*;
|
||||
@@ -390,6 +391,7 @@ async fn apply_hunks_to_files(
|
||||
for hunk in hunks {
|
||||
let affected_path = hunk.path().to_path_buf();
|
||||
let path_abs = hunk.resolve_path(cwd);
|
||||
let path_uri = PathUri::from_abs_path(&path_abs)?;
|
||||
match hunk {
|
||||
Hunk::AddFile { contents, .. } => {
|
||||
let overwritten_content =
|
||||
@@ -415,7 +417,7 @@ async fn apply_hunks_to_files(
|
||||
}
|
||||
Hunk::DeleteFile { .. } => {
|
||||
note_existing_path_delta_support(&path_abs, fs, sandbox, &mut delta.exact).await;
|
||||
let deleted_content = fs.read_file_text(&path_abs, sandbox).await.ok();
|
||||
let deleted_content = fs.read_file_text(&path_uri, sandbox).await.ok();
|
||||
if deleted_content.is_none() {
|
||||
delta.exact = false;
|
||||
}
|
||||
@@ -424,7 +426,7 @@ async fn apply_hunks_to_files(
|
||||
.with_context(|| format!("Failed to delete file {}", path_abs.display()))?;
|
||||
if let Err(error) = fs
|
||||
.remove(
|
||||
&path_abs,
|
||||
&path_uri,
|
||||
RemoveOptions {
|
||||
recursive: false,
|
||||
force: false,
|
||||
@@ -488,7 +490,7 @@ async fn apply_hunks_to_files(
|
||||
})?;
|
||||
if let Err(error) = fs
|
||||
.remove(
|
||||
&path_abs,
|
||||
&path_uri,
|
||||
RemoveOptions {
|
||||
recursive: false,
|
||||
force: false,
|
||||
@@ -521,7 +523,7 @@ async fn apply_hunks_to_files(
|
||||
modified.push(affected_path);
|
||||
} else {
|
||||
try_write!(
|
||||
fs.write_file(&path_abs, new_contents.clone().into_bytes(), sandbox)
|
||||
fs.write_file(&path_uri, new_contents.clone().into_bytes(), sandbox)
|
||||
.await
|
||||
.with_context(|| format!(
|
||||
"Failed to write file {}",
|
||||
@@ -554,7 +556,8 @@ async fn ensure_not_directory(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> io::Result<()> {
|
||||
let metadata = fs.get_metadata(path, sandbox).await?;
|
||||
let path_uri = PathUri::from_abs_path(path)?;
|
||||
let metadata = fs.get_metadata(&path_uri, sandbox).await?;
|
||||
if metadata.is_directory {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -570,9 +573,12 @@ async fn remove_failure_was_side_effect_free(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> bool {
|
||||
let Ok(path_uri) = PathUri::from_abs_path(path) else {
|
||||
return false;
|
||||
};
|
||||
match expected_content {
|
||||
Some(expected_content) => fs
|
||||
.read_file_text(path, sandbox)
|
||||
.read_file_text(&path_uri, sandbox)
|
||||
.await
|
||||
.is_ok_and(|content| content == expected_content),
|
||||
None => false,
|
||||
@@ -586,7 +592,14 @@ async fn read_optional_file_text_for_delta(
|
||||
exact: &mut bool,
|
||||
) -> Option<String> {
|
||||
note_existing_path_delta_support(path, fs, sandbox, exact).await;
|
||||
match fs.read_file_text(path, sandbox).await {
|
||||
let path_uri = match PathUri::from_abs_path(path) {
|
||||
Ok(path_uri) => path_uri,
|
||||
Err(_) => {
|
||||
*exact = false;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match fs.read_file_text(&path_uri, sandbox).await {
|
||||
Ok(content) => Some(content),
|
||||
Err(source) if source.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(_) => {
|
||||
@@ -602,7 +615,11 @@ async fn note_existing_path_delta_support(
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
exact: &mut bool,
|
||||
) {
|
||||
match fs.get_metadata(path, sandbox).await {
|
||||
let Ok(path_uri) = PathUri::from_abs_path(path) else {
|
||||
*exact = false;
|
||||
return;
|
||||
};
|
||||
match fs.get_metadata(&path_uri, sandbox).await {
|
||||
Ok(metadata) if metadata.is_file && !metadata.is_symlink => {}
|
||||
Ok(_) => *exact = false,
|
||||
Err(source) if source.kind() == io::ErrorKind::NotFound => {}
|
||||
@@ -616,12 +633,14 @@ async fn write_file_with_missing_parent_retry(
|
||||
contents: Vec<u8>,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> anyhow::Result<()> {
|
||||
match fs.write_file(path_abs, contents.clone(), sandbox).await {
|
||||
let path_uri = PathUri::from_abs_path(path_abs)?;
|
||||
match fs.write_file(&path_uri, contents.clone(), sandbox).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
if let Some(parent_abs) = path_abs.parent() {
|
||||
let parent_uri = PathUri::from_abs_path(&parent_abs)?;
|
||||
fs.create_directory(
|
||||
&parent_abs,
|
||||
&parent_uri,
|
||||
CreateDirectoryOptions { recursive: true },
|
||||
sandbox,
|
||||
)
|
||||
@@ -633,7 +652,7 @@ async fn write_file_with_missing_parent_retry(
|
||||
)
|
||||
})?;
|
||||
}
|
||||
fs.write_file(path_abs, contents, sandbox)
|
||||
fs.write_file(&path_uri, contents, sandbox)
|
||||
.await
|
||||
.with_context(|| format!("Failed to write file {}", path_abs.display()))?;
|
||||
Ok(())
|
||||
@@ -657,7 +676,8 @@ async fn derive_new_contents_from_chunks(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> std::result::Result<AppliedPatch, ApplyPatchError> {
|
||||
let original_contents = fs.read_file_text(path_abs, sandbox).await.map_err(|err| {
|
||||
let path_uri = PathUri::from_abs_path(path_abs)?;
|
||||
let original_contents = fs.read_file_text(&path_uri, sandbox).await.map_err(|err| {
|
||||
ApplyPatchError::IoError(IoError {
|
||||
context: format!("Failed to read file to update {}", path_abs.display()),
|
||||
source: err,
|
||||
|
||||
@@ -8,7 +8,6 @@ license.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait.workspace = true
|
||||
tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread", "time"] }
|
||||
tokio-util.workspace = true
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use async_trait::async_trait;
|
||||
use std::future::Future;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -7,14 +6,15 @@ pub enum CancelErr {
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait OrCancelExt: Sized {
|
||||
type Output;
|
||||
|
||||
async fn or_cancel(self, token: &CancellationToken) -> Result<Self::Output, CancelErr>;
|
||||
fn or_cancel(
|
||||
self,
|
||||
token: &CancellationToken,
|
||||
) -> impl Future<Output = Result<Self::Output, CancelErr>> + Send;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<F> OrCancelExt for F
|
||||
where
|
||||
F: Future + Send,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate", "multiplatform_binaries")
|
||||
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate")
|
||||
load("//bazel/platforms:release_binaries.bzl", "multiplatform_binaries")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "cli",
|
||||
|
||||
@@ -33,6 +33,7 @@ codex-utils-cli = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-core-plugins = { workspace = true }
|
||||
codex-home = { workspace = true }
|
||||
codex-exec = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-execpolicy = { workspace = true }
|
||||
|
||||
@@ -1324,6 +1324,7 @@ fn stored_auth_mode(auth: &codex_login::AuthDotJson) -> &'static str {
|
||||
codex_app_server_protocol::AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
|
||||
codex_app_server_protocol::AuthMode::AgentIdentity => "agent_identity",
|
||||
codex_app_server_protocol::AuthMode::PersonalAccessToken => "personal_access_token",
|
||||
codex_app_server_protocol::AuthMode::BedrockApiKey => "bedrock_api_key",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1331,10 +1332,12 @@ fn stored_auth_mode_value(auth: &AuthDotJson) -> codex_app_server_protocol::Auth
|
||||
if let Some(mode) = auth.auth_mode {
|
||||
return mode;
|
||||
}
|
||||
if auth.openai_api_key.is_some() {
|
||||
codex_app_server_protocol::AuthMode::ApiKey
|
||||
} else if auth.personal_access_token.is_some() {
|
||||
if auth.personal_access_token.is_some() {
|
||||
codex_app_server_protocol::AuthMode::PersonalAccessToken
|
||||
} else if auth.bedrock_api_key.is_some() {
|
||||
codex_app_server_protocol::AuthMode::BedrockApiKey
|
||||
} else if auth.openai_api_key.is_some() {
|
||||
codex_app_server_protocol::AuthMode::ApiKey
|
||||
} else {
|
||||
codex_app_server_protocol::AuthMode::Chatgpt
|
||||
}
|
||||
@@ -1407,6 +1410,11 @@ fn stored_auth_issues(
|
||||
issues.push("personal access token auth is missing a personal access token");
|
||||
}
|
||||
}
|
||||
codex_app_server_protocol::AuthMode::BedrockApiKey => {
|
||||
if auth.bedrock_api_key.is_none() {
|
||||
issues.push("Bedrock API key auth is missing a Bedrock API key");
|
||||
}
|
||||
}
|
||||
}
|
||||
issues
|
||||
}
|
||||
@@ -2437,6 +2445,7 @@ fn auth_mode_name(auth: &CodexAuth) -> &'static str {
|
||||
codex_app_server_protocol::AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
|
||||
codex_app_server_protocol::AuthMode::AgentIdentity => "agent_identity",
|
||||
codex_app_server_protocol::AuthMode::PersonalAccessToken => "personal_access_token",
|
||||
codex_app_server_protocol::AuthMode::BedrockApiKey => "bedrock_api_key",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2566,7 +2575,10 @@ fn provider_auth_reachability_mode_from_auth(
|
||||
return ProviderAuthReachabilityMode::Chatgpt;
|
||||
}
|
||||
match stored_auth.map(stored_auth_mode_value) {
|
||||
Some(codex_app_server_protocol::AuthMode::ApiKey) => ProviderAuthReachabilityMode::ApiKey,
|
||||
Some(
|
||||
codex_app_server_protocol::AuthMode::ApiKey
|
||||
| codex_app_server_protocol::AuthMode::BedrockApiKey,
|
||||
) => ProviderAuthReachabilityMode::ApiKey,
|
||||
Some(
|
||||
codex_app_server_protocol::AuthMode::Chatgpt
|
||||
| codex_app_server_protocol::AuthMode::ChatgptAuthTokens
|
||||
@@ -3471,6 +3483,7 @@ mod tests {
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
@@ -3489,6 +3502,7 @@ mod tests {
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
@@ -3509,6 +3523,7 @@ mod tests {
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: Some("at-test".to_string()),
|
||||
bedrock_api_key: None,
|
||||
};
|
||||
|
||||
assert_eq!(stored_auth_mode(&auth), "personal_access_token");
|
||||
@@ -3531,6 +3546,7 @@ mod tests {
|
||||
last_refresh: None,
|
||||
agent_identity: None,
|
||||
personal_access_token: None,
|
||||
bedrock_api_key: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
|
||||
@@ -207,6 +207,7 @@ pub async fn run_login_with_access_token(
|
||||
&config.codex_home,
|
||||
&access_token,
|
||||
config.cli_auth_credentials_store_mode,
|
||||
config.forced_chatgpt_workspace_id.as_deref(),
|
||||
Some(&config.chatgpt_base_url),
|
||||
)
|
||||
.await
|
||||
@@ -395,6 +396,10 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
|
||||
eprintln!("Logged in using personal access token");
|
||||
std::process::exit(0);
|
||||
}
|
||||
AuthMode::BedrockApiKey => {
|
||||
eprintln!("Logged in using Amazon Bedrock API key");
|
||||
std::process::exit(0);
|
||||
}
|
||||
},
|
||||
Ok(None) => {
|
||||
eprintln!("Not logged in");
|
||||
|
||||
+152
-19
@@ -36,11 +36,12 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::ProfileV2Name;
|
||||
use codex_utils_cli::SharedCliOptions;
|
||||
use codex_utils_cli::resume_hint;
|
||||
use owo_colors::OwoColorize;
|
||||
use std::collections::HashSet;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use supports_color::Stream;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
@@ -75,6 +76,7 @@ use codex_core::config::resolve_profile_v2_config_path;
|
||||
use codex_features::FEATURES;
|
||||
use codex_features::Stage;
|
||||
use codex_features::is_known_feature_key;
|
||||
use codex_home::CodexHomeUserInstructionsProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::read_codex_access_token_from_env;
|
||||
@@ -180,6 +182,9 @@ enum Subcommand {
|
||||
/// Archive a saved session by id or session name.
|
||||
Archive(SessionArchiveCommand),
|
||||
|
||||
/// Permanently delete a saved session by id or session name.
|
||||
Delete(DeleteCommand),
|
||||
|
||||
/// Unarchive a saved session by id or session name.
|
||||
Unarchive(SessionArchiveCommand),
|
||||
|
||||
@@ -354,6 +359,16 @@ struct SessionArchiveConfigOverrides {
|
||||
config_overrides: CliConfigOverrides,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct DeleteCommand {
|
||||
#[clap(flatten)]
|
||||
session: SessionArchiveCommand,
|
||||
|
||||
/// Delete without prompting. SESSION must be a UUID.
|
||||
#[arg(long, default_value_t = false)]
|
||||
force: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
struct ForkCommand {
|
||||
/// Conversation/session id (UUID). When provided, forks this session.
|
||||
@@ -518,7 +533,7 @@ struct AppServerCommand {
|
||||
#[arg(long = "stdio", conflicts_with = "listen")]
|
||||
stdio: bool,
|
||||
|
||||
/// Enable remote control for this app-server process.
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
|
||||
@@ -685,10 +700,11 @@ fn parse_socket_path(raw: &str) -> Result<AbsolutePathBuf, String> {
|
||||
}
|
||||
|
||||
fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<String> {
|
||||
let is_fatal = matches!(&exit_info.exit_reason, ExitReason::Fatal(_));
|
||||
let AppExitInfo {
|
||||
token_usage,
|
||||
thread_id: conversation_id,
|
||||
thread_name,
|
||||
resume_hint,
|
||||
..
|
||||
} = exit_info;
|
||||
|
||||
@@ -697,13 +713,15 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
|
||||
lines.push(token_usage.to_string());
|
||||
}
|
||||
|
||||
if let Some(resume_cmd) = resume_hint(thread_name.as_deref(), conversation_id) {
|
||||
if let Some(resume_cmd) = resume_hint {
|
||||
let command = if color_enabled {
|
||||
resume_cmd.cyan().to_string()
|
||||
} else {
|
||||
resume_cmd
|
||||
};
|
||||
lines.push(format!("To continue this session, run {command}"));
|
||||
} else if is_fatal && let Some(conversation_id) = conversation_id {
|
||||
lines.push(format!("Session ID: {conversation_id}"));
|
||||
}
|
||||
|
||||
lines
|
||||
@@ -711,19 +729,23 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
|
||||
|
||||
/// Handle the app exit and print the results. Optionally run the update action.
|
||||
fn handle_app_exit(exit_info: AppExitInfo) -> anyhow::Result<()> {
|
||||
match exit_info.exit_reason {
|
||||
let is_fatal = match &exit_info.exit_reason {
|
||||
ExitReason::Fatal(message) => {
|
||||
eprintln!("ERROR: {message}");
|
||||
std::process::exit(1);
|
||||
true
|
||||
}
|
||||
ExitReason::UserRequested => { /* normal exit */ }
|
||||
}
|
||||
ExitReason::UserRequested => false,
|
||||
};
|
||||
|
||||
let update_action = exit_info.update_action;
|
||||
let color_enabled = supports_color::on(Stream::Stdout).is_some();
|
||||
for line in format_exit_messages(exit_info, color_enabled) {
|
||||
println!("{line}");
|
||||
}
|
||||
if is_fatal {
|
||||
std::io::stdout().flush()?;
|
||||
std::process::exit(1);
|
||||
}
|
||||
if let Some(action) = update_action {
|
||||
run_update_action(action)?;
|
||||
}
|
||||
@@ -829,6 +851,17 @@ async fn run_session_archive_cli_command(
|
||||
.map_err(|err| anyhow::anyhow!("{err}"))
|
||||
}
|
||||
|
||||
fn delete_action(target: &str, force: bool) -> anyhow::Result<codex_tui::SessionArchiveAction> {
|
||||
if force && codex_protocol::ThreadId::from_string(target).is_err() {
|
||||
anyhow::bail!("--force requires a session UUID; names must be confirmed interactively");
|
||||
}
|
||||
let confirmation = match force {
|
||||
true => codex_tui::DeleteConfirmation::Skip,
|
||||
false => codex_tui::DeleteConfirmation::Prompt,
|
||||
};
|
||||
Ok(codex_tui::SessionArchiveAction::Delete(confirmation))
|
||||
}
|
||||
|
||||
async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Result<()> {
|
||||
match cmd.subcommand {
|
||||
DebugAppServerSubcommand::SendMessageV2(cmd) => {
|
||||
@@ -920,13 +953,17 @@ fn stage_str(stage: Stage) -> &'static str {
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
|
||||
cli_main(arg0_paths).await?;
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
cli_main(arg0_paths, remote_control_disabled).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
async fn cli_main(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
remote_control_disabled: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let MultitoolCli {
|
||||
config_overrides: mut root_config_overrides,
|
||||
feature_toggles,
|
||||
@@ -1085,7 +1122,18 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
};
|
||||
let auth = auth.try_into_settings()?;
|
||||
let runtime_options = codex_app_server::AppServerRuntimeOptions {
|
||||
remote_control_enabled: remote_control,
|
||||
remote_control_startup_mode: match (remote_control, remote_control_disabled)
|
||||
{
|
||||
(true, _) => {
|
||||
codex_app_server::RemoteControlStartupMode::EnabledEphemeral
|
||||
}
|
||||
(false, true) => {
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral
|
||||
}
|
||||
(false, false) => {
|
||||
codex_app_server::RemoteControlStartupMode::ResolvePersisted
|
||||
}
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
codex_app_server::run_main_with_transport_options(
|
||||
@@ -1233,6 +1281,20 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
.await?;
|
||||
println!("{output}");
|
||||
}
|
||||
Some(Subcommand::Delete(DeleteCommand { session, force })) => {
|
||||
let action = delete_action(&session.target, force)?;
|
||||
let output = run_session_archive_cli_command(
|
||||
action,
|
||||
session,
|
||||
interactive,
|
||||
root_config_overrides.clone(),
|
||||
root_remote.clone(),
|
||||
root_remote_auth_token_env.clone(),
|
||||
arg0_paths.clone(),
|
||||
)
|
||||
.await?;
|
||||
println!("{output}");
|
||||
}
|
||||
Some(Subcommand::Unarchive(cmd)) => {
|
||||
let output = run_session_archive_cli_command(
|
||||
codex_tui::SessionArchiveAction::Unarchive,
|
||||
@@ -1597,6 +1659,7 @@ fn profile_v2_for_subcommand<'a>(
|
||||
| Subcommand::Review(_)
|
||||
| Subcommand::Resume(_)
|
||||
| Subcommand::Archive(_)
|
||||
| Subcommand::Delete(_)
|
||||
| Subcommand::Unarchive(_)
|
||||
| Subcommand::Fork(_)
|
||||
| Subcommand::Mcp(_)
|
||||
@@ -1605,7 +1668,7 @@ fn profile_v2_for_subcommand<'a>(
|
||||
subcommand: DebugSubcommand::PromptInput(_),
|
||||
}) => Ok(Some(profile_v2)),
|
||||
_ => anyhow::bail!(
|
||||
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex archive`, `codex unarchive`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
|
||||
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex archive`, `codex delete`, `codex unarchive`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -1895,7 +1958,16 @@ async fn run_debug_prompt_input_command(
|
||||
});
|
||||
}
|
||||
|
||||
let prompt_input = codex_core::build_prompt_input(config, input, /*state_db*/ None).await?;
|
||||
let user_instructions_provider = Arc::new(CodexHomeUserInstructionsProvider::new(
|
||||
config.codex_home.clone(),
|
||||
));
|
||||
let prompt_input = codex_core::build_prompt_input(
|
||||
config,
|
||||
input,
|
||||
/*state_db*/ None,
|
||||
user_instructions_provider,
|
||||
)
|
||||
.await?;
|
||||
println!("{}", serde_json::to_string_pretty(&prompt_input)?);
|
||||
|
||||
Ok(())
|
||||
@@ -2026,6 +2098,7 @@ fn unsupported_subcommand_name_for_strict_config(
|
||||
| Some(Subcommand::ExecServer(_))
|
||||
| Some(Subcommand::Resume(_))
|
||||
| Some(Subcommand::Archive(_))
|
||||
| Some(Subcommand::Delete(_))
|
||||
| Some(Subcommand::Unarchive(_))
|
||||
| Some(Subcommand::Fork(_))
|
||||
| Some(Subcommand::Doctor(_)) => None,
|
||||
@@ -2600,6 +2673,14 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_remains_an_interactive_prompt() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "import"]).expect("parse");
|
||||
|
||||
assert!(cli.subcommand.is_none());
|
||||
assert_eq!(cli.interactive.prompt.as_deref(), Some("import"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_v2_rejects_non_plain_names_at_parse_time() {
|
||||
assert!(
|
||||
@@ -2860,6 +2941,17 @@ mod tests {
|
||||
assert!(interactive.bypass_hook_trust);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_force_requires_uuid() {
|
||||
assert!(delete_action("123e4567-e89b-12d3-a456-426614174000", true).is_ok());
|
||||
|
||||
let err = delete_action("my-thread", true).expect_err("name should require prompt");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"--force requires a session UUID; names must be confirmed interactively"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
|
||||
#[test]
|
||||
fn sandbox_parses_permissions_profile() {
|
||||
@@ -2978,12 +3070,13 @@ mod tests {
|
||||
total_tokens: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let thread_id = conversation_id
|
||||
.map(ThreadId::from_string)
|
||||
.map(Result::unwrap);
|
||||
AppExitInfo {
|
||||
token_usage,
|
||||
thread_id: conversation_id
|
||||
.map(ThreadId::from_string)
|
||||
.map(Result::unwrap),
|
||||
thread_name: thread_name.map(str::to_string),
|
||||
thread_id,
|
||||
resume_hint: codex_utils_cli::resume_hint(thread_name, thread_id),
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
}
|
||||
@@ -2994,7 +3087,7 @@ mod tests {
|
||||
let exit_info = AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: None,
|
||||
thread_name: None,
|
||||
resume_hint: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
};
|
||||
@@ -3002,6 +3095,40 @@ mod tests {
|
||||
assert!(lines.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_exit_messages_includes_session_id_for_fatal_exit_without_resume_hint() {
|
||||
let exit_info = AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: Some(ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap()),
|
||||
resume_hint: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::Fatal("boom".to_string()),
|
||||
};
|
||||
let lines = format_exit_messages(exit_info, /*color_enabled*/ false);
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec!["Session ID: 123e4567-e89b-12d3-a456-426614174000".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_exit_messages_includes_resume_hint_for_fatal_exit() {
|
||||
let mut exit_info = sample_exit_info(
|
||||
Some("123e4567-e89b-12d3-a456-426614174000"),
|
||||
/*thread_name*/ None,
|
||||
);
|
||||
exit_info.exit_reason = ExitReason::Fatal("boom".to_string());
|
||||
let lines = format_exit_messages(exit_info, /*color_enabled*/ false);
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec![
|
||||
"Token usage: total=2 input=0 output=2".to_string(),
|
||||
"To continue this session, run codex resume 123e4567-e89b-12d3-a456-426614174000"
|
||||
.to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_exit_messages_includes_resume_hint_without_color() {
|
||||
let exit_info = sample_exit_info(
|
||||
@@ -3299,6 +3426,12 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_remote_control_startup_flag_enables_remote_control() {
|
||||
let enabled = app_server_from_args(["codex", "app-server", "--remote-control"].as_ref());
|
||||
assert!(enabled.remote_control);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_analytics_default_enabled_with_flag() {
|
||||
let app_server =
|
||||
|
||||
@@ -204,7 +204,7 @@ pub async fn run_plugin_list(
|
||||
..
|
||||
} = load_plugin_command_context(overrides).await?;
|
||||
let outcome = manager
|
||||
.list_marketplaces_for_config(&plugins_input, &[])
|
||||
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list marketplace plugins")?;
|
||||
ensure_configured_marketplace_snapshots_loaded(
|
||||
codex_home.as_path(),
|
||||
@@ -609,7 +609,7 @@ fn find_marketplace_for_plugin(
|
||||
plugin_name: &str,
|
||||
) -> Result<ConfiguredMarketplace> {
|
||||
let outcome = manager
|
||||
.list_marketplaces_for_config(plugins_input, &[])
|
||||
.list_marketplaces_for_config(plugins_input, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list marketplace plugins")?;
|
||||
ensure_configured_marketplace_snapshots_loaded(
|
||||
codex_home,
|
||||
|
||||
@@ -115,7 +115,7 @@ async fn run_foreground_remote_control(
|
||||
socket_path: socket_path.clone(),
|
||||
};
|
||||
let runtime_options = AppServerRuntimeOptions {
|
||||
remote_control_enabled: true,
|
||||
remote_control_startup_mode: codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
install_shutdown_signal_handler: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user