Route in-memory message board notifications through app-server (#63641)

## Why

The SQLite message board can queue native agent mail through app-server.
In-memory boards previously relied on the host's notification callback
for delivery.

## What changed

Add `launch_in_memory_with_app_server` so runners can opt into the same
bounded, queue-only delivery as SQLite via `thread/inject_items`. The
host still resolves agent membership, and the shared notification client
queues post previews without starting a turn.

## Testing

Extend the app-server integration test to check that, after an
app-server restart, a post from each backend reaches an idle worker
exactly once on its next turn. The test also checks that app-server
delivery bypasses the in-memory host's notification callback.

GitOrigin-RevId: fc01b5e3f43dcfca5f43366f0b184c41dc07f9eb
This commit is contained in:
jif
2026-11-24 13:50:12 +00:00
committed by copyberry
parent e351ffa4b6
commit 75df5098a6
11 changed files with 213 additions and 81 deletions
+1
View File
@@ -2147,6 +2147,7 @@ dependencies = [
"codex-memories-extension",
"codex-memories-write",
"codex-message-board",
"codex-message-board-mcp",
"codex-model-provider",
"codex-model-provider-info",
"codex-models-manager",
+1
View File
@@ -11,6 +11,7 @@ codex_rust_crate(
"//codex-rs/message-board-mcp:codex-message-board-mcp",
"//codex-rs/rmcp-client:test_stdio_server",
],
integration_compile_data_extra = ["//codex-rs/message-board:tests/common/mod.rs"],
integration_test_timeout = "long",
run_tests_with_wine_exec = True,
test_shard_counts = {
+1
View File
@@ -136,6 +136,7 @@ codex-windows-sandbox = { workspace = true }
[dev-dependencies]
codex-message-board = { workspace = true }
codex-message-board-mcp = { workspace = true }
zip = { workspace = true }
codex-uds = { workspace = true }
app_test_support = { workspace = true }
@@ -1,4 +1,4 @@
//! Board tools share namespace metadata; the detached SQLite server delivers native agent mail.
//! Board tools share namespace metadata; SQLite and in-memory MCP servers deliver native agent mail.
use super::connection_handling_websocket as websocket;
use anyhow::Context;
@@ -9,16 +9,24 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput;
use codex_features::Feature;
use codex_message_board_mcp::AppServerNotifications;
use codex_message_board_mcp::launch_in_memory_with_app_server;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_rmcp_client::RmcpClient;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::sync::Arc;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::time::Duration;
use tokio::time::timeout;
#[path = "../../../../message-board/tests/common/mod.rs"]
mod board_host;
#[test_case::test_case(None, "collaboration"; "default_namespace")]
#[test_case::test_case(Some("agents"), "agents"; "configured_namespace")]
#[tokio::test]
@@ -135,6 +143,10 @@ async fn board_tools_share_multi_agent_namespace(
.await??
.context("board server readiness")?;
let ready: Value = serde_json::from_str(&ready)?;
let in_memory = launch_in_memory_with_app_server(Arc::new(
AppServerNotifications::connect(format!("ws://{address}").parse()?).await?,
))
.await?;
// The board must reconnect before sending its first notice after a known disconnect.
app_process.kill().await?;
let (restarted, _) = websocket::spawn_websocket_server_with_args(
@@ -180,52 +192,102 @@ async fn board_tools_share_multi_agent_namespace(
Some(json!({"threadId":root,"input":[{"type":"text","text":"Spawn a worker."}]})),
)
.await?;
let mut child_id = None;
for _ in 0..2 {
let completion = websocket::read_notification_for_method(&mut ws, "turn/completed").await?;
assert_eq!(
completion.params.context("completion params")?["turn"]["status"],
"completed"
);
let params = completion.params.context("completion params")?;
assert_eq!(params["turn"]["status"], "completed");
let thread_id = params["threadId"].as_str().context("completed thread")?;
if thread_id != root {
child_id = Some(ThreadId::from_string(thread_id)?);
}
}
let client = RmcpClient::new_streamable_http_client(
"sqlite-notifications",
ready["url"].as_str().context("board URL")?,
Some("sqlite-notifications-test-token".into()),
/*http_headers*/ None,
/*env_http_headers*/ None,
codex_config::types::OAuthCredentialsStoreMode::File,
Default::default(),
codex_exec_server::Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
)
.await?;
client
.initialize(
rmcp::model::InitializeRequestParams::default(),
/*timeout*/ None,
Box::new(|_, _| Box::pin(async { anyhow::bail!("unexpected elicitation") })),
let root_id = ThreadId::from_string(&root)?;
let child_id = child_id.context("native child")?;
let host = Arc::new(board_host::Host {
members: [
(root_id, AgentPath::root()),
(
child_id,
AgentPath::root()
.join("worker")
.map_err(anyhow::Error::msg)?,
),
]
.into(),
clock: Default::default(),
fail_clock: true.into(),
agent_path_calls: Default::default(),
active: true.into(),
fail_notifications: false.into(),
notifications: Default::default(),
});
in_memory
.bind_agent(root_id.into(), root_id, host.clone())
.await?;
in_memory
.bind_agent(root_id.into(), child_id, host.clone())
.await?;
let mut notifications = Vec::new();
for (backend, url, token) in [
(
"SQLite",
ready["url"].as_str().context("board URL")?,
"sqlite-notifications-test-token",
),
(
"in-memory",
in_memory.url(),
in_memory
.authorization()
.to_str()?
.strip_prefix("Bearer ")
.context("in-memory bearer token")?,
),
] {
let client = RmcpClient::new_streamable_http_client(
"board-notifications",
url,
Some(token.into()),
/*http_headers*/ None,
/*env_http_headers*/ None,
codex_config::types::OAuthCredentialsStoreMode::File,
Default::default(),
codex_exec_server::Environment::default_for_tests().get_http_client(),
/*auth_provider*/ None,
)
.await?;
let posted = client
.call_tool(
"post".into(),
Some(json!({
"new_channel_name":"delivery",
"text":"A notice from the detached SQLite board.",
"agents_to_notify":["/root/worker"]
})),
|_| Ok(Some(json!({"threadId":root,"sessionId":root}))),
/*timeout*/ None,
)
.await?;
assert_ne!(posted.is_error, Some(true), "{posted:?}");
let post = posted.structured_content.context("posted metadata")?;
let notification = format!(
"Message Type: CHANNEL_POST\nSender: /root\nChannel: delivery\nMessage ID: {}\nThread ID: {}\nPayload:\nA notice from the detached SQLite board.",
post["message_id"].as_str().context("message id")?,
post["thread_id"].as_str().context("thread id")?,
);
client
.initialize(
rmcp::model::InitializeRequestParams::default(),
/*timeout*/ None,
Box::new(|_, _| Box::pin(async { anyhow::bail!("unexpected elicitation") })),
)
.await?;
let text = format!("A notice from the detached {backend} board.");
let posted = client
.call_tool(
"post".into(),
Some(json!({
"new_channel_name":"delivery",
"text":text,
"agents_to_notify":["/root/worker"]
})),
|_| Ok(Some(json!({"threadId":root,"sessionId":root}))),
/*timeout*/ None,
)
.await?;
assert_ne!(posted.is_error, Some(true), "{posted:?}");
let post = posted.structured_content.context("posted metadata")?;
notifications.push(format!(
"Message Type: CHANNEL_POST\nSender: /root\nChannel: delivery\nMessage ID: {}\nThread ID: {}\nPayload:\n{text}",
post["message_id"].as_str().context("message id")?,
post["thread_id"].as_str().context("thread id")?,
));
client.shutdown().await;
}
// Queue-only mail must be available when the parent follows up with its idle child.
let delivered = responses::mount_sse_sequence(
@@ -274,17 +336,24 @@ async fn board_tools_share_multi_agent_namespace(
.map(responses::strip_metadata_from_json)
.map(responses::strip_response_item_ids_from_json)
.collect::<Vec<_>>();
for notification in notifications {
assert_eq!(
delivered_items
.iter()
.filter(|item| item["content"] == json!([{"type":"input_text","text":notification}]))
.collect::<Vec<_>>(),
vec![&json!({
"type":"agent_message","author":"/root","recipient":"/root/worker",
"content":[{"type":"input_text","text":notification}]
})],
);
}
in_memory.shutdown().await?;
assert_eq!(
delivered_items
.iter()
.filter(|item| item["content"] == json!([{"type":"input_text","text":notification}]))
.collect::<Vec<_>>(),
vec![&json!({
"type":"agent_message","author":"/root","recipient":"/root/worker",
"content":[{"type":"input_text","text":notification}]
})],
*host.notifications.lock().expect("host notifications"),
Vec::new(),
"app-server delivery must bypass the host callback"
);
client.shutdown().await;
board_process.kill().await?;
app_process.kill().await?;
Ok(())
+32 -4
View File
@@ -12,7 +12,11 @@ use codex_app_server_remote_client::RemoteAppServerClient;
use codex_app_server_remote_client::RemoteAppServerConnectArgs;
use codex_app_server_remote_client::RemoteAppServerEndpoint;
use codex_app_server_remote_client::RemoteAppServerRequestHandle;
use codex_message_board::NotificationDelivery;
use codex_message_board::PostPreview;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::protocol::InterAgentCommunication;
use std::sync::Arc;
use std::sync::Mutex;
@@ -35,13 +39,16 @@ struct Connection {
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
pub(super) struct AppServer {
/// Shared local app-server connection for bounded, queue-only board notifications.
/// The caller must validate the recipient's membership before delivering a notice.
pub struct AppServerNotifications {
url: Url,
connection: Mutex<Arc<OnceCell<Connection>>>,
}
impl AppServer {
pub(super) async fn connect(url: Url) -> anyhow::Result<Self> {
impl AppServerNotifications {
/// Connects to a loopback WebSocket endpoint using the shared app-server client.
pub async fn connect(url: Url) -> anyhow::Result<Self> {
anyhow::ensure!(
url.scheme() == "ws"
&& match url.host() {
@@ -65,7 +72,28 @@ impl AppServer {
})
}
pub(super) async fn inject(
/// Delivers the existing post preview through `thread/inject_items`.
/// Notices retain the 1,024-byte budget and are never replayed after failure.
pub async fn notify(
&self,
recipient: ThreadId,
path: AgentPath,
post: PostPreview,
) -> codex_protocol::error::Result<NotificationDelivery> {
let notice = InterAgentCommunication::new(
post.metadata.author.clone(),
path,
Vec::new(),
post.notification_text(),
/*trigger_turn*/ false,
);
self.inject(recipient, notice)
.await
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?;
Ok(NotificationDelivery::Accepted)
}
async fn inject(
&self,
recipient: ThreadId,
notice: InterAgentCommunication,
@@ -1,7 +1,7 @@
#![cfg(test)]
//! Exercise bounded, concurrent notification delivery and recovery without replay.
use super::AppServer;
use super::AppServerNotifications;
use anyhow::Context;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
@@ -21,7 +21,7 @@ use tokio_tungstenite::tungstenite::Message;
async fn bounded_concurrent_notices_recover_without_replay() -> anyhow::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let (client, mut peer) = tokio::try_join!(
AppServer::connect(format!("ws://{}", listener.local_addr()?).parse()?),
AppServerNotifications::connect(format!("ws://{}", listener.local_addr()?).parse()?),
accept_connection(&listener),
)?;
let recipient = ThreadId::new();
+3
View File
@@ -2,12 +2,15 @@
//! Bound adapters fix caller identity; HTTP validates it against the configured host.
//! Storage, permissions and notification delivery remain owned by the board.
mod app_server;
mod http;
mod local;
pub use app_server::AppServerNotifications;
pub use http::serve_http;
pub use local::LocalServer;
pub use local::launch_in_memory;
pub use local::launch_in_memory_with_app_server;
use codex_attachment_store::InlineAttachmentStore;
use codex_message_board::AgentMessageBoard;
+48 -8
View File
@@ -1,7 +1,9 @@
//! Runner-owned HTTP lifecycle over the existing in-memory board and host interfaces.
//! Agent-specific bindings share tree state while retaining each caller's host.
//! Timestamps use the MCP backend's system clock, independently of the agent clock.
//! Runners can supply app-server delivery without replacing host membership.
use crate::AppServerNotifications;
use crate::MessageBoardMcpServer;
use crate::serve_http;
use axum::http::HeaderValue;
@@ -17,6 +19,7 @@ use codex_message_board::PostPreview;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result;
use futures::future::BoxFuture;
use rmcp::ErrorData;
@@ -31,20 +34,23 @@ use tokio_util::sync::CancellationToken;
type BoardBinding = (Arc<dyn AgentMessageBoard>, Arc<dyn MessageBoardHost>);
type Boards = Arc<RwLock<HashMap<(SessionId, Option<ThreadId>), BoardBinding>>>;
struct BackendClockHost(Arc<dyn MessageBoardHost>);
struct LocalHost {
membership: Arc<dyn MessageBoardHost>,
app_server: Option<Arc<AppServerNotifications>>,
}
impl MessageBoardHost for BackendClockHost {
impl MessageBoardHost for LocalHost {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
self.0.agent_path(caller)
self.membership.agent_path(caller)
}
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
self.0.resolve_agent(path)
self.membership.resolve_agent(path)
}
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async move {
self.0.agent_path(caller).await?;
self.membership.agent_path(caller).await?;
Ok(Utc::now())
})
}
@@ -54,7 +60,19 @@ impl MessageBoardHost for BackendClockHost {
recipient: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
self.0.notify(recipient, post)
let Some(app_server) = &self.app_server else {
return self.membership.notify(recipient, post);
};
Box::pin(async move {
let path = match self.membership.agent_path(recipient).await {
Ok(path) => path,
Err(error) if matches!(error.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(NotificationDelivery::SkippedInactive);
}
Err(error) => return Err(error),
};
app_server.notify(recipient, path, post).await
})
}
}
@@ -66,6 +84,7 @@ pub struct LocalServer {
authorization: HeaderValue,
boards: Boards,
states: InMemoryMessageBoards,
app_server: Option<Arc<AppServerNotifications>>,
cancellation: CancellationToken,
task: Option<JoinHandle<anyhow::Result<()>>>,
}
@@ -94,7 +113,10 @@ impl LocalServer {
!boards.keys().any(|(tree, _)| *tree == identity),
"board session already registered"
);
let host: Arc<dyn MessageBoardHost> = Arc::new(BackendClockHost(host));
let host: Arc<dyn MessageBoardHost> = Arc::new(LocalHost {
membership: host,
app_server: self.app_server.clone(),
});
boards.insert(
(identity, None),
(
@@ -112,7 +134,10 @@ impl LocalServer {
caller: ThreadId,
host: Arc<dyn MessageBoardHost>,
) -> anyhow::Result<()> {
let host: Arc<dyn MessageBoardHost> = Arc::new(BackendClockHost(host));
let host: Arc<dyn MessageBoardHost> = Arc::new(LocalHost {
membership: host,
app_server: self.app_server.clone(),
});
let board = self.states.open(identity, host.clone()).await;
let mut boards = self
.boards
@@ -145,6 +170,20 @@ impl Drop for LocalServer {
/// Binds a loopback endpoint for a local run. Register hosts before tool calls.
/// All connections for a tree share one board; the last owner releases its state.
pub async fn launch_in_memory() -> anyhow::Result<LocalServer> {
launch(/*app_server*/ None).await
}
/// Launches an in-memory board whose notifications use the runner's app-server connection.
/// Hosts still provide membership; their notification callbacks are not used.
/// The runner must supply the app-server that owns those agents.
/// Delivery uses the same bounded notices as the SQLite executable.
pub async fn launch_in_memory_with_app_server(
app_server: Arc<AppServerNotifications>,
) -> anyhow::Result<LocalServer> {
launch(Some(app_server)).await
}
async fn launch(app_server: Option<Arc<AppServerNotifications>>) -> anyhow::Result<LocalServer> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?;
let url = format!("http://{}/mcp", listener.local_addr()?);
let token = uuid::Uuid::new_v4().to_string();
@@ -188,6 +227,7 @@ pub async fn launch_in_memory() -> anyhow::Result<LocalServer> {
authorization,
boards,
states: InMemoryMessageBoards::default(),
app_server,
cancellation,
task: Some(task),
})
+2 -2
View File
@@ -1,6 +1,5 @@
//! Detached HTTP entry point; endpoint configuration and process lifetime belong to the deployer.
mod app_server;
mod persisted;
use clap::Parser;
@@ -8,6 +7,7 @@ use codex_message_board::LocalAgentMessageBoard;
use codex_message_board::LocalBoardOptions;
use codex_message_board::MessageBoardHost;
use codex_message_board::MessageBoardTool;
use codex_message_board_mcp::AppServerNotifications;
use codex_message_board_mcp::MessageBoardMcpServer;
use codex_state::SqliteConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -48,7 +48,7 @@ async fn main() -> anyhow::Result<()> {
.open_read_only_pool(&sqlite.state_db_path(), /*busy_timeout*/ None)
.await?;
let app_server = match args.app_server {
Some(url) => Some(Arc::new(app_server::AppServer::connect(url).await?)),
Some(url) => Some(Arc::new(AppServerNotifications::connect(url).await?)),
None => None,
};
let listener = tokio::net::TcpListener::bind(args.listen).await?;
+3 -15
View File
@@ -1,17 +1,16 @@
//! Reads persisted membership without starting runtimes or modifying Codex's registry.
//! Posts use system time and optionally deliver notices through the existing app-server RPC.
use crate::app_server::AppServer;
use chrono::DateTime;
use chrono::Utc;
use codex_message_board::MessageBoardHost;
use codex_message_board::NotificationDelivery;
use codex_message_board::PostPreview;
use codex_message_board_mcp::AppServerNotifications;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use codex_protocol::protocol::InterAgentCommunication;
use futures::future::BoxFuture;
use sqlx::SqlitePool;
use std::sync::Arc;
@@ -19,7 +18,7 @@ use std::sync::Arc;
pub(super) struct PersistedHost {
pub registry: SqlitePool,
pub root: ThreadId,
pub app_server: Option<Arc<AppServer>>,
pub app_server: Option<Arc<AppServerNotifications>>,
}
impl MessageBoardHost for PersistedHost {
@@ -99,18 +98,7 @@ LIMIT 2
return Ok(NotificationDelivery::SkippedInactive);
};
let path = self.agent_path(recipient).await?;
let notice = InterAgentCommunication::new(
post.metadata.author.clone(),
path,
Vec::new(),
post.notification_text(),
/*trigger_turn*/ false,
);
app_server
.inject(recipient, notice)
.await
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?;
Ok(NotificationDelivery::Accepted)
app_server.notify(recipient, path, post).await
})
}
}
+1
View File
@@ -3,6 +3,7 @@ load("//:defs.bzl", "codex_rust_crate")
exports_files(
["tests/common/mod.rs"],
visibility = [
"//codex-rs/app-server:__pkg__",
"//codex-rs/core:__pkg__",
"//codex-rs/ext/guardian-v3:__pkg__",
],