aKode fase 2a: rimossi cloud tasks, chatgpt apply, responses-api-proxy, codex app, remote control, guardian decisions; realtime senza fallback OpenAI; doctor senza sonde OpenAI
This commit is contained in:
@@ -17,7 +17,6 @@ codex-app-server = { workspace = true }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-app-server-transport = { workspace = true }
|
||||
codex-arg0 = { workspace = true }
|
||||
codex-cloud-client = { path = "../cloud-client" }
|
||||
codex-config = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
|
||||
@@ -20,6 +20,22 @@ 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 {
|
||||
@@ -28,7 +44,7 @@ pub enum CloudOperation {
|
||||
StartProjectThread {
|
||||
request_id: RequestId,
|
||||
params: Box<codex_app_server_protocol::ThreadStartParams>,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
},
|
||||
SubmitUserMessage(Box<TurnStartParams>),
|
||||
Notify(ClientNotification),
|
||||
@@ -81,19 +97,6 @@ impl CloudStreamLosses {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(super) fn record(&self, thread_id: &str) {
|
||||
self.pending()
|
||||
.entry(thread_id.to_owned())
|
||||
.or_default()
|
||||
.remaining += 1;
|
||||
}
|
||||
|
||||
pub(super) fn supersede(&self, thread_id: &str) {
|
||||
if let Some(losses) = self.pending().get_mut(thread_id) {
|
||||
losses.superseded = losses.remaining;
|
||||
}
|
||||
}
|
||||
|
||||
fn should_deliver(&self, thread_id: &str) -> bool {
|
||||
let mut pending = self.pending();
|
||||
let Some(losses) = pending.get_mut(thread_id) else {
|
||||
@@ -195,7 +198,7 @@ impl CloudRequestHandle {
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
params: codex_app_server_protocol::ThreadStartParams,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
) -> io::Result<RequestResult> {
|
||||
self.send(CloudOperation::StartProjectThread {
|
||||
request_id,
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
//! Opens the internal Cloud preview with the selected ChatGPT credentials and local transport policy.
|
||||
|
||||
use super::start_worker;
|
||||
use crate::AppServerClient;
|
||||
use crate::legacy_core::config::Config;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_login::token_data::parse_jwt_expiration;
|
||||
use codex_protocol::account::PlanType;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
|
||||
const ORIGIN: &str = "https://codex-cloud-backend.chatgpt.com";
|
||||
|
||||
pub async fn connect(config: &Config) -> Result<AppServerClient> {
|
||||
// The preview borrows Local's policy without owning credential updates.
|
||||
let factory = config.http_client_factory();
|
||||
let policy = factory.network_policy().clone().for_current_account();
|
||||
let factory = factory.with_network_policy(policy);
|
||||
let auth = config
|
||||
.auth_config()
|
||||
.load_auth(/*enable_codex_api_key_env*/ false)
|
||||
.await?
|
||||
.ok_or_else(|| eyre!("Sign in with ChatGPT and reopen Codex to use Cloud."))?;
|
||||
if !auth.is_chatgpt_auth() || auth.is_fedramp_account() {
|
||||
bail!("This account is not supported by the cloud conversation preview.");
|
||||
}
|
||||
let account_id = auth
|
||||
.get_account_id()
|
||||
.ok_or_else(|| eyre!("Cloud requires a selected account."))?;
|
||||
let token = auth.get_token()?;
|
||||
if let Ok(Some(expires)) = parse_jwt_expiration(&token)
|
||||
&& std::time::SystemTime::from(expires) <= std::time::SystemTime::now()
|
||||
{
|
||||
bail!("Your ChatGPT credential expired. Reopen Codex to reconnect.");
|
||||
}
|
||||
factory.network_policy().acquire(&ORIGIN.parse()?)?;
|
||||
let credentials = cloud::Credentials::new(&token, &account_id)?;
|
||||
let client = cloud::Client::new(&factory, ORIGIN, credentials)?;
|
||||
Ok(start_worker(
|
||||
client,
|
||||
protocol::GetAccountResponse {
|
||||
user_id: auth.get_chatgpt_user_id(),
|
||||
account: Some(protocol::Account::Chatgpt {
|
||||
email: auth.get_account_email(),
|
||||
plan_type: auth.account_plan_type().unwrap_or(PlanType::Unknown),
|
||||
workspace_name: None,
|
||||
}),
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Ensures only a successfully attached thread can receive new turns.
|
||||
|
||||
use super::*;
|
||||
use futures::stream;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_replacement_keeps_old_thread_until_new_attachment_succeeds() -> Result<()> {
|
||||
let (output, mut notifications) = mpsc::unbounded_channel();
|
||||
let mut replies = Replies::default();
|
||||
replies
|
||||
.replace("old", async { Ok(stream::pending().boxed()) }, &output)
|
||||
.await?;
|
||||
|
||||
for failure in [
|
||||
Err(cloud::Error::InvalidResponse),
|
||||
Ok(stream::empty().boxed()),
|
||||
Ok(stream::iter([Err(cloud::Error::InvalidResponse)]).boxed()),
|
||||
] {
|
||||
assert!(
|
||||
replies
|
||||
.replace("new", async { failure }, &output)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
replies.admit_turn("old", &output)?;
|
||||
assert!(replies.admit_turn("new", &output).is_err());
|
||||
}
|
||||
|
||||
let (close, closed) = tokio::sync::oneshot::channel::<()>();
|
||||
let stream = stream::once(async move {
|
||||
let _ = closed.await;
|
||||
Err(cloud::Error::InvalidResponse)
|
||||
})
|
||||
.boxed();
|
||||
replies
|
||||
.replace("new", async { Ok(stream) }, &output)
|
||||
.await?;
|
||||
replies.detach("old");
|
||||
assert!(replies.admit_turn("old", &output).is_err());
|
||||
replies.admit_turn("new", &output)?;
|
||||
|
||||
let _ = close.send(());
|
||||
assert!(replies.admit_turn("new", &output).is_err());
|
||||
let AppServerEvent::ThreadStreamDisconnected(notification) = notifications.try_recv()? else {
|
||||
panic!("expected a disconnect notification");
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(protocol::ServerNotification::Error(*notification))?,
|
||||
serde_json::to_value(protocol::ServerNotification::Error(cloud_error(
|
||||
"new",
|
||||
"Cloud stream ended. Reopen the conversation to reconnect."
|
||||
)))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn successful_reopen_supersedes_only_earlier_losses_for_that_thread() -> Result<()> {
|
||||
let (mut client, _commands, output) = CloudClient::channel(/*capacity*/ 1);
|
||||
let mut replies = Replies {
|
||||
stream_losses: client.stream_losses.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for id in ["reopened", "different", "reopened"] {
|
||||
let (sender, stream) = futures::channel::mpsc::unbounded();
|
||||
replies
|
||||
.replace(id, async { Ok(stream.boxed()) }, &output)
|
||||
.await?;
|
||||
drop(sender);
|
||||
replies.forward_next(&output).await;
|
||||
}
|
||||
assert!(
|
||||
replies
|
||||
.replace("reopened", async { Ok(stream::empty().boxed()) }, &output)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
// The first EOF was followed by a successful reopen. A different thread's
|
||||
// EOF and the reopened thread's newer EOF must still be delivered, in order.
|
||||
drop(output);
|
||||
for expected in ["different", "reopened"] {
|
||||
let Some(AppServerEvent::ThreadStreamDisconnected(error)) = client.next_event().await
|
||||
else {
|
||||
panic!("expected a thread stream disconnect");
|
||||
};
|
||||
assert_eq!(
|
||||
*error,
|
||||
cloud_error(
|
||||
expected,
|
||||
"Cloud stream ended. Reopen the conversation to reconnect."
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(client.next_event().await.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_status_follows_its_server_notifications() -> Result<()> {
|
||||
let (output, _notifications) = mpsc::unbounded_channel();
|
||||
let mut replies = Replies::default();
|
||||
let notifications: [&[u8]; 3] = [
|
||||
b"\x1a\x0d\x12\x0b\x0a\x06\x22\x04\x0a\x02\x08\x01\x12\x01t", // t is waiting
|
||||
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01x", // x is idle
|
||||
b"\x1a\x09\x12\x07\x0a\x02\x12\x00\x12\x01t", // t is idle
|
||||
];
|
||||
let stream =
|
||||
stream::iter(notifications.map(|bytes| Ok(cloud::Event::Notification(bytes.into()))));
|
||||
replies
|
||||
.replace("t", async { Ok(stream.boxed()) }, &output)
|
||||
.await?;
|
||||
|
||||
let waiting = cloud::ThreadStatus::Active {
|
||||
active_flags: vec![cloud::ThreadActiveFlag::WaitingOnApproval],
|
||||
};
|
||||
assert_eq!(replies.thread_status("t"), Some(&waiting));
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&waiting));
|
||||
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
|
||||
replies.forward_next(&output).await;
|
||||
assert_eq!(replies.thread_status("t"), Some(&cloud::ThreadStatus::Idle));
|
||||
|
||||
replies
|
||||
.replace("t", async { Ok(stream::pending().boxed()) }, &output)
|
||||
.await?;
|
||||
assert_eq!(replies.thread_status("t"), None);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
//! Converts supported cloud transcript events without interpreting executor paths locally.
|
||||
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
|
||||
pub(super) fn turn(summary: cloud::TurnSummary) -> Result<protocol::Turn> {
|
||||
Ok(protocol::Turn {
|
||||
id: summary.id,
|
||||
root_turn_id: None,
|
||||
items: Vec::new(),
|
||||
items_view: protocol::TurnItemsView::NotLoaded,
|
||||
status: match summary.status {
|
||||
cloud::TurnStatus::Completed => protocol::TurnStatus::Completed,
|
||||
cloud::TurnStatus::Interrupted => protocol::TurnStatus::Interrupted,
|
||||
cloud::TurnStatus::Failed => protocol::TurnStatus::Failed,
|
||||
cloud::TurnStatus::InProgress => protocol::TurnStatus::InProgress,
|
||||
cloud::TurnStatus::Unknown(_) => {
|
||||
bail!("The cloud returned an unsupported turn status.");
|
||||
}
|
||||
},
|
||||
error: summary.error.map(|error| protocol::TurnError {
|
||||
message: error.message,
|
||||
additional_details: error.additional_details,
|
||||
codex_error_info: None,
|
||||
misalignment: None,
|
||||
}),
|
||||
started_at: summary.started_at,
|
||||
completed_at: summary.completed_at,
|
||||
duration_ms: summary.duration_ms,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn transcript(
|
||||
thread_id: String,
|
||||
update: cloud::TranscriptUpdate,
|
||||
) -> Result<Option<protocol::ServerNotification>> {
|
||||
use protocol::ServerNotification as Notification;
|
||||
Ok(Some(match update {
|
||||
cloud::TranscriptUpdate::TurnStarted(summary) => {
|
||||
Notification::TurnStarted(protocol::TurnStartedNotification {
|
||||
thread_id,
|
||||
turn: turn(summary)?,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::TurnCompleted(summary) => {
|
||||
Notification::TurnCompleted(protocol::TurnCompletedNotification {
|
||||
thread_id,
|
||||
turn: turn(summary)?,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::AgentMessageDelta(delta) => {
|
||||
Notification::AgentMessageDelta(protocol::AgentMessageDeltaNotification {
|
||||
thread_id,
|
||||
turn_id: delta.turn_id,
|
||||
item_id: delta.item_id,
|
||||
delta: delta.delta,
|
||||
})
|
||||
}
|
||||
cloud::TranscriptUpdate::ItemStarted(item) => {
|
||||
let Some(content) = item_summary(item.item) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Notification::ItemStarted(protocol::ItemStartedNotification::new(
|
||||
thread_id,
|
||||
item.turn_id,
|
||||
content.payload,
|
||||
item.at_ms,
|
||||
))
|
||||
}
|
||||
cloud::TranscriptUpdate::ItemCompleted(item) => {
|
||||
let Some(content) = item_summary(item.item) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Notification::ItemCompleted(protocol::ItemCompletedNotification::new(
|
||||
thread_id,
|
||||
item.turn_id,
|
||||
content.payload,
|
||||
/*started_at_ms*/ None,
|
||||
item.at_ms,
|
||||
))
|
||||
}
|
||||
cloud::TranscriptUpdate::CommandOutputDelta(_)
|
||||
| cloud::TranscriptUpdate::FileChangeOutputDelta(_)
|
||||
| cloud::TranscriptUpdate::FileChangePatchUpdated(_) => return Ok(None),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn item_summary(item: cloud::ItemSummary) -> Option<protocol::ThreadItem> {
|
||||
let payload = match item {
|
||||
cloud::ItemSummary::UserMessage {
|
||||
id,
|
||||
client_id,
|
||||
content,
|
||||
} => protocol::ThreadItemPayload::UserMessage {
|
||||
id,
|
||||
client_id,
|
||||
content: content
|
||||
.into_iter()
|
||||
.map(|item| match item {
|
||||
cloud::UserMessageInput::Text {
|
||||
text,
|
||||
text_elements,
|
||||
} => protocol::UserInput::Text {
|
||||
text,
|
||||
text_elements: text_elements
|
||||
.into_iter()
|
||||
.map(|element| {
|
||||
protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: element.start,
|
||||
end: element.end,
|
||||
},
|
||||
element.placeholder,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
cloud::UserMessageInput::Image { image, detail } => {
|
||||
protocol::UserInput::Image {
|
||||
image: match image {
|
||||
cloud::ImageReference::Url(url) => {
|
||||
protocol::ImageReference::Inline { url }
|
||||
}
|
||||
cloud::ImageReference::FileId(file_id) => {
|
||||
protocol::ImageReference::File { file_id }
|
||||
}
|
||||
},
|
||||
detail: detail.map(|detail| match detail {
|
||||
cloud::ImageDetail::Auto => ImageDetail::Auto,
|
||||
cloud::ImageDetail::Low => ImageDetail::Low,
|
||||
cloud::ImageDetail::High => ImageDetail::High,
|
||||
cloud::ImageDetail::Original => ImageDetail::Original,
|
||||
}),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
cloud::ItemSummary::AgentMessage {
|
||||
id,
|
||||
text,
|
||||
questions,
|
||||
} => protocol::ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id,
|
||||
text,
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: questions.map(|questions| {
|
||||
questions
|
||||
.into_iter()
|
||||
.map(|question| protocol::AsyncUserInputQuestion {
|
||||
title: question.title,
|
||||
options: question.options,
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
},
|
||||
cloud::ItemSummary::Reasoning { .. }
|
||||
| cloud::ItemSummary::CommandExecution(_)
|
||||
| cloud::ItemSummary::FileChange { .. } => return None,
|
||||
};
|
||||
Some(protocol::ThreadItem::untimed(payload))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "events_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,98 +0,0 @@
|
||||
#![cfg(test)]
|
||||
//! Covers the user receipt and final assistant message presented by Cloud.
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn image_receipt_preserves_submission_identity_and_attachment() {
|
||||
let label = "[Image #1]";
|
||||
let actual = item_summary(cloud::ItemSummary::UserMessage {
|
||||
id: "item-1".into(),
|
||||
client_id: Some("submission-1".into()),
|
||||
content: vec![
|
||||
cloud::UserMessageInput::Image {
|
||||
image: cloud::ImageReference::FileId("file-synthetic".into()),
|
||||
detail: Some(cloud::ImageDetail::High),
|
||||
},
|
||||
cloud::UserMessageInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![cloud::UserMessageTextElement {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
placeholder: Some(label.into()),
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
assert_eq!(
|
||||
actual,
|
||||
Some(protocol::ThreadItem::untimed(
|
||||
protocol::ThreadItemPayload::UserMessage {
|
||||
id: "item-1".into(),
|
||||
client_id: Some("submission-1".into()),
|
||||
content: vec![
|
||||
protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::File {
|
||||
file_id: "file-synthetic".into(),
|
||||
},
|
||||
detail: Some(ImageDetail::High),
|
||||
},
|
||||
protocol::UserInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
},
|
||||
Some(label.into()),
|
||||
)],
|
||||
},
|
||||
],
|
||||
},
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_reply_preserves_the_full_text_questions_and_timestamp() -> Result<()> {
|
||||
let item = cloud::ItemSummary::AgentMessage {
|
||||
id: "reply".into(),
|
||||
text: "Choose one".into(),
|
||||
questions: Some(vec![cloud::AgentQuestion {
|
||||
title: "Which?".into(),
|
||||
options: Some(vec!["One".into(), "Two".into()]),
|
||||
}]),
|
||||
};
|
||||
let update = cloud::TranscriptUpdate::ItemCompleted(cloud::ItemLifecycle {
|
||||
turn_id: "turn".into(),
|
||||
at_ms: 45,
|
||||
item,
|
||||
});
|
||||
let Some(protocol::ServerNotification::ItemCompleted(actual)) =
|
||||
transcript("thread".into(), update)?
|
||||
else {
|
||||
panic!("expected a completed message");
|
||||
};
|
||||
assert_eq!(
|
||||
actual,
|
||||
protocol::ItemCompletedNotification::new(
|
||||
"thread".into(),
|
||||
"turn".into(),
|
||||
protocol::ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "reply".into(),
|
||||
text: "Choose one".into(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: Some(vec![protocol::AsyncUserInputQuestion {
|
||||
title: "Which?".into(),
|
||||
options: Some(vec!["One".into(), "Two".into()]),
|
||||
}]),
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 45
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
//! Adapts native Cloud requests and the currently open conversation’s reply stream.
|
||||
//! A replacement becomes active only after its native attachment opens successfully.
|
||||
|
||||
mod auth;
|
||||
mod events;
|
||||
mod requests;
|
||||
|
||||
use crate::AppServerClient;
|
||||
use crate::AppServerEvent;
|
||||
use crate::CloudClient;
|
||||
use crate::CloudOperation;
|
||||
use crate::cloud::CloudStreamLosses;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::BoxStream;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub use auth::connect;
|
||||
|
||||
type ReplyStream = BoxStream<'static, Result<cloud::Event, cloud::Error>>;
|
||||
|
||||
/// Rejected locally before an admission request can be sent.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
struct PreflightRejection(&'static str);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Cloud stream is not connected. Reopen the conversation before sending.")]
|
||||
struct MissingReplyAttachment;
|
||||
|
||||
struct Attachment {
|
||||
thread_id: String,
|
||||
stream: ReplyStream,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Replies {
|
||||
active: Option<Attachment>,
|
||||
stream_losses: CloudStreamLosses,
|
||||
// Keep the last observed status through EOF until this conversation is unloaded.
|
||||
latest_status: Option<(String, cloud::ThreadStatus)>,
|
||||
}
|
||||
|
||||
impl Replies {
|
||||
async fn forward_next(&mut self, output: &mpsc::UnboundedSender<AppServerEvent>) {
|
||||
let Some(active) = &mut self.active else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
match active.stream.next().await {
|
||||
Some(Ok(event)) => forward(&active.thread_id, event, output, &mut self.latest_status),
|
||||
Some(Err(_)) | None => {
|
||||
let error = cloud_error(
|
||||
&active.thread_id,
|
||||
"Cloud stream ended. Reopen the conversation to reconnect.",
|
||||
);
|
||||
self.active = None;
|
||||
self.stream_losses.record(&error.thread_id);
|
||||
let _ = output.send(AppServerEvent::ThreadStreamDisconnected(Box::new(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn while_listening<T>(
|
||||
&mut self,
|
||||
future: impl Future<Output = T>,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> T {
|
||||
tokio::pin!(future);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut future => return result,
|
||||
() = self.forward_next(output) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn replace(
|
||||
&mut self,
|
||||
id: &str,
|
||||
open: impl Future<Output = Result<ReplyStream, cloud::Error>>,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<()> {
|
||||
let mut stream = self.while_listening(open, output).await?;
|
||||
// A server can close Attach immediately after returning successful headers.
|
||||
// A healthy idle stream needs no event to prove that it is ready.
|
||||
let first_event = match tokio::task::unconstrained(stream.next()).now_or_never() {
|
||||
Some(None | Some(Err(_))) => bail!(
|
||||
"Cloud conversation activated but its stream did not connect. Reopen it before sending."
|
||||
),
|
||||
Some(Some(Ok(event))) => Some(event),
|
||||
None => None,
|
||||
};
|
||||
self.active = Some(Attachment {
|
||||
thread_id: id.to_owned(),
|
||||
stream,
|
||||
});
|
||||
self.stream_losses.supersede(id);
|
||||
self.latest_status = None;
|
||||
if let Some(event) = first_event {
|
||||
forward(id, event, output, &mut self.latest_status);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn thread_status(&self, id: &str) -> Option<&cloud::ThreadStatus> {
|
||||
self.latest_status
|
||||
.as_ref()
|
||||
.filter(|(thread_id, _)| thread_id == id)
|
||||
.map(|(_, status)| status)
|
||||
}
|
||||
|
||||
fn detach(&mut self, id: &str) {
|
||||
if self.thread_status(id).is_some() {
|
||||
self.latest_status = None;
|
||||
}
|
||||
if self
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|active| active.thread_id == id)
|
||||
{
|
||||
self.active = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_turn(
|
||||
&mut self,
|
||||
id: &str,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<(), MissingReplyAttachment> {
|
||||
// Notice a ready disconnect before sending. A continuous stream of events
|
||||
// must still allow commands to make progress.
|
||||
let _ = tokio::task::unconstrained(self.forward_next(output)).now_or_never();
|
||||
if self
|
||||
.active
|
||||
.as_ref()
|
||||
.is_none_or(|active| active.thread_id != id)
|
||||
{
|
||||
return Err(MissingReplyAttachment);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens an app-server client backed by the authenticated native Cloud client.
|
||||
fn start_worker(client: cloud::Client, account: protocol::GetAccountResponse) -> AppServerClient {
|
||||
let (app_client, commands, output) = CloudClient::channel(/*capacity*/ 32);
|
||||
let mut requests = requests::Requests {
|
||||
client,
|
||||
account,
|
||||
loaded: None,
|
||||
warned_partial_history: None,
|
||||
};
|
||||
let mut replies = Replies {
|
||||
stream_losses: app_client.stream_losses.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
run_worker(commands, &mut requests, &mut replies, &output).await;
|
||||
});
|
||||
AppServerClient::Cloud(app_client)
|
||||
}
|
||||
|
||||
async fn run_worker(
|
||||
mut commands: mpsc::Receiver<crate::CloudCommand>,
|
||||
requests: &mut requests::Requests,
|
||||
replies: &mut Replies,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) {
|
||||
loop {
|
||||
let command = tokio::select! {
|
||||
_ = output.closed() => return,
|
||||
() = replies.forward_next(output) => continue,
|
||||
command = commands.recv() => match command { Some(command) => command, None => return },
|
||||
};
|
||||
let user_message_submission =
|
||||
matches!(&command.operation, CloudOperation::SubmitUserMessage(_));
|
||||
let request = match command.operation {
|
||||
CloudOperation::Shutdown => {
|
||||
let _ = command.response.send(Ok(Ok(Value::Null)));
|
||||
return;
|
||||
}
|
||||
CloudOperation::Request(request) => {
|
||||
Ok((*request, cloud::SubmissionMode::StartIfIdle, None))
|
||||
}
|
||||
CloudOperation::StartProjectThread {
|
||||
request_id,
|
||||
params,
|
||||
project,
|
||||
} => Ok((
|
||||
protocol::ClientRequest::ThreadStart {
|
||||
request_id,
|
||||
params: *params,
|
||||
},
|
||||
cloud::SubmissionMode::StartIfIdle,
|
||||
Some(project),
|
||||
)),
|
||||
CloudOperation::SubmitUserMessage(params) => Ok((
|
||||
protocol::ClientRequest::TurnStart {
|
||||
// Native admission is keyed by the caller's stable message ID.
|
||||
request_id: protocol::RequestId::Integer(0),
|
||||
params: *params,
|
||||
},
|
||||
cloud::SubmissionMode::Steer,
|
||||
None,
|
||||
)),
|
||||
CloudOperation::Notify(_) => {
|
||||
Err(eyre!("Cloud client notifications are not supported yet."))
|
||||
}
|
||||
CloudOperation::Resolve { .. } | CloudOperation::Reject { .. } => Err(eyre!(
|
||||
"Answer this cloud approval in another client; TUI approval replies are not supported yet."
|
||||
)),
|
||||
};
|
||||
let result = match request {
|
||||
Ok((request, mode, project)) => tokio::select! {
|
||||
_ = output.closed() => return,
|
||||
result = handle_request(request, mode, project, requests, replies, output) => result,
|
||||
},
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let result = result.map_err(|error| protocol::JSONRPCErrorError {
|
||||
code: if error
|
||||
.downcast_ref::<requests::UnsupportedOperation>()
|
||||
.is_some()
|
||||
{
|
||||
-32601
|
||||
} else if error.is::<PreflightRejection>()
|
||||
|| user_message_submission && error.is::<MissingReplyAttachment>()
|
||||
{
|
||||
-32602
|
||||
} else {
|
||||
-32000
|
||||
},
|
||||
message: error.to_string(),
|
||||
data: None,
|
||||
});
|
||||
let _ = command.response.send(Ok(result));
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_request(
|
||||
request: protocol::ClientRequest,
|
||||
mode: cloud::SubmissionMode,
|
||||
project: Option<cloud::ProjectEnvironment>,
|
||||
requests: &mut requests::Requests,
|
||||
replies: &mut Replies,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
) -> Result<Value> {
|
||||
if let protocol::ClientRequest::ThreadRead { params, .. } = &request {
|
||||
return requests.read_thread(params, replies.thread_status(¶ms.thread_id));
|
||||
}
|
||||
if let protocol::ClientRequest::ThreadUnsubscribe { params, .. } = &request {
|
||||
let status = if requests
|
||||
.loaded
|
||||
.as_ref()
|
||||
.is_some_and(|loaded| loaded.thread.id == params.thread_id)
|
||||
{
|
||||
replies.detach(¶ms.thread_id);
|
||||
requests.loaded = None;
|
||||
protocol::ThreadUnsubscribeStatus::Unsubscribed
|
||||
} else {
|
||||
protocol::ThreadUnsubscribeStatus::NotSubscribed
|
||||
};
|
||||
return Ok(serde_json::json!({ "status": status }));
|
||||
}
|
||||
if let protocol::ClientRequest::TurnStart { params, .. } = &request {
|
||||
replies.admit_turn(¶ms.thread_id, output)?;
|
||||
}
|
||||
match replies
|
||||
.while_listening(requests.handle(request, mode, project, output), output)
|
||||
.await?
|
||||
{
|
||||
requests::Response::Value(value) => Ok(value),
|
||||
requests::Response::Attach(settings) => {
|
||||
let id = &settings.thread.id;
|
||||
let result = serde_json::to_value(&settings)?;
|
||||
replies
|
||||
.replace(id, requests.client.attach(id), output)
|
||||
.await?;
|
||||
requests.loaded = Some(settings);
|
||||
requests.warned_partial_history = None;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forward(
|
||||
id: &str,
|
||||
event: cloud::Event,
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
latest_status: &mut Option<(String, cloud::ThreadStatus)>,
|
||||
) {
|
||||
if let Some(status) = event.thread_status_for(id) {
|
||||
*latest_status = Some((id.to_owned(), status));
|
||||
return;
|
||||
}
|
||||
let notification = match event {
|
||||
cloud::Event::Transcript(event) => match events::transcript(event.thread_id, event.update) {
|
||||
Ok(Some(notification)) => notification,
|
||||
Ok(None) => return,
|
||||
Err(_) => protocol::ServerNotification::Error(cloud_error(
|
||||
id,
|
||||
"The cloud sent an unsupported transcript event.",
|
||||
)),
|
||||
},
|
||||
cloud::Event::ServerRequest(_) => protocol::ServerNotification::Warning(protocol::WarningNotification {
|
||||
thread_id: Some(id.to_owned()),
|
||||
message: "This cloud turn requested an unsupported interaction. Open it in another client to continue.".into(),
|
||||
}),
|
||||
cloud::Event::Notification(_) => return,
|
||||
};
|
||||
send_notification(output, notification);
|
||||
}
|
||||
|
||||
fn send_notification(
|
||||
output: &mpsc::UnboundedSender<AppServerEvent>,
|
||||
notification: protocol::ServerNotification,
|
||||
) {
|
||||
let _ = output.send(AppServerEvent::ServerNotification(Box::new(notification)));
|
||||
}
|
||||
|
||||
fn cloud_error(id: &str, message: &str) -> protocol::ErrorNotification {
|
||||
protocol::ErrorNotification {
|
||||
thread_id: id.to_owned(),
|
||||
turn_id: String::new(),
|
||||
will_retry: false,
|
||||
error: protocol::TurnError {
|
||||
message: message.to_owned(),
|
||||
additional_details: None,
|
||||
codex_error_info: None,
|
||||
misalignment: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "connection_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "submission_tests.rs"]
|
||||
mod submission_tests;
|
||||
@@ -1,201 +0,0 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn ordinary_multi_backend_resume_queries_cloud_interactive_threads_on_every_page() {
|
||||
// The mixed picker has no shared cwd/provider filter. It sends conventional
|
||||
// interactive source names, even when the connection belongs to Cloud.
|
||||
for (cursor, state_db_only) in [(None, true), (Some("page-2"), false)] {
|
||||
let params = serde_json::from_value(json!({
|
||||
"currentAccountOnly": true,
|
||||
"cursor": cursor,
|
||||
"limit": 25,
|
||||
"sortKey": "updated_at",
|
||||
"modelProviders": [],
|
||||
"sourceKinds": ["cli", "vscode"],
|
||||
"archived": false,
|
||||
"useStateDbOnly": state_db_only,
|
||||
}))
|
||||
.unwrap();
|
||||
let query = thread_list_query(params).unwrap();
|
||||
assert_eq!(query.cursor.as_deref(), cursor);
|
||||
assert_eq!(query.limit, Some(25));
|
||||
assert!(matches!(query.sort_key, cloud::ThreadSortKey::UpdatedAt));
|
||||
assert!(matches!(
|
||||
query.sort_direction,
|
||||
cloud::ThreadSortDirection::Desc
|
||||
));
|
||||
assert!(query.originators.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_filters_do_not_return_unrelated_cloud_rows() {
|
||||
for filter in [
|
||||
json!({"archived": true}),
|
||||
json!({"sourceKinds": ["exec"]}),
|
||||
json!({"attachedToThreadId": "other"}),
|
||||
json!({"modelProviders": ["other"]}),
|
||||
] {
|
||||
let params = serde_json::from_value(filter).unwrap();
|
||||
assert!(thread_list_query(params).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn message() -> protocol::TurnStartParams {
|
||||
let text = |text: &str| protocol::UserInput::Text {
|
||||
text: text.to_owned(),
|
||||
text_elements: Vec::new(),
|
||||
};
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "thread-a".into(),
|
||||
client_user_message_id: Some("submission-a".into()),
|
||||
turn_trigger: Some("safety_recourse_follow_up".into()),
|
||||
input: vec![text("one"), text("two")],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_input_uses_stable_id_and_the_existing_cloud_configuration() {
|
||||
let request = cloud_message(message()).unwrap();
|
||||
assert_eq!(request.thread_id, "thread-a");
|
||||
assert_eq!(request.client_user_message_id, "submission-a");
|
||||
assert_eq!(
|
||||
request.input,
|
||||
vec![cloud::UserMessageInput::Text {
|
||||
text: "one\ntwo".into(),
|
||||
text_elements: Vec::new(),
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
request.turn_trigger.as_deref(),
|
||||
Some("safety_recourse_follow_up")
|
||||
);
|
||||
assert!(matches!(request.mode, cloud::SubmissionMode::StartIfIdle));
|
||||
assert!(!request.shared_access);
|
||||
|
||||
for tier in ["default", "priority"] {
|
||||
assert!(
|
||||
cloud_message(protocol::TurnStartParams {
|
||||
service_tier_for_turn: Some(tier.into()),
|
||||
..message()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
cloud_message(protocol::TurnStartParams {
|
||||
client_user_message_id: None,
|
||||
..message()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_submission_keeps_attachment_markers_and_input_order() {
|
||||
let label = "[Image #1]";
|
||||
let request = cloud_message(protocol::TurnStartParams {
|
||||
input: vec![
|
||||
protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::File {
|
||||
file_id: "file-synthetic".into(),
|
||||
},
|
||||
detail: Some(ImageDetail::High),
|
||||
},
|
||||
protocol::UserInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![protocol::TextElement::new(
|
||||
protocol::ByteRange {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
},
|
||||
Some(label.into()),
|
||||
)],
|
||||
},
|
||||
],
|
||||
..message()
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
request.input,
|
||||
vec![
|
||||
cloud::UserMessageInput::Image {
|
||||
image: cloud::ImageReference::FileId("file-synthetic".into()),
|
||||
detail: Some(cloud::ImageDetail::High),
|
||||
},
|
||||
cloud::UserMessageInput::Text {
|
||||
text: format!("{label} describe"),
|
||||
text_elements: vec![cloud::UserMessageTextElement {
|
||||
start: 0,
|
||||
end: label.len(),
|
||||
placeholder: Some(label.into()),
|
||||
}],
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_and_queued_admissions_never_invent_a_running_turn() {
|
||||
for outcome in [
|
||||
cloud::AdmissionOutcome::Duplicate { turn_id: None },
|
||||
cloud::AdmissionOutcome::Duplicate {
|
||||
turn_id: Some("completed-or-running".into()),
|
||||
},
|
||||
cloud::AdmissionOutcome::Queued {
|
||||
submission_id: "queued".into(),
|
||||
},
|
||||
] {
|
||||
assert!(
|
||||
admitted_turn(outcome)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("already accepted")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_receipts_preserve_server_turns_and_duplicate_identity() -> Result<()> {
|
||||
let turn = |id: &str, status| cloud::TurnSummary {
|
||||
id: id.into(),
|
||||
status,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
};
|
||||
for (outcome, expected) in [
|
||||
(
|
||||
cloud::AdmissionOutcome::Started(turn("u", cloud::TurnStatus::InProgress)),
|
||||
("started", "u", protocol::TurnStatus::InProgress),
|
||||
),
|
||||
(
|
||||
cloud::AdmissionOutcome::Steered(turn("v", cloud::TurnStatus::Completed)),
|
||||
("steered", "v", protocol::TurnStatus::Completed),
|
||||
),
|
||||
] {
|
||||
let (kind, turn) = match admitted_message(outcome)? {
|
||||
CloudUserMessageReceipt::Started(turn) => ("started", turn),
|
||||
CloudUserMessageReceipt::Steered(turn) => ("steered", turn),
|
||||
CloudUserMessageReceipt::Duplicate { .. } => panic!("expected a turn"),
|
||||
};
|
||||
assert_eq!((kind, turn.id.as_str(), turn.status), expected);
|
||||
}
|
||||
for turn_id in [None, Some("original".into())] {
|
||||
let CloudUserMessageReceipt::Duplicate { turn_id: actual } =
|
||||
admitted_message(cloud::AdmissionOutcome::Duplicate {
|
||||
turn_id: turn_id.clone(),
|
||||
})?
|
||||
else {
|
||||
panic!("a duplicate must not become a running turn");
|
||||
};
|
||||
assert_eq!(actual, turn_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
//! Maps conversation requests onto native Cloud operations.
|
||||
|
||||
use super::PreflightRejection;
|
||||
use super::events;
|
||||
use super::send_notification;
|
||||
use crate::CloudUserMessageReceipt;
|
||||
use codex_app_server_protocol as protocol;
|
||||
use codex_cloud_client as cloud;
|
||||
use codex_protocol::models::ImageDetail;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::bail;
|
||||
use color_eyre::eyre::eyre;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0} is not supported by the cloud backend yet.")]
|
||||
pub(super) struct UnsupportedOperation(pub(super) String);
|
||||
|
||||
pub(super) struct Requests {
|
||||
pub(super) client: cloud::Client,
|
||||
pub(super) account: protocol::GetAccountResponse,
|
||||
pub(super) loaded: Option<Box<protocol::ThreadResumeResponse>>,
|
||||
pub(super) warned_partial_history: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) enum Response {
|
||||
Value(Value),
|
||||
Attach(Box<protocol::ThreadResumeResponse>),
|
||||
}
|
||||
|
||||
impl Requests {
|
||||
pub(super) fn read_thread(
|
||||
&self,
|
||||
params: &protocol::ThreadReadParams,
|
||||
status: Option<&cloud::ThreadStatus>,
|
||||
) -> Result<Value> {
|
||||
if params.include_turns {
|
||||
bail!("Use paginated history for cloud conversations.");
|
||||
}
|
||||
let loaded = self
|
||||
.loaded
|
||||
.as_deref()
|
||||
.filter(|loaded| loaded.thread.id == params.thread_id)
|
||||
.ok_or_else(|| eyre!("Open this cloud conversation before reading its transcript."))?;
|
||||
let mut thread = serde_json::to_value(&loaded.thread)?;
|
||||
if let Some(status) = status {
|
||||
thread["status"] = serde_json::to_value(status)?;
|
||||
}
|
||||
Ok(json!({"thread": thread, "readState": null}))
|
||||
}
|
||||
|
||||
pub(super) async fn handle(
|
||||
&mut self,
|
||||
request: protocol::ClientRequest,
|
||||
mode: cloud::SubmissionMode,
|
||||
project: Option<cloud::ProjectEnvironment>,
|
||||
output: &mpsc::UnboundedSender<crate::AppServerEvent>,
|
||||
) -> Result<Response> {
|
||||
use protocol::ClientRequest as Request;
|
||||
|
||||
let value = match request {
|
||||
Request::GetAccount { .. } => serde_json::to_value(&self.account)?,
|
||||
Request::ThreadList { params, .. } => {
|
||||
let query = thread_list_query(params)?;
|
||||
let mut page = self.client.list_threads(&query).await?;
|
||||
for thread in &mut page.data {
|
||||
use_paginated_history(thread);
|
||||
}
|
||||
serde_json::to_value(page)?
|
||||
}
|
||||
Request::ThreadStart { mut params, .. } => {
|
||||
let model = params.model.take();
|
||||
let provider = params.model_provider.take();
|
||||
if params.ephemeral == Some(false) {
|
||||
params.ephemeral = None;
|
||||
}
|
||||
if params != protocol::ThreadStartParams::default() {
|
||||
bail!(
|
||||
"Cloud conversations start with server defaults. Custom settings are not supported yet."
|
||||
);
|
||||
}
|
||||
let settings = self.client.prewarm_thread(model, provider, project).await?;
|
||||
return attach_response(settings);
|
||||
}
|
||||
Request::ThreadResume { params, .. } => {
|
||||
let supported = protocol::ThreadResumeParams {
|
||||
thread_id: params.thread_id.clone(),
|
||||
exclude_turns: true,
|
||||
..Default::default()
|
||||
};
|
||||
if params != supported {
|
||||
bail!(
|
||||
"Cloud conversations resume by ID with saved settings. Set excludeTurns to true and load history separately."
|
||||
);
|
||||
}
|
||||
let settings = self.client.activate(¶ms.thread_id).await?;
|
||||
return attach_response(settings);
|
||||
}
|
||||
Request::ThreadLoadedList { .. } => {
|
||||
let ids = self
|
||||
.loaded
|
||||
.iter()
|
||||
.map(|loaded| &loaded.thread.id)
|
||||
.collect::<Vec<_>>();
|
||||
json!({"data": ids, "nextCursor": null})
|
||||
}
|
||||
Request::ThreadTurnsList { params, .. } => {
|
||||
if params.items_view != Some(protocol::TurnItemsView::NotLoaded) {
|
||||
bail!("Read cloud turn items separately with thread/items/list.");
|
||||
}
|
||||
let page = self
|
||||
.client
|
||||
.list_turns(&cloud::ListTurnsRequest {
|
||||
thread_id: params.thread_id,
|
||||
page: cloud::HistoryQuery {
|
||||
cursor: params.cursor,
|
||||
limit: params.limit,
|
||||
order: history_order(
|
||||
params
|
||||
.sort_direction
|
||||
.unwrap_or(protocol::SortDirection::Desc),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
serde_json::to_value(protocol::ThreadTurnsListResponse {
|
||||
data: page
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|entry| events::turn(entry.summary))
|
||||
.collect::<Result<_>>()?,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})?
|
||||
}
|
||||
Request::ThreadItemsList { params, .. } => {
|
||||
let cursor = match params.cursor {
|
||||
Some(protocol::ThreadItemsListCursor::Opaque(cursor)) => Some(cursor),
|
||||
None => None,
|
||||
Some(protocol::ThreadItemsListCursor::Anchor(_)) => {
|
||||
bail!("Cloud item anchors are not supported yet.")
|
||||
}
|
||||
};
|
||||
let page = self
|
||||
.client
|
||||
.list_items(&cloud::ListItemsRequest {
|
||||
thread_id: params.thread_id.clone(),
|
||||
turn_id: params.turn_id,
|
||||
page: cloud::HistoryQuery {
|
||||
cursor,
|
||||
limit: params.limit,
|
||||
order: history_order(
|
||||
params
|
||||
.sort_direction
|
||||
.unwrap_or(protocol::SortDirection::Asc),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let size = page.data.len();
|
||||
let data = page
|
||||
.data
|
||||
.into_iter()
|
||||
.filter_map(|entry| {
|
||||
Some(protocol::ThreadItemEntry {
|
||||
turn_id: entry.turn_id,
|
||||
item: events::item_summary(entry.summary?)?,
|
||||
output_deferred: false,
|
||||
started_at_ms: entry.started_at_ms,
|
||||
completed_at_ms: entry.completed_at_ms,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if data.len() != size
|
||||
&& self.warned_partial_history.as_ref() != Some(¶ms.thread_id)
|
||||
{
|
||||
self.warned_partial_history = Some(params.thread_id.clone());
|
||||
let warning = protocol::WarningNotification {
|
||||
thread_id: Some(params.thread_id),
|
||||
message: "Some Cloud history items cannot be displayed in this preview."
|
||||
.to_owned(),
|
||||
};
|
||||
send_notification(output, protocol::ServerNotification::Warning(warning));
|
||||
}
|
||||
serde_json::to_value(protocol::ThreadItemsListResponse {
|
||||
data,
|
||||
next_cursor: page.next_cursor,
|
||||
backwards_cursor: page.backwards_cursor,
|
||||
})?
|
||||
}
|
||||
Request::TurnStart { params, .. } => {
|
||||
let mut message = cloud_message(params)?;
|
||||
message.mode = mode;
|
||||
let admission = match self.client.add_user_message(&message).await {
|
||||
Err(cloud::MutationError::InvalidRequest) => {
|
||||
return Err(PreflightRejection(
|
||||
"The Cloud message is empty, invalid, or too large.",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
if matches!(mode, cloud::SubmissionMode::Steer) {
|
||||
serde_json::to_value(admitted_message(admission.outcome)?)?
|
||||
} else {
|
||||
let turn = admitted_turn(admission.outcome)?;
|
||||
serde_json::to_value(protocol::TurnStartResponse { turn })?
|
||||
}
|
||||
}
|
||||
Request::TurnInterrupt { params, .. } => {
|
||||
self.client
|
||||
.interrupt_turn(&cloud::InterruptTurnRequest {
|
||||
thread_id: params.thread_id,
|
||||
turn_id: params.turn_id,
|
||||
shared_access: false,
|
||||
})
|
||||
.await?;
|
||||
serde_json::to_value(protocol::TurnInterruptResponse {})?
|
||||
}
|
||||
other => return Err(UnsupportedOperation(other.method_name().to_owned()).into()),
|
||||
};
|
||||
Ok(Response::Value(value))
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_response(mut settings: cloud::ThreadActivation) -> Result<Response> {
|
||||
use_paginated_history(&mut settings.thread);
|
||||
let resolved = serde_json::from_value(serde_json::to_value(settings)?)
|
||||
.map_err(|_| eyre!("The cloud returned unsupported conversation settings."))?;
|
||||
Ok(Response::Attach(resolved))
|
||||
}
|
||||
|
||||
// Cloud serves history in pages even when an older thread used the legacy rollout format.
|
||||
fn use_paginated_history(thread: &mut cloud::ThreadSnapshot) {
|
||||
thread.history_mode = cloud::ThreadHistoryMode::Paginated;
|
||||
}
|
||||
|
||||
fn thread_list_query(params: protocol::ThreadListParams) -> Result<cloud::ThreadListQuery> {
|
||||
use protocol::ThreadSourceKind::Cli;
|
||||
use protocol::ThreadSourceKind::VsCode;
|
||||
// The resume picker's ordinary interactive list maps to Cloud's own interactive default.
|
||||
// Its explicit CLI/VS Code defaults are conventional source names.
|
||||
let sources = params.source_kinds.as_deref().unwrap_or_default();
|
||||
if !matches!(sources, [] | [Cli, VsCode] | [VsCode, Cli])
|
||||
|| params.archived == Some(true)
|
||||
|| params.cwd.is_some()
|
||||
|| params.search_term.is_some()
|
||||
|| params.section_id.is_some()
|
||||
|| params.project_id.is_some()
|
||||
|| params.parent_thread_id.is_some()
|
||||
|| params.ancestor_thread_id.is_some()
|
||||
|| params.attached_to_thread_id.is_some()
|
||||
|| params
|
||||
.model_providers
|
||||
.as_ref()
|
||||
.is_some_and(|values| !values.is_empty())
|
||||
|| params
|
||||
.excluded_thread_ids
|
||||
.as_ref()
|
||||
.is_some_and(|values| !values.is_empty())
|
||||
{
|
||||
bail!("These cloud conversation filters are not supported yet.");
|
||||
}
|
||||
Ok(cloud::ThreadListQuery {
|
||||
cursor: params.cursor,
|
||||
limit: params.limit,
|
||||
originators: params.originators.unwrap_or_default(),
|
||||
sort_key: match params.sort_key {
|
||||
Some(protocol::ThreadSortKey::CreatedAt) | None => cloud::ThreadSortKey::CreatedAt,
|
||||
Some(protocol::ThreadSortKey::UpdatedAt) => cloud::ThreadSortKey::UpdatedAt,
|
||||
Some(protocol::ThreadSortKey::RecencyAt) => cloud::ThreadSortKey::RecencyAt,
|
||||
Some(protocol::ThreadSortKey::SectionPosition) => {
|
||||
bail!("Cloud section ordering is not supported yet.")
|
||||
}
|
||||
},
|
||||
sort_direction: match params.sort_direction {
|
||||
Some(protocol::SortDirection::Asc) => cloud::ThreadSortDirection::Asc,
|
||||
Some(protocol::SortDirection::Desc) | None => cloud::ThreadSortDirection::Desc,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn history_order(direction: protocol::SortDirection) -> cloud::HistoryOrder {
|
||||
match direction {
|
||||
protocol::SortDirection::Asc => cloud::HistoryOrder::Ascending,
|
||||
protocol::SortDirection::Desc => cloud::HistoryOrder::Descending,
|
||||
}
|
||||
}
|
||||
|
||||
fn cloud_message(
|
||||
mut params: protocol::TurnStartParams,
|
||||
) -> Result<cloud::AddUserMessageRequest, PreflightRejection> {
|
||||
let thread_id = std::mem::take(&mut params.thread_id);
|
||||
let client_user_message_id = params
|
||||
.client_user_message_id
|
||||
.take()
|
||||
.ok_or(PreflightRejection(
|
||||
"A cloud message needs a stable submission ID.",
|
||||
))?;
|
||||
let input = std::mem::take(&mut params.input);
|
||||
let turn_trigger = params.turn_trigger.take();
|
||||
if params != protocol::TurnStartParams::default() {
|
||||
return Err(PreflightRejection(
|
||||
"Changing cloud settings or sending structured input is not supported yet.",
|
||||
));
|
||||
}
|
||||
let mut content = Vec::with_capacity(input.len());
|
||||
for item in input {
|
||||
let item = match item {
|
||||
protocol::UserInput::Text {
|
||||
text,
|
||||
text_elements,
|
||||
} => {
|
||||
// Keep the existing line separation for consecutive plain text parts.
|
||||
if text_elements.is_empty()
|
||||
&& let Some(cloud::UserMessageInput::Text {
|
||||
text: previous,
|
||||
text_elements: previous_elements,
|
||||
}) = content.last_mut()
|
||||
&& previous_elements.is_empty()
|
||||
{
|
||||
previous.push('\n');
|
||||
previous.push_str(&text);
|
||||
continue;
|
||||
}
|
||||
cloud::UserMessageInput::Text {
|
||||
text,
|
||||
text_elements: text_elements
|
||||
.into_iter()
|
||||
.map(|element| cloud::UserMessageTextElement {
|
||||
placeholder: element.placeholder().map(str::to_owned),
|
||||
start: element.byte_range.start,
|
||||
end: element.byte_range.end,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
protocol::UserInput::Image { image, detail } => cloud::UserMessageInput::Image {
|
||||
image: match image {
|
||||
protocol::ImageReference::Inline { url } => cloud::ImageReference::Url(url),
|
||||
protocol::ImageReference::File { file_id } => {
|
||||
cloud::ImageReference::FileId(file_id)
|
||||
}
|
||||
},
|
||||
detail: detail.map(|detail| match detail {
|
||||
ImageDetail::Auto => cloud::ImageDetail::Auto,
|
||||
ImageDetail::Low => cloud::ImageDetail::Low,
|
||||
ImageDetail::High => cloud::ImageDetail::High,
|
||||
ImageDetail::Original => cloud::ImageDetail::Original,
|
||||
}),
|
||||
},
|
||||
protocol::UserInput::LocalImage { .. } => {
|
||||
return Err(PreflightRejection(
|
||||
"Prepare local images before sending them to Cloud.",
|
||||
));
|
||||
}
|
||||
protocol::UserInput::Audio { .. }
|
||||
| protocol::UserInput::LocalAudio { .. }
|
||||
| protocol::UserInput::Skill { .. }
|
||||
| protocol::UserInput::Mention { .. } => {
|
||||
return Err(PreflightRejection(
|
||||
"Cloud conversations currently accept text and images.",
|
||||
));
|
||||
}
|
||||
};
|
||||
content.push(item);
|
||||
}
|
||||
Ok(cloud::AddUserMessageRequest {
|
||||
thread_id,
|
||||
client_user_message_id,
|
||||
input: content,
|
||||
turn_trigger,
|
||||
mode: cloud::SubmissionMode::StartIfIdle,
|
||||
shared_access: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn admitted_message(outcome: cloud::AdmissionOutcome) -> Result<CloudUserMessageReceipt> {
|
||||
Ok(match outcome {
|
||||
cloud::AdmissionOutcome::Started(turn) => {
|
||||
CloudUserMessageReceipt::Started(events::turn(turn)?)
|
||||
}
|
||||
cloud::AdmissionOutcome::Steered(turn) => {
|
||||
CloudUserMessageReceipt::Steered(events::turn(turn)?)
|
||||
}
|
||||
cloud::AdmissionOutcome::Duplicate { turn_id } => {
|
||||
CloudUserMessageReceipt::Duplicate { turn_id }
|
||||
}
|
||||
cloud::AdmissionOutcome::Queued { .. } => bail!(
|
||||
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn admitted_turn(outcome: cloud::AdmissionOutcome) -> Result<protocol::Turn> {
|
||||
match admitted_message(outcome)? {
|
||||
CloudUserMessageReceipt::Started(turn) | CloudUserMessageReceipt::Steered(turn) => Ok(turn),
|
||||
CloudUserMessageReceipt::Duplicate { .. } => bail!(
|
||||
"Cloud already accepted this message without returning a turn. Reopen the conversation to see its status before sending again."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,206 +0,0 @@
|
||||
#![cfg(test)]
|
||||
//! Exercises native admission and local validation through the command worker.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
fn submission(message_id: &str) -> protocol::TurnStartParams {
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "t".into(),
|
||||
client_user_message_id: Some(message_id.into()),
|
||||
input: vec![protocol::UserInput::Text {
|
||||
text: "hello".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_submission_uses_one_admission_and_keeps_preflight_guards() -> Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = crate::legacy_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_owned())
|
||||
.fallback_cwd(Some(home.path().to_owned()))
|
||||
.without_project_context()
|
||||
.build()
|
||||
.await?;
|
||||
let native = cloud::Client::new(
|
||||
&config.http_client_factory(),
|
||||
&server.uri(),
|
||||
cloud::Credentials::new("synthetic-bearer", "synthetic-account")?,
|
||||
)?;
|
||||
let account = protocol::GetAccountResponse {
|
||||
user_id: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
};
|
||||
let (client, commands, output) = crate::CloudClient::channel(/*capacity*/ 4);
|
||||
let client = crate::AppServerClient::Cloud(client);
|
||||
let handle = client.request_handle();
|
||||
let crate::AppServerRequestHandle::Cloud(cloud_handle) = &handle else {
|
||||
panic!("expected a Cloud handle");
|
||||
};
|
||||
let (reply_sender, stream) = futures::channel::mpsc::unbounded();
|
||||
let mut replies = Replies {
|
||||
active: Some(Attachment {
|
||||
thread_id: "t".into(),
|
||||
stream: stream.boxed(),
|
||||
}),
|
||||
..Replies::default()
|
||||
};
|
||||
let worker = tokio::spawn(async move {
|
||||
let mut requests = crate::cloud_backend::requests::Requests {
|
||||
client: native,
|
||||
account,
|
||||
loaded: None,
|
||||
warned_partial_history: None,
|
||||
};
|
||||
crate::cloud_backend::run_worker(commands, &mut requests, &mut replies, &output).await
|
||||
});
|
||||
let rpc = "/oaiproto.codex_app_server_backend.ThreadService/AddUserMessage";
|
||||
Mock::given(method("POST"))
|
||||
.and(path(rpc))
|
||||
.and(header("authorization", "Bearer synthetic-bearer"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let url = "data:image/png;base64,iVBORw0KGgo=";
|
||||
let image = protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::Inline { url: url.into() },
|
||||
detail: None,
|
||||
};
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) = cloud_handle
|
||||
.submit_user_message(protocol::TurnStartParams {
|
||||
input: vec![image.clone()],
|
||||
..submission("x")
|
||||
})
|
||||
.await
|
||||
else {
|
||||
panic!("a lost receipt must remain uncertain");
|
||||
};
|
||||
assert_eq!(source.code, -32000);
|
||||
assert!(source.message.contains("mutation outcome unknown"));
|
||||
// Existing typed turn/start callers keep StartIfIdle and the same native error.
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) = handle
|
||||
.request_typed::<protocol::TurnStartResponse>(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(1),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![
|
||||
image,
|
||||
protocol::UserInput::Text {
|
||||
text: "describe the image".into(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
],
|
||||
..submission("m")
|
||||
},
|
||||
})
|
||||
.await
|
||||
else {
|
||||
panic!("ordinary turn/start must retain its server error");
|
||||
};
|
||||
assert_eq!(source.code, -32000);
|
||||
assert!(source.message.contains("mutation outcome unknown"));
|
||||
|
||||
for params in [
|
||||
protocol::TurnStartParams {
|
||||
model: Some("other".into()),
|
||||
..submission("invalid")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
client_user_message_id: None,
|
||||
..submission("missing")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
input: Vec::new(),
|
||||
..submission("empty")
|
||||
},
|
||||
protocol::TurnStartParams {
|
||||
thread_id: "other".into(),
|
||||
..submission("foreign")
|
||||
},
|
||||
] {
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) =
|
||||
cloud_handle.submit_user_message(params).await
|
||||
else {
|
||||
panic!("invalid input must fail before admission");
|
||||
};
|
||||
assert_eq!(source.code, -32602);
|
||||
}
|
||||
let queued = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(3),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![protocol::UserInput::LocalImage {
|
||||
path: "queued.png".into(),
|
||||
detail: None,
|
||||
}],
|
||||
..submission("queued-image")
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.expect_err("a queued attachment must fail before admission");
|
||||
assert_eq!(queued.code, -32602);
|
||||
assert_eq!(
|
||||
queued.message,
|
||||
"Prepare local images before sending them to Cloud."
|
||||
);
|
||||
let invalid_image = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(4),
|
||||
params: protocol::TurnStartParams {
|
||||
input: vec![protocol::UserInput::Image {
|
||||
image: protocol::ImageReference::Inline { url: String::new() },
|
||||
detail: None,
|
||||
}],
|
||||
..submission("invalid-image")
|
||||
},
|
||||
})
|
||||
.await?
|
||||
.expect_err("an invalid image must fail before admission");
|
||||
assert_eq!(invalid_image.code, -32602);
|
||||
|
||||
drop(reply_sender);
|
||||
let Err(crate::TypedRequestError::Server { source, .. }) =
|
||||
cloud_handle.submit_user_message(submission("closed")).await
|
||||
else {
|
||||
panic!("a disconnected stream must reject input");
|
||||
};
|
||||
assert_eq!(source.code, -32602);
|
||||
let ordinary = handle
|
||||
.request(protocol::ClientRequest::TurnStart {
|
||||
request_id: protocol::RequestId::Integer(2),
|
||||
params: submission("closed"),
|
||||
})
|
||||
.await?
|
||||
.expect_err("ordinary turn/start keeps its existing disconnected error");
|
||||
assert_eq!(ordinary.code, -32000);
|
||||
|
||||
client.shutdown().await?;
|
||||
worker.await?;
|
||||
let calls = server.received_requests().await.unwrap();
|
||||
assert!(calls.iter().all(|request| {
|
||||
request
|
||||
.body
|
||||
.windows(url.len())
|
||||
.any(|bytes| bytes == url.as_bytes())
|
||||
}));
|
||||
assert_eq!(
|
||||
calls
|
||||
.iter()
|
||||
.map(|request| (request.body[7], *request.body.last().unwrap()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(b'x', 1), (b'm', 3)]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -21,8 +21,7 @@
|
||||
//! unread notifications cannot prevent request responses from being delivered.
|
||||
|
||||
mod cloud;
|
||||
pub mod cloud_backend;
|
||||
pub use codex_cloud_client::ProjectEnvironment;
|
||||
pub use cloud::ProjectEnvironment;
|
||||
mod path;
|
||||
mod remote;
|
||||
mod remote_websocket;
|
||||
@@ -725,7 +724,7 @@ impl AppServerRequestHandle {
|
||||
&self,
|
||||
request_id: RequestId,
|
||||
params: codex_app_server_protocol::ThreadStartParams,
|
||||
project: codex_cloud_client::ProjectEnvironment,
|
||||
project: ProjectEnvironment,
|
||||
) -> Result<codex_app_server_protocol::ThreadStartResponse, TypedRequestError> {
|
||||
let response = match self {
|
||||
Self::Cloud(handle) => {
|
||||
|
||||
Reference in New Issue
Block a user