Broadcast read-state changes to experimental clients (#61852)

## Why

Clients need read-state updates for threads they have not opened so they can keep thread lists current.

## What changed

Broadcast `thread/readState/changed` to initialized experimental clients whenever a durable read receipt changes, regardless of thread subscription. Preserve filtering through `optOutNotificationMethods` and document refreshing the list after reconnecting to recover missed changes.

## Testing

Add a WebSocket regression test verifying that an unsubscribed experimental client receives updates while clients without the experimental capability and clients that opt out do not.

GitOrigin-RevId: a1a0f29405a856fdf6e379ded1376ed7d3d765cb
This commit is contained in:
yiqian-oai
2026-11-16 18:20:25 +00:00
committed by copyberry
parent effad7568c
commit 35145aba21
5 changed files with 97 additions and 17 deletions
+4 -4
View File
@@ -111,12 +111,12 @@ exact revision match, and both conflicts return `-32600` with
Do not blindly retry: the original action may precede an unseen result or
another window's mark. Unavailable threads fail; writes never change recency.
Started, resumed or forked threads send `thread/readState/changed` alongside
ordinary thread events; thread/unsubscribe or disconnect stops delivery.
Clients can filter this method with the existing notification opt-out setting.
The server broadcasts `thread/readState/changed` to initialized experimental clients
whenever a durable receipt changes, including for chats they have not opened. Clients can
ignore irrelevant thread IDs or suppress the method with `optOutNotificationMethods`.
Revisions are equality tokens, not clocks: never compare or merge them across
threads or hosts. When concurrent responses disagree, refresh with `thread/read`.
Offscreen threads converge on page refresh.
Refresh the list after reconnecting to recover changes missed while disconnected.
# Guardian circuit-breaker errors
@@ -583,7 +583,7 @@ async fn start_listener(
).await
{
super::thread_read_state::notify(
&db, &thread_state_manager,
&db,
&outgoing_for_task, conversation_id,
).await;
}
@@ -2446,13 +2446,7 @@ impl ThreadRequestProcessor {
};
match retirement {
Ok(true) => {
super::thread_read_state::notify(
db,
&self.thread_state_manager,
&self.outgoing,
thread_id,
)
.await;
super::thread_read_state::notify(db, &self.outgoing, thread_id).await;
}
Ok(false) => {}
Err(err) => {
@@ -1,4 +1,4 @@
//! Read state for durable local threads. Receipt changes use the thread's usual subscribers.
//! Read state for durable local threads. Receipt changes are broadcast to experimental clients.
use super::*;
use crate::error_code::method_not_found;
@@ -66,15 +66,13 @@ pub(super) async fn snapshots(
pub(super) async fn notify(
db: &StateDbHandle,
manager: &ThreadStateManager,
outgoing: &Arc<OutgoingMessageSender>,
id: ThreadId,
) {
match db.thread_read_states(&[id]).await {
Ok(mut states) => {
if let Some(state) = states.remove(&id) {
let subscribers = manager.subscribed_connection_ids(id).await;
ThreadScopedOutgoingMessageSender::new(Arc::clone(outgoing), subscribers, id)
outgoing
.send_server_notification(ServerNotification::ThreadReadStateChanged(
ThreadReadStateChangedNotification {
thread_id: id.to_string(),
@@ -184,7 +182,7 @@ impl ThreadRequestProcessor {
.map_err(|err| internal_error(format!("read state was not saved: {err}")))?;
match outcome {
ReadStateUpdate::Applied(state) => {
notify(db, &self.thread_state_manager, &self.outgoing, id).await;
notify(db, &self.outgoing, id).await;
Ok(Some(
ThreadReadStateUpdateResponse {
read_state: to_api(state),
@@ -1,12 +1,20 @@
use super::connection_handling_websocket::connect_websocket;
use super::connection_handling_websocket::read_jsonrpc_message;
use super::connection_handling_websocket::read_notification_for_method;
use super::connection_handling_websocket::read_response_for_id;
use super::connection_handling_websocket::send_request;
use super::connection_handling_websocket::spawn_websocket_server;
use anyhow::Context;
use anyhow::Result;
use app_test_support::DEFAULT_CLIENT_NAME;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::create_fake_rollout;
use app_test_support::create_mock_responses_server_repeating_assistant;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::InitializeCapabilities;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadHistoryMode;
use codex_app_server_protocol::ThreadListResponse;
@@ -28,6 +36,86 @@ use tokio::time::timeout;
const TIMEOUT: Duration = Duration::from_secs(15);
#[tokio::test]
async fn read_state_changes_reach_unsubscribed_experimental_clients() -> Result<()> {
let home = TempDir::new()?;
MockResponsesConfig::new("http://127.0.0.1:1")
.enable_feature(Feature::Sqlite)
.write(home.path())?;
create_fake_rollout(
home.path(),
"2025-01-01T12-00-00",
"2025-01-01T12:00:00Z",
"Saved user message",
Some("mock_provider"),
/*git_info*/ None,
)?;
let (mut process, addr) = spawn_websocket_server(home.path()).await?;
let mut writer = connect_websocket(addr).await?;
let mut observer = connect_websocket(addr).await?;
let mut stable = connect_websocket(addr).await?;
let mut opted_out = connect_websocket(addr).await?;
for (client, capabilities) in [
(&mut writer, json!({"experimentalApi": true})),
(&mut observer, json!({"experimentalApi": true})),
(&mut stable, json!({})),
(
&mut opted_out,
json!({
"experimentalApi": true,
"optOutNotificationMethods": ["thread/readState/changed"]
}),
),
] {
send_request(
client,
"initialize",
/*id*/ 1,
Some(json!({
"clientInfo": {"name": "read-state-test", "version": "1"},
"capabilities": capabilities
})),
)
.await?;
read_response_for_id(client, /*id*/ 1).await?;
}
send_request(&mut writer, "thread/list", /*id*/ 2, Some(json!({}))).await?;
let list = read_response_for_id(&mut writer, /*id*/ 2).await?.result;
let id = list["data"][0]["id"].as_str().context("thread id")?;
send_request(
&mut writer,
"thread/readState/update",
/*id*/ 3,
Some(json!({
"threadId": id,
"expectedRevision": list["readStates"][id]["revision"],
"operation": {"type": "unread"}
})),
)
.await?;
let updated = read_response_for_id(&mut writer, /*id*/ 3).await?.result;
let event = read_notification_for_method(&mut observer, "thread/readState/changed").await?;
assert_eq!(
event.params,
Some(json!({"threadId": id, "readState": updated["readState"]}))
);
for client in [&mut stable, &mut opted_out] {
send_request(client, "thread/loaded/list", /*id*/ 4, Some(json!({}))).await?;
loop {
match read_jsonrpc_message(client).await? {
JSONRPCMessage::Notification(notification) => {
assert_ne!(notification.method, "thread/readState/changed");
}
JSONRPCMessage::Response(response) if response.id == RequestId::Integer(4) => break,
message => anyhow::bail!("unexpected message: {message:?}"),
}
}
}
process.kill().await?;
Ok(())
}
#[tokio::test]
async fn read_state_methods_require_experimental_capability() -> Result<()> {
let mut server = TestAppServer::builder().without_auto_env().build().await?;