aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "app-server-client",
crate_name = "akode_app_server_client",
)

View File

@@ -0,0 +1,45 @@
[package]
name = "akode-app-server-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
name = "akode_app_server_client"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-app-server = { workspace = true }
akode-app-server-protocol = { workspace = true }
akode-app-server-transport = { workspace = true }
akode-arg0 = { workspace = true }
akode-config = { workspace = true }
akode-login = { workspace = true }
akode-core = { workspace = true }
akode-exec-server = { workspace = true }
akode-feedback = { workspace = true }
akode-protocol = { workspace = true }
akode-uds = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-rustls-provider = { workspace = true }
color-eyre = { workspace = true }
futures = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["sync", "time", "rt"] }
tokio-tungstenite = { workspace = true }
toml = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,66 @@
# akode-app-server-client
Shared in-process app-server client used by conversational CLI surfaces:
- `akode-exec`
- `akode-tui`
## Purpose
This crate centralizes startup and lifecycle management for an in-process
`akode-app-server` runtime, so CLI clients do not need to duplicate:
- app-server bootstrap and initialize handshake
- in-memory request/event transport wiring
- lifecycle orchestration around caller-provided startup identity
- graceful shutdown behavior
## Startup identity
Callers pass both the app-server `SessionSource` and the initialize
`client_info.name` explicitly when starting the facade.
That keeps thread metadata (for example in `thread/list` and `thread/read`)
aligned with the originating runtime without baking TUI/exec-specific policy
into the shared client layer.
## Transport model
The in-process path uses typed channels:
- client -> server: `ClientRequest` / `ClientNotification`
- server -> client: `InProcessServerEvent`
- `ServerRequest`
- `ServerNotification`
- `LegacyNotification`
JSON serialization is still used at external transport boundaries
(stdio/websocket), but the in-process hot path is typed.
Typed requests still receive app-server responses through the JSON-RPC
result envelope internally. That is intentional: the in-process path is
meant to preserve app-server semantics while removing the process
boundary, not to introduce a second response contract.
## Bootstrap behavior
The client facade starts an already-initialized in-process runtime, but
thread bootstrap still follows normal app-server flow:
- caller sends `thread/start` or `thread/resume`
- app-server returns the immediate typed response
- richer session metadata may arrive later as a `SessionConfigured`
legacy event
Surfaces such as TUI and exec may therefore need a short bootstrap
phase where they reconcile startup response data with later events.
## Backpressure and shutdown
- Command queues and the embedded runtime remain bounded, using
`DEFAULT_IN_PROCESS_CHANNEL_CAPACITY` by default.
- The facade's local consumer event queue is unbounded and preserves notification
order. This keeps the worker draining the bounded runtime while a caller waits
for a request, preventing unread notifications from blocking its response.
- `shutdown()` performs a bounded graceful shutdown and then aborts if timeout
is exceeded.

View File

@@ -0,0 +1,272 @@
//! Channel-backed cloud client. Requests and retained replies stay on one owner;
//! events are drained independently so a foreground request cannot block its response.
use crate::AppServerEvent;
use crate::RequestResult;
use crate::TypedRequestError;
use akode_app_server_protocol::ClientNotification;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::JSONRPCErrorError;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::Result as JsonRpcResult;
use akode_app_server_protocol::Turn;
use akode_app_server_protocol::TurnStartParams;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
/// A local project's GitHub origins for a cloud coding thread.
/// The native cloud backend was removed in aKode; the type stays for the channel API.
#[derive(Clone)]
pub struct ProjectEnvironment {
pub name: String,
pub origin_urls: Vec<String>,
/// Working directory inside the managed environment, when a project selects one.
pub cwd: Option<String>,
}
impl std::fmt::Debug for ProjectEnvironment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ProjectEnvironment([redacted])")
}
}
/// Operations the cloud worker must handle without forwarding to another backend.
/// Unsupported operations must return an explicit error; they must not claim success.
pub enum CloudOperation {
Request(Box<ClientRequest>),
/// Host project metadata stays on the private transport, outside the app-server wire.
StartProjectThread {
request_id: RequestId,
params: Box<akode_app_server_protocol::ThreadStartParams>,
project: ProjectEnvironment,
},
SubmitUserMessage(Box<TurnStartParams>),
Notify(ClientNotification),
Resolve {
request_id: RequestId,
result: JsonRpcResult,
},
Reject {
request_id: RequestId,
error: JSONRPCErrorError,
},
Shutdown,
}
/// One server-decided admission, not completion. A duplicate carries identity
/// only; read history or observe the reply stream before inferring its status.
#[derive(serde::Serialize, serde::Deserialize)]
pub enum CloudUserMessageReceipt {
Started(Turn),
Steered(Turn),
Duplicate { turn_id: Option<String> },
}
/// An operation and its single response. Dropping a caller does not undo admission;
/// cloud workers must not retry mutations when the receiver has gone away.
pub struct CloudCommand {
pub operation: CloudOperation,
pub response: oneshot::Sender<io::Result<RequestResult>>,
}
#[derive(Clone)]
pub struct CloudRequestHandle {
commands: mpsc::Sender<CloudCommand>,
}
/// Tracks only losses queued for delivery. The worker remains the sole owner
/// of the active attachment. A successful replacement supersedes earlier losses
/// for that conversation, even if the replacement itself later ends.
#[derive(Clone, Default)]
pub(super) struct CloudStreamLosses(Arc<Mutex<HashMap<String, PendingLosses>>>);
#[derive(Default)]
struct PendingLosses {
remaining: usize,
superseded: usize,
}
impl CloudStreamLosses {
fn pending(&self) -> MutexGuard<'_, HashMap<String, PendingLosses>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
fn should_deliver(&self, thread_id: &str) -> bool {
let mut pending = self.pending();
let Some(losses) = pending.get_mut(thread_id) else {
return true;
};
// A single worker sends losses in the same order as it records them.
let deliver = losses.superseded == 0;
losses.superseded = losses.superseded.saturating_sub(1);
losses.remaining -= 1;
if losses.remaining == 0 {
pending.remove(thread_id);
}
deliver
}
}
pub struct CloudClient {
pub(super) stream_losses: CloudStreamLosses,
handle: CloudRequestHandle,
events: mpsc::UnboundedReceiver<AppServerEvent>,
}
impl CloudClient {
/// Creates a cloud transport. The owner must drain commands and stop when
/// its receiver closes. Event delivery is independent of request completion,
/// matching conventional transports; cloud workers must bound remote payloads.
pub fn channel(
capacity: usize,
) -> (
Self,
mpsc::Receiver<CloudCommand>,
mpsc::UnboundedSender<AppServerEvent>,
) {
let (commands, receiver) = mpsc::channel(capacity.max(1));
let (events, event_receiver) = mpsc::unbounded_channel();
(
Self {
stream_losses: CloudStreamLosses::default(),
handle: CloudRequestHandle { commands },
events: event_receiver,
},
receiver,
events,
)
}
pub(crate) fn request_handle(&self) -> CloudRequestHandle {
self.handle.clone()
}
pub(crate) async fn next_event(&mut self) -> Option<AppServerEvent> {
while let Some(event) = self.events.recv().await {
if let AppServerEvent::ThreadStreamDisconnected(error) = &event
&& !self.stream_losses.should_deliver(&error.thread_id)
{
continue;
}
return Some(event);
}
None
}
pub(crate) async fn request(&self, request: ClientRequest) -> io::Result<RequestResult> {
self.handle.request(request).await
}
pub(crate) async fn notify(&self, notification: ClientNotification) -> io::Result<()> {
self.handle.unit(CloudOperation::Notify(notification)).await
}
pub(crate) async fn resolve_server_request(
&self,
request_id: RequestId,
result: JsonRpcResult,
) -> io::Result<()> {
self.handle.resolve_server_request(request_id, result).await
}
pub(crate) async fn reject_server_request(
&self,
request_id: RequestId,
error: JSONRPCErrorError,
) -> io::Result<()> {
self.handle.reject_server_request(request_id, error).await
}
pub(crate) async fn shutdown(self) -> io::Result<()> {
tokio::time::timeout(
crate::SHUTDOWN_TIMEOUT,
self.handle.unit(CloudOperation::Shutdown),
)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "cloud backend shutdown timed out"))?
}
}
impl CloudRequestHandle {
pub(crate) async fn start_project_thread(
&self,
request_id: RequestId,
params: akode_app_server_protocol::ThreadStartParams,
project: ProjectEnvironment,
) -> io::Result<RequestResult> {
self.send(CloudOperation::StartProjectThread {
request_id,
params: Box::new(params),
project,
})
.await
}
/// Submit once with a stable message ID and saved thread settings. The server
/// starts or steers; an error can mean admission is unknown. Never auto-resend.
pub async fn submit_user_message(
&self,
params: TurnStartParams,
) -> Result<CloudUserMessageReceipt, TypedRequestError> {
let response = self
.send(CloudOperation::SubmitUserMessage(Box::new(params)))
.await;
crate::decode_typed_response("cloud/submitUserMessage", response)
}
async fn send(&self, operation: CloudOperation) -> io::Result<RequestResult> {
let (response, result) = oneshot::channel();
self.commands
.send(CloudCommand {
operation,
response,
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "cloud backend is closed"))?;
result.await.map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
"cloud backend dropped its response",
)
})?
}
async fn unit(&self, operation: CloudOperation) -> io::Result<()> {
self.send(operation)
.await?
.map(|_| ())
.map_err(|error| io::Error::other(error.message))
}
pub(crate) async fn request(&self, request: ClientRequest) -> io::Result<RequestResult> {
self.send(CloudOperation::Request(Box::new(request))).await
}
pub(crate) async fn resolve_server_request(
&self,
request_id: RequestId,
result: JsonRpcResult,
) -> io::Result<()> {
self.unit(CloudOperation::Resolve { request_id, result })
.await
}
pub(crate) async fn reject_server_request(
&self,
request_id: RequestId,
error: JSONRPCErrorError,
) -> io::Result<()> {
self.unit(CloudOperation::Reject { request_id, error })
.await
}
}
#[cfg(test)]
#[path = "cloud_tests.rs"]
mod tests;

View File

@@ -0,0 +1,104 @@
use super::*;
use crate::AppServerClient;
use crate::AppServerEvent;
use akode_app_server_protocol::ThreadReadParams;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn retained_request_and_reply_stay_with_their_cloud_backend() {
let (first, mut first_commands, first_events) = CloudClient::channel(/*capacity*/ 1);
let (second, mut second_commands, _second_events) = CloudClient::channel(/*capacity*/ 1);
let mut first = AppServerClient::Cloud(first);
let second = AppServerClient::Cloud(second);
let handle = first.request_handle();
let reply = handle.server_request_reply_handle(RequestId::Integer(7));
let worker = tokio::spawn(async move {
let command = first_commands.recv().await.unwrap();
let CloudOperation::Request(request) = command.operation else {
panic!("expected thread read");
};
let ClientRequest::ThreadRead { params, .. } = *request else {
panic!("expected thread read");
};
assert_eq!(params.thread_id, "thread-1");
first_events
.send(AppServerEvent::Disconnected {
message: "stream ended".into(),
})
.unwrap();
command
.response
.send(Ok(Ok(serde_json::json!({"owner": "first"}))))
.unwrap();
let command = first_commands.recv().await.unwrap();
let CloudOperation::Resolve { request_id, result } = command.operation else {
panic!("expected retained reply");
};
assert_eq!(
(request_id, result),
(
RequestId::Integer(7),
serde_json::json!({"decision": "accept"})
)
);
command
.response
.send(Ok(Ok(serde_json::Value::Null)))
.unwrap();
});
assert_eq!(
handle
.request(ClientRequest::ThreadRead {
request_id: RequestId::Integer(1),
params: ThreadReadParams {
thread_id: "thread-1".into(),
include_turns: false
},
})
.await
.unwrap()
.unwrap(),
serde_json::json!({"owner": "first"})
);
reply
.resolve(serde_json::json!({"decision": "accept"}))
.await
.unwrap();
assert!(second_commands.try_recv().is_err());
assert!(matches!(
first.next_event().await,
Some(AppServerEvent::Disconnected { .. })
));
worker.await.unwrap();
assert!(
handle
.request(ClientRequest::ThreadRead {
request_id: RequestId::Integer(2),
params: ThreadReadParams {
thread_id: "thread-1".into(),
include_turns: false
},
})
.await
.is_err()
);
drop(second);
}
#[tokio::test(start_paused = true)]
async fn cloud_shutdown_times_out_when_owner_does_not_respond() {
let (client, mut commands, events) = CloudClient::channel(/*capacity*/ 1);
let error = tokio::time::timeout(
crate::SHUTDOWN_TIMEOUT + std::time::Duration::from_secs(1),
AppServerClient::Cloud(client).shutdown(),
)
.await
.expect("shutdown should be bounded")
.expect_err("an unresponsive cloud worker should time out");
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
let command = commands.try_recv().expect("shutdown was admitted");
assert!(matches!(command.operation, CloudOperation::Shutdown));
assert!(command.response.is_closed());
assert!(events.is_closed());
assert!(commands.recv().await.is_none());
}

File diff suppressed because it is too large Load Diff

View File

@@ -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("//")
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,120 @@
//! Negotiated WebSocket compression. Codec history lasts for the connection.
use std::io;
use akode_app_server_transport::CompressionConnection;
use akode_app_server_transport::WEBSOCKET_COMPRESSION_HEADER;
use akode_app_server_transport::WebSocketCompression;
use akode_app_server_transport::ZstdDecoder;
use akode_app_server_transport::ZstdEncoder;
use akode_app_server_transport::zstd_codec_pair;
use futures::SinkExt;
use futures::StreamExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Bytes;
use tokio_tungstenite::tungstenite::Error;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::client::Response;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::frame::Frame;
use tokio_tungstenite::tungstenite::protocol::frame::coding::Data;
use tokio_tungstenite::tungstenite::protocol::frame::coding::OpCode;
// Match the listener's default incoming frame limit when no smaller cap is advertised.
const DEFAULT_MAX_FRAME_BYTES: usize = 16 << 20;
const MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER: &str =
"x-codex-websocket-max-unfragmented-message-bytes";
pub(crate) type WebSocketHandshake<S> = (WebSocketStream<S>, Response);
pub(crate) struct RemoteWebSocket<S> {
stream: WebSocketStream<S>,
codec: Option<(ZstdEncoder, ZstdDecoder)>,
max_frame_bytes: usize,
write_failed: bool,
}
impl<S: AsyncRead + AsyncWrite + Unpin> RemoteWebSocket<S> {
pub(crate) fn from_handshake(
(stream, response): WebSocketHandshake<S>,
max_message_size: usize,
) -> io::Result<Self> {
let headers = response.headers();
let header = headers
.get(WEBSOCKET_COMPRESSION_HEADER)
.map(HeaderValue::to_str)
.transpose()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let codec = match WebSocketCompression::from_response_header(header)? {
WebSocketCompression::Plain => None,
WebSocketCompression::Zstd => Some(zstd_codec_pair(
max_message_size,
CompressionConnection::NativeClient,
)?),
};
let max_frame_bytes = headers
.get(MAX_UNFRAGMENTED_MESSAGE_BYTES_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
.unwrap_or(DEFAULT_MAX_FRAME_BYTES)
.min(DEFAULT_MAX_FRAME_BYTES);
Ok(Self {
stream,
codec,
max_frame_bytes,
write_failed: false,
})
}
pub(crate) async fn next(&mut self) -> Option<Result<Message, Error>> {
if self.write_failed {
return Some(Err(Error::Io(io::ErrorKind::BrokenPipe.into())));
}
let message = self.stream.next().await?;
Some(match (&mut self.codec, message) {
(Some((_, decoder)), Ok(Message::Binary(bytes))) => decoder
.decode(&bytes)
.map(|text| Message::Text(text.into()))
.map_err(Error::Io),
(Some(_), Ok(Message::Text(_))) => Err(Error::Io(io::Error::new(
io::ErrorKind::InvalidData,
"expected compressed binary app-server message",
))),
(_, message) => message,
})
}
pub(crate) async fn send_text(&mut self, text: String) -> Result<(), Error> {
if self.write_failed {
return Err(Error::Io(io::ErrorKind::BrokenPipe.into()));
}
let result = async {
let Some((encoder, _)) = &mut self.codec else {
return self.stream.send(Message::Text(text.into())).await;
};
let mut bytes = Bytes::from(encoder.encode(&text).map_err(Error::Io)?);
if bytes.len() <= self.max_frame_bytes {
return self.stream.send(Message::Binary(bytes)).await;
}
let mut opcode = OpCode::Data(Data::Binary);
while !bytes.is_empty() {
let chunk = bytes.split_to(bytes.len().min(self.max_frame_bytes));
let frame = Frame::message(chunk, opcode, bytes.is_empty());
self.stream.feed(Message::Frame(frame)).await?;
opcode = OpCode::Data(Data::Continue);
}
self.stream.flush().await
}
.await;
// A failed write may leave the compression history ahead of the receiver.
self.write_failed = result.is_err();
result
}
pub(crate) async fn close(&mut self) -> Result<(), Error> {
self.stream.close(/*msg*/ None).await
}
}

View File

@@ -0,0 +1,68 @@
//! Retained reply capability: a server request ID and the worker that emitted it.
use crate::AppServerRequestHandle;
use akode_app_server_protocol::JSONRPCErrorError;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::Result as JsonRpcResult;
use std::fmt;
use std::io;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
/// A reply always targets its originating connection, regardless of later UI selection.
/// Clones share a single-use completion state, so only the first resolve or reject is
/// submitted. Dropping a handle sends nothing. It does not keep a shutdown worker alive
/// or reconnect it; a stale connection returns its normal I/O error. No retries occur.
#[derive(Clone)]
pub struct AppServerReplyHandle {
client: AppServerRequestHandle,
request_id: RequestId,
claimed: Arc<AtomicBool>,
}
impl fmt::Debug for AppServerReplyHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AppServerReplyHandle([redacted])")
}
}
impl AppServerRequestHandle {
/// Capture at event ingress, using an ID from this connection's event stream.
/// Request IDs may be reused by other connections and must not select a client.
pub fn server_request_reply_handle(&self, request_id: RequestId) -> AppServerReplyHandle {
AppServerReplyHandle {
client: self.clone(),
request_id,
claimed: Arc::new(AtomicBool::new(false)),
}
}
}
impl AppServerReplyHandle {
fn claim(&self) -> io::Result<()> {
self.claimed
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.map(|_| ())
.map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"app-server reply handle already used",
)
})
}
/// Resolve at the caller's explicit request. Failure can have an unknown outcome.
pub async fn resolve(&self, result: JsonRpcResult) -> io::Result<()> {
self.claim()?;
self.client
.resolve_server_request(self.request_id.clone(), result)
.await
}
/// Reject on the originating connection; never fall back to another connection.
pub async fn reject(&self, error: JSONRPCErrorError) -> io::Result<()> {
self.claim()?;
self.client
.reject_server_request(self.request_id.clone(), error)
.await
}
}
#[cfg(test)]
#[path = "server_request_tests.rs"]
mod tests;

View File

@@ -0,0 +1,105 @@
//! Worker-channel ownership checks, including stale handles and identical request IDs.
use super::*;
use crate::ClientCommand;
use crate::InProcessAppServerRequestHandle;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
#[tokio::test]
async fn in_process_replies_keep_their_worker_and_request_id() {
let (first_tx, mut first_rx) = mpsc::channel(/*buffer*/ 2);
let (second_tx, mut second_rx) = mpsc::channel(/*buffer*/ 2);
let first = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle {
command_tx: first_tx,
});
let second = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle {
command_tx: second_tx,
});
let id = RequestId::String("private-request".into());
let reply = first.server_request_reply_handle(id.clone());
let stale = first.server_request_reply_handle(RequestId::String("stale-request".into()));
let other = second.server_request_reply_handle(id.clone());
drop(first);
assert_eq!(format!("{reply:?}"), "AppServerReplyHandle([redacted])");
assert_eq!(reply.request_id, id);
let (result, ()) = tokio::join!(reply.resolve(serde_json::json!({"first": true})), async {
let ClientCommand::ResolveServerRequest {
request_id,
result,
response_tx,
} = first_rx.recv().await.unwrap()
else {
panic!("wrong command")
};
assert_eq!(
(request_id, result),
(id.clone(), serde_json::json!({"first": true}))
);
response_tx.send(Ok(())).unwrap();
});
result.unwrap();
assert!(second_rx.try_recv().is_err());
let error = JSONRPCErrorError {
code: -32000,
message: "declined".into(),
data: None,
};
let (result, ()) = tokio::join!(other.reject(error.clone()), async {
let ClientCommand::RejectServerRequest {
request_id,
error: received,
response_tx,
} = second_rx.recv().await.unwrap()
else {
panic!("wrong command")
};
assert_eq!((request_id, received), (id, error));
response_tx.send(Ok(())).unwrap();
});
result.unwrap();
assert!(first_rx.try_recv().is_err());
drop(first_rx);
assert_eq!(
stale
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
io::ErrorKind::BrokenPipe
);
drop(other);
assert!(second_rx.try_recv().is_err());
}
#[tokio::test]
async fn cloned_reply_handle_only_submits_once() {
let (command_tx, mut command_rx) = mpsc::channel(/*buffer*/ 2);
let client = AppServerRequestHandle::InProcess(InProcessAppServerRequestHandle { command_tx });
let reply = client.server_request_reply_handle(RequestId::Integer(1));
let duplicate = reply.clone();
let error = JSONRPCErrorError {
code: -32000,
message: "declined".into(),
data: None,
};
let (resolved, rejected, ()) = tokio::join!(
reply.resolve(serde_json::json!({"accepted": true})),
duplicate.reject(error),
async {
match command_rx.recv().await.unwrap() {
ClientCommand::ResolveServerRequest { response_tx, .. }
| ClientCommand::RejectServerRequest { response_tx, .. } => {
response_tx.send(Ok(())).unwrap();
}
_ => panic!("wrong command"),
}
}
);
let outcomes = [resolved, rejected].map(|result| result.map_err(|error| error.kind()));
assert!(
outcomes == [Ok(()), Err(io::ErrorKind::InvalidInput)]
|| outcomes == [Err(io::ErrorKind::InvalidInput), Ok(())]
);
assert!(command_rx.try_recv().is_err());
}

View File

@@ -0,0 +1,101 @@
//! Real WebSocket workers retain independent replies even when request IDs collide.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn remote_reply_handles_keep_original_connection() {
let mut clients = Vec::new();
let mut replies = Vec::new();
let mut stale_replies = Vec::new();
let mut observed = Vec::new();
for label in ["first", "second"] {
let (done_tx, done_rx) = oneshot::channel();
let websocket_url = start_test_remote_server(move |mut websocket| async move {
expect_remote_initialize(&mut websocket).await;
write_websocket_message(&mut websocket, JSONRPCMessage::Request(JSONRPCRequest {
id: RequestId::Integer(1), method: "item/tool/requestUserInput".into(),
params: Some(serde_json::json!({"threadId":"same-thread", "turnId":"same-turn", "itemId":"same-item", "questions":[], "isBlocking":true})),
trace: None,
})).await;
let response = read_websocket_message(&mut websocket).await;
done_tx.send((label, response)).unwrap();
while websocket.next().await.is_some() {}
}).await;
let mut client = AppServerClient::Remote(
RemoteAppServerClient::connect(test_remote_connect_args(websocket_url))
.await
.unwrap(),
);
let AppServerEvent::ServerRequest(request) = client.next_event().await.unwrap() else {
panic!("expected request")
};
replies.push(
client
.request_handle()
.server_request_reply_handle(request.id().clone()),
);
stale_replies.push(
client
.request_handle()
.server_request_reply_handle(RequestId::Integer(2)),
);
clients.push(client);
observed.push(done_rx);
}
replies[1]
.reject(JSONRPCErrorError {
code: -32000,
message: "second".into(),
data: None,
})
.await
.unwrap();
replies[0]
.resolve(serde_json::json!({"first": true}))
.await
.unwrap();
for receiver in observed {
let (label, message) = timeout(Duration::from_secs(/*secs*/ 5), receiver)
.await
.unwrap()
.unwrap();
match message {
JSONRPCMessage::Response(response) => assert_eq!(
(label, response.id, response.result),
(
"first",
RequestId::Integer(1),
serde_json::json!({"first": true})
)
),
JSONRPCMessage::Error(error) => assert_eq!(
(label, error.id, error.error.message),
("second", RequestId::Integer(1), "second".into())
),
_ => panic!("expected response or rejection"),
}
}
for client in clients {
client.shutdown().await.unwrap();
}
for reply in replies {
assert_eq!(
reply
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
ErrorKind::InvalidInput
);
}
for reply in stale_replies {
assert_eq!(
reply
.resolve(serde_json::json!({}))
.await
.unwrap_err()
.kind(),
ErrorKind::BrokenPipe
);
}
}

View File

@@ -0,0 +1,116 @@
//! Exercise a negotiated compressed session through the remote client API.
use std::error::Error;
use akode_app_server_client::AppServerEvent;
use akode_app_server_client::RemoteAppServerClient;
use akode_app_server_client::RemoteAppServerConnectArgs;
use akode_app_server_client::RemoteAppServerEndpoint;
use akode_app_server_protocol::JSONRPCRequest;
use akode_app_server_protocol::RequestId;
use akode_app_server_transport::WEBSOCKET_COMPRESSION_HEADER;
use akode_app_server_transport::ZSTD_STREAM_PROTOCOL;
use akode_app_server_transport::ZstdDecoder;
use akode_app_server_transport::ZstdEncoder;
use akode_uds::UnixListener;
use akode_utils_absolute_path::AbsolutePathBuf;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio_tungstenite::accept_hdr_async_with_config;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
#[tokio::test]
async fn compressed_session_negotiates_fragments_and_retains_history() -> Result<(), Box<dyn Error>>
{
const FRAME_LIMIT: usize = 16;
let dir = TempDir::new()?;
let socket_path = AbsolutePathBuf::from_absolute_path(dir.path().join("akode.sock"))?;
let mut listener = UnixListener::bind(socket_path.as_path()).await?;
let server = async {
let stream = listener.accept().await?;
let mut websocket = accept_hdr_async_with_config(
stream,
|request: &Request, mut response: Response| {
assert_eq!(
request.headers()[WEBSOCKET_COMPRESSION_HEADER],
ZSTD_STREAM_PROTOCOL
);
response.headers_mut().insert(
WEBSOCKET_COMPRESSION_HEADER,
HeaderValue::from_static(ZSTD_STREAM_PROTOCOL),
);
response.headers_mut().insert(
"x-codex-websocket-max-unfragmented-message-bytes",
HeaderValue::from(FRAME_LIMIT),
);
Ok(response)
},
Some(WebSocketConfig::default().max_frame_size(Some(FRAME_LIMIT))),
)
.await?;
let mut decoder = ZstdDecoder::new(/*max_message_size*/ 1024)?;
let mut encoder = ZstdEncoder::new()?;
for expected_method in ["initialize", "initialized", "echo"] {
let Message::Binary(bytes) = websocket.next().await.ok_or("connection closed")?? else {
return Err("expected compressed message".into());
};
if expected_method == "initialize" {
assert!(
bytes.len() > FRAME_LIMIT,
"initialize must require fragmentation"
);
}
let request: Value = serde_json::from_str(&decoder.decode(&bytes)?)?;
assert_eq!(request["method"], expected_method);
if expected_method != "initialized" {
let response = json!({"id": request["id"], "result": {"ok": true}}).to_string();
websocket
.send(Message::Binary(encoder.encode(&response)?.into()))
.await?;
}
}
websocket.send(Message::Text("{}".into())).await?;
Ok::<(), Box<dyn Error>>(())
};
let client = async {
let mut client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
required_human_approval: false,
endpoint: RemoteAppServerEndpoint::UnixSocket { socket_path },
client_name: "compression-test".to_string(),
client_version: "0.0.0".to_string(),
experimental_api: false,
mcp_server_openai_form_elicitation: false,
opt_out_notification_methods: Vec::new(),
channel_capacity: 8,
})
.await?;
assert_eq!(
client
.request_handle()
.request_json_rpc(JSONRPCRequest {
id: RequestId::Integer(1),
method: "echo".to_string(),
params: None,
trace: None,
})
.await?,
Ok(json!({"ok": true}))
);
let Some(AppServerEvent::Disconnected { message }) = client.next_event().await else {
return Err("expected disconnect after uncompressed message".into());
};
assert!(message.contains("expected compressed binary"));
client.shutdown().await?;
Ok::<(), Box<dyn Error>>(())
};
tokio::try_join!(server, client)?;
Ok(())
}