Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions crates/acp/src/client/lifecycle_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ from pathlib import Path
mode = sys.argv[1]
def update(text):
return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':text}}}}
def activity(state):
return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'session_info_update','_meta':{'codex':{'threadStatus':{'type':state}}}}}}
pause_next_read = False
prompts = []
while True:
Expand Down Expand Up @@ -41,6 +43,14 @@ while True:
assert isinstance(replies, list) and len(replies) == 2, replies
assert {reply['id']: reply['error']['code'] for reply in replies} == {'first':-32601,'second':-32601}, replies
result = {'stopReason':'end_turn'}
elif method == 'session/prompt' and mode == 'autonomous':
print(json.dumps(activity('active')), flush=True)
print(json.dumps(activity('idle')), flush=True)
print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':{'stopReason':'end_turn'}}),flush=True)
print(json.dumps(activity('active')), flush=True)
print(json.dumps(update('continuation')), flush=True)
print(json.dumps(activity('idle')), flush=True)
continue
elif method == 'session/prompt' and mode == 'bench-text':
assert request['params']['prompt'] == [{'type':'text','text':'latency fixture'}]
result = {'stopReason':'end_turn'}
Expand Down Expand Up @@ -129,6 +139,66 @@ fn subprocess_batches_keep_update_order_and_group_replies() {
});
}

#[test]
fn subprocess_activity_arrives_even_after_the_prompt_response() {
use nocterm_ai::model::session::{SessionActivity, StopReason};

let exercise = async {
let directory = tempfile::tempdir().unwrap();
let connection = connection("autonomous", directory.path()).await;
let session = connection
.commands
.new_session(SessionOpen {
working_directory: directory.path().to_path_buf(),
endpoints: Vec::new(),
})
.await
.unwrap();
let result = connection
.commands
.prompt(PromptRequest {
session: session.session.clone(),
content: vec![nocterm_ai::model::content::Content::text("work")],
})
.await
.unwrap();
assert_eq!(result.stop_reason, StopReason::EndTurn);
for expected in [
Some(SessionActivity::Active),
Some(SessionActivity::Idle),
Some(SessionActivity::Active),
None,
Some(SessionActivity::Idle),
] {
let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else {
panic!("expected an ACP session update");
};
assert_eq!(event.session, session.session);
match (expected, event.update) {
(Some(activity), SessionUpdate::SessionInfoUpdate(info)) => {
assert_eq!(info.activity, Some(activity))
}
(None, SessionUpdate::AgentMessageChunk(content)) => assert_eq!(
content,
nocterm_ai::model::content::Content::text("continuation")
),
_ => panic!("unexpected update"),
}
}
connection.commands.shutdown_gracefully().await.unwrap();
};
futures::executor::block_on(async {
assert!(matches!(
select(
Box::pin(exercise),
Box::pin(async_io::Timer::after(Duration::from_secs(5)))
)
.await,
Either::Left(_)
));
});
}

#[test]
fn sends_a_full_composer_image_budget_to_the_agent() {
use nocterm_ai::model::session::StopReason;
Expand Down
18 changes: 17 additions & 1 deletion crates/acp/src/mapping/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use nocterm_ai::model::{
diagnostic::ModelError,
ids::{ModeId, SessionId},
plan::{Plan, PlanEntry, PlanPriority, PlanStatus},
session::{SessionInfo, SessionNotice, SessionUpdate},
session::{SessionActivity, SessionInfo, SessionNotice, SessionUpdate},
usage::{ContextUsage, Cost},
};

Expand Down Expand Up @@ -55,6 +55,21 @@ fn title(value: MaybeUndefined<String>) -> Change<String> {
_ => Change::Keep,
}
}
// codex-acp reports autonomous app-server turns through this session-info extension.
// Other provider metadata remains inert; unknown or malformed statuses do not change liveness.
fn session_activity(meta: Option<&wire::Meta>) -> Option<SessionActivity> {
match meta?
.get("codex")?
.get("threadStatus")?
.get("type")?
.as_str()?
{
"active" => Some(SessionActivity::Active),
"idle" => Some(SessionActivity::Idle),
_ => None,
}
}

fn update(value: wire::SessionUpdate) -> Result<SessionUpdate, ModelError> {
Ok(match value {
wire::SessionUpdate::UserMessageChunk(chunk) => {
Expand Down Expand Up @@ -85,6 +100,7 @@ fn update(value: wire::SessionUpdate) -> Result<SessionUpdate, ModelError> {
wire::SessionUpdate::SessionInfoUpdate(value) => {
SessionUpdate::SessionInfoUpdate(SessionInfo {
title: title(value.title),
activity: session_activity(value.meta.as_ref()),
meta: extensions(value.meta),
})
}
Expand Down
27 changes: 27 additions & 0 deletions crates/acp/src/mapping/session_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,30 @@ fn agent_introductions_keep_images_and_sign_in_methods() {
assert_eq!(setup.args, ["login"]);
assert_eq!(methods[1].label, "Setup");
}

#[test]
fn codex_thread_status_is_a_typed_activity_without_losing_the_title() {
for (status, expected) in [
(
json!({"type":"active","activeFlags":[]}),
Some(SessionActivity::Active),
),
(json!({"type":"idle"}), Some(SessionActivity::Idle)),
(json!({"type":"notLoaded"}), None),
(json!({"type":"future"}), None),
(json!("active"), None),
(json!(null), None),
] {
let notice = notice(update(json!({"update":{
"sessionUpdate":"session_info_update",
"title":"Still my chat",
"_meta":{"codex":{"threadStatus":status}}
}})))
.unwrap();
let SessionUpdate::SessionInfoUpdate(info) = notice.update else {
panic!("session info expected");
};
assert_eq!(info.title, Change::Set("Still my chat".into()));
assert_eq!(info.activity, expected);
}
}
26 changes: 14 additions & 12 deletions crates/agent-chat/src/thread/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ impl AgentThread {
self.state.set_pending_history(false, self.deps.timestamp());
self.persist(cx);
}
self.resume_observed_turn();
self.dispatch_next(cx);
cx.notify();
}
Expand All @@ -349,13 +350,6 @@ impl AgentThread {
}
}

pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) {
if !self.deps.enabled(cx) && self.state.release_disabled() {
self.config.disabled();
self.composer.reset_after_disable();
}
}

/// The chat's connection stopped. With AI turned off, the chat also
/// forgets its transcript and what was attached.
pub fn connection_stopped(&mut self, message: &str, cx: &mut Context<Self>) {
Expand All @@ -370,14 +364,22 @@ impl AgentThread {
self.config
.keep_control(self.session.ticket(), notification);
}
if self.session().as_ref() != Some(&notification.session) {
return;
}
if let SessionUpdate::Turn(activity) = &notification.update {
if self.session().as_ref() == Some(&notification.session) {
self.external_turn(activity, cx);
}
self.external_turn(activity, cx);
return;
}
if self.session().as_ref() != Some(&notification.session)
|| !self.session.accepts_updates()
if let SessionUpdate::SessionInfoUpdate(info) = &notification.update
&& let Some(activity) = info.activity
{
self.observe_session_activity(activity, cx);
if matches!(info.title, nocterm_ai::model::controls::Change::Keep) {
return;
}
}
if !self.session.accepts_updates()
|| matches!(notification.update, SessionUpdate::UserMessageChunk(_))
{
return;
Expand Down
1 change: 1 addition & 0 deletions crates/agent-chat/src/thread/document/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ fn update(value: serde_json::Value) -> SessionUpdate {
}),
"session_info_update" => SessionUpdate::SessionInfoUpdate(SessionInfo {
title: Change::Set(value["title"].as_str().unwrap().into()),
activity: None,
meta: None,
}),
"usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new(
Expand Down
126 changes: 44 additions & 82 deletions crates/agent-chat/src/thread/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use super::{
execution::WaitSubject,
};
use gpui::{App, Context, EntityId, Task};
use nocterm_ai::history::{SavedAttachment, SavedPrompt};
use nocterm_ai::model::content::Content;
use nocterm_ai::history::SavedAttachment;
use nocterm_ai::model::{content::Content, session::SessionActivity};
use nocterm_ai::{BridgeCall, TerminalCall, ToolFailure};

use nocterm_workspace_ports::{ExpectedSession, TerminalEntry, TerminalStatus};
Expand All @@ -20,48 +20,8 @@ use super::{AgentThread, Attachment};
mod submit_error;
pub(super) use submit_error::SubmitError;

#[derive(Clone)]
pub struct QueuedPrompt {
saved: Arc<SavedPrompt>,
attachments: Vec<Attachment>,
encoded_len: usize,
memory_len: usize,
}

impl QueuedPrompt {
#[cfg(any(test, feature = "test-support"))]
pub fn new(saved: SavedPrompt, attachments: Vec<Attachment>) -> Self {
Self::prepared(saved, attachments, None)
}
pub fn prepared(
saved: SavedPrompt,
attachments: Vec<Attachment>,
encoded_len: Option<usize>,
) -> Self {
let encoded_len = encoded_len
.unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX));
let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX);
Self {
memory_len,
saved: Arc::new(saved),
attachments,
encoded_len,
}
}
pub fn saved(&self) -> &Arc<SavedPrompt> {
&self.saved
}
/// What the prompt was written about, captured when it was queued.
pub fn attachments(&self) -> &[Attachment] {
&self.attachments
}
pub fn encoded_len(&self) -> usize {
self.encoded_len
}
pub fn memory_len(&self) -> usize {
self.memory_len
}
}
mod prompt;
pub use prompt::QueuedPrompt;

impl AgentThread {
pub(super) fn start_execution_watch(&mut self, cx: &mut Context<Self>) {
Expand Down Expand Up @@ -681,8 +641,8 @@ impl AgentThread {
}
self.state.validate_candidate(
&metadata,
queue.iter().map(|prompt| prompt.encoded_len),
queue.iter().map(|prompt| prompt.memory_len),
queue.iter().map(QueuedPrompt::encoded_len),
queue.iter().map(QueuedPrompt::memory_len),
)?;
self.composer.commit_prompt_change(candidate);
self.accept_document_inputs(cx, false);
Expand Down Expand Up @@ -719,15 +679,46 @@ impl AgentThread {
if !self.session.finish_external_turn() {
return;
}
self.finalize_tool_displays();
self.notice.present("Ready".into());
self.persist(cx);
self.dispatch_next(cx);
self.settle_external_turn(cx);
}
}
cx.notify();
}

/// Provider status is an observation, not a new user prompt or a tool grant.
pub(super) fn observe_session_activity(
&mut self,
activity: SessionActivity,
cx: &mut Context<Self>,
) {
if !self.session.observe_activity(activity) {
return;
}
if self.session.generating() {
self.notice.present("Working…".into());
} else {
self.settle_external_turn(cx);
}
cx.notify();
}

pub(super) fn resume_observed_turn(&mut self) {
if self.session.resume_observed_turn() {
self.notice.present("Working…".into());
}
}

fn settle_external_turn(&mut self, cx: &mut Context<Self>) {
self.finalize_tool_displays();
self.notice.present(if self.session.stopped() {
"Stopped".into()
} else {
"Ready".into()
});
self.persist(cx);
self.dispatch_next(cx);
}

pub fn dispatch_next(&mut self, cx: &mut Context<Self>) {
if !self.queue_dispatchable()
|| self.session.generating()
Expand All @@ -751,8 +742,9 @@ impl AgentThread {
return;
};
// Context is fixed for this turn, including terminal tool access.
self.tools.capture_scope(prompt.attachments);
let saved = Arc::unwrap_or_clone(prompt.saved);
let (attachments, saved) = prompt.into_parts();
self.tools.capture_scope(attachments);
let saved = Arc::unwrap_or_clone(saved);
self.start_prompt(saved.text, saved.images, cx);
}
}
Expand All @@ -767,33 +759,3 @@ pub(super) fn restore_attachments(values: &[SavedAttachment]) -> Vec<Attachment>
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rendering_snapshot_shares_immutable_image_payload() {
let prompt = QueuedPrompt::new(
SavedPrompt {
id: 1,
text: "image".into(),
images: vec![Content::Image(nocterm_ai::model::content::Image::new(
"a".repeat(2 * 1024 * 1024),
"image/png",
))],
attachments: Vec::new(),
},
Vec::new(),
);
let copy = prompt.clone();
assert!(Arc::ptr_eq(prompt.saved(), copy.saved()));
let Content::Image(original) = &prompt.saved().images[0] else {
panic!("image");
};
let Content::Image(cloned) = &copy.saved().images[0] else {
panic!("image");
};
assert_eq!(original.data.as_ptr(), cloned.data.as_ptr());
assert_eq!(cloned.data.len(), 2 * 1024 * 1024);
}
}
Loading
Loading