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
48 changes: 45 additions & 3 deletions crates/jcode-app-core/src/agent/turn_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,12 @@ impl Agent {

self.announce_late_mcp_tools().await;
self.announce_late_skills();
self.append_user_context_message_with_display_role(user_message, images, display_role)?;
self.append_user_context_message_with_display_role(
user_message,
images,
display_role,
false,
)?;
crate::telemetry::record_turn();
let turn_started_at = Instant::now();
let start_message_index = self.message_count();
Expand All @@ -130,20 +135,57 @@ impl Agent {
result
}

/// Enter a native receipt turn. The durable state advances only after the
/// exact message has been committed to this session's transcript.
pub(crate) async fn run_once_streaming_mpsc_with_receipt(
&mut self,
message: &str,
receipt_id: &str,
event_tx: mpsc::UnboundedSender<ServerEvent>,
) -> Result<()> {
// Receipt turns carry no reminder. A turn that panicked before its own
// cleanup can leave the field set on this reused agent, and the stale
// reminder would then ride along with the synthetic wake input.
self.current_turn_system_reminder = None;
self.announce_late_mcp_tools().await;
self.announce_late_skills();
self.append_user_context_message_with_display_role(
message,
Vec::new(),
Some(crate::session::StoredDisplayRole::System),
false,
)?;
// System-displayed inputs do not count as visible conversation for
// the normal first-save guard. Force the first snapshot before proof.
self.session.save_prepared()?;
self.session.sync_wake_turn_entry()?;
crate::server::wake_receipts::mark_awakened(receipt_id, self.session_id())?;
crate::telemetry::record_turn();
let started_at = Instant::now();
let start_message_index = self.message_count();
self.fire_turn_start_hook("native_wake_receipt");
let result = self.run_turn_streaming_mpsc(event_tx).await;
Comment thread
codeant-ai[bot] marked this conversation as resolved.
Resolved
self.fire_turn_end_hook(&result, started_at, start_message_index);
result
}

/// Append and persist a user message without starting a model turn.
pub(crate) fn append_user_context_message(
&mut self,
user_message: &str,
images: Vec<(String, String)>,
) -> Result<()> {
self.append_user_context_message_with_display_role(user_message, images, None)
self.append_user_context_message_with_display_role(user_message, images, None, false)
}

fn append_user_context_message_with_display_role(
&mut self,
user_message: &str,
images: Vec<(String, String)>,
display_role: Option<crate::session::StoredDisplayRole>,
// A synthetic continuation (reload recovery) resumes the previous
// turn, so it must not start a new model-usage turn.
continues_turn: bool,
) -> Result<()> {
let mut blocks: Vec<ContentBlock> = images
.into_iter()
Expand All @@ -161,7 +203,7 @@ impl Agent {
));
}

let starts_turn = blocks.len() > 1 || !user_message.trim().is_empty();
let starts_turn = !continues_turn && (blocks.len() > 1 || !user_message.trim().is_empty());
let input_id = self.add_message_with_display_role(Role::User, blocks, display_role);
if starts_turn {
self.begin_model_usage_turn(&input_id);
Expand Down
1 change: 1 addition & 0 deletions crates/jcode-app-core/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ mod swarm_labels;
mod swarm_mutation_state;
mod swarm_persistence;
mod util;
pub(crate) mod wake_receipts;

pub(super) use self::await_members_state::AwaitMembersRuntime;
use self::background_tasks::{
Expand Down
60 changes: 60 additions & 0 deletions crates/jcode-app-core/src/server/client_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,65 @@ pub(super) async fn handle_notify_session(
}
}

pub(super) async fn handle_notify_session_receipt(
id: u64,
session_id: String,
message: String,
receipt_id: String,
ctx: NotifySessionContext<'_>,
) {
let result = async {
if !super::wake_receipts::target_is_allowed(&session_id) {
anyhow::bail!("Session '{}' is not allowed for native wakes", session_id);
}
// Only new admissions need a live target. An identical replay must keep
// returning the stored state even if the target transcript was removed
// since, which is why the replay lookup runs before this guard.
if super::wake_receipts::get(&receipt_id)?.is_none() {
// A receipt names one existing target in this profile. Never create a
// new session implicitly from untrusted bridge input. An attached
// live session counts as existing before its first transcript save.
let attached = ctx.sessions.read().await.contains_key(&session_id);
if !attached && !crate::session::session_exists(&session_id) {
anyhow::bail!("Session '{}' does not exist in this profile", session_id);
}
}
let receipt = super::wake_receipts::submit(&receipt_id, &session_id, &message)?;
if receipt.state == super::wake_receipts::WakeState::Queued {
let has_client = ctx
.client_connections
.read()
.await
.values()
.any(|connection| connection.session_id == session_id);
if has_client {
super::live_turn::run_receipt_turn_if_idle(
&session_id,
&message,
&receipt_id,
ctx.sessions,
super::live_turn::LiveTurnSwarmContext::new(
ctx.swarm_members,
ctx.swarms_by_id,
ctx.event_history,
ctx.event_counter,
ctx.swarm_event_tx,
),
)
.await;
Comment thread
codeant-ai[bot] marked this conversation as resolved.
Resolved
}
}
super::wake_receipts::get(&receipt_id)?
.ok_or_else(|| anyhow::anyhow!("receipt disappeared after submission"))
}
.await;
let event = match result {
Ok(receipt) => super::wake_receipts::status_event(id, receipt),
Err(error) => super::wake_receipts::error_event(id, &error.to_string()),
};
super::wake_receipts::send_event(ctx.client_event_tx, event);
}

/// A user pressed something in an agent applet: store its state, publish, then
/// resolve a waiting `applet` tool call or wake the agent like a notification.
pub(super) async fn handle_applet_action(
Expand Down Expand Up @@ -1191,6 +1250,7 @@ pub(super) async fn handle_resume_all_sessions(
Some(reminder),
None,
Some("resuming interrupted session".to_string()),
None,
super::live_turn::LiveTurnSwarmContext::new(
swarm_members,
swarms_by_id,
Expand Down
37 changes: 37 additions & 0 deletions crates/jcode-app-core/src/server/client_lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2333,6 +2333,43 @@ pub(super) async fn handle_client(
)
.await;
}
r @ (Request::NotifySessionReceipt { .. } | Request::GetWakeReceipt { .. }) => {
// is_lightweight_control_request routes these before attach, but a
// client that has already subscribed can still send one later.
// Handle it on the control path rather than aborting the task.
if let Err(error) = handle_lightweight_control_request(
r,
Arc::clone(&writer),
LightweightControlContext {
sessions: &sessions,
global_session_id: &global_session_id,
provider_template: &provider_template,
swarm_members: &swarm_members,
swarms_by_id: &swarms_by_id,
shared_context: &shared_context,
swarm_plans: &swarm_plans,
swarm_coordinators: &swarm_coordinators,
file_touch: &file_touch,
channel_subscriptions: &channel_subscriptions,
channel_subscriptions_by_session: &channel_subscriptions_by_session,
client_connections: &client_connections,
event_history: &event_history,
event_counter: &event_counter,
swarm_event_tx: &swarm_event_tx,
mcp_pool: &mcp_pool,
soft_interrupt_queues: &soft_interrupt_queues,
await_members_runtime: &await_members_runtime,
swarm_mutation_runtime: &swarm_mutation_runtime,
},
)
.await
{
super::wake_receipts::send_event(
&client_event_tx,
super::wake_receipts::error_event(request_id, &error.to_string()),
);
}
}

Request::AppletAction {
id,
Expand Down
68 changes: 68 additions & 0 deletions crates/jcode-app-core/src/server/client_lightweight_control.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::client_actions::{
NotifySessionContext, handle_applet_action, handle_close_applet, handle_notify_session,
handle_notify_session_receipt,
};
use super::client_comm::{
handle_comm_channel_members, handle_comm_list, handle_comm_list_channels, handle_comm_message,
Expand Down Expand Up @@ -180,6 +181,73 @@ pub(super) async fn handle_lightweight_control_request(
)
.await;
}
Request::NotifySessionReceipt {
id,
session_id,
message,
receipt_id,
} => {
handle_notify_session_receipt(
id,
session_id,
message,
receipt_id,
NotifySessionContext {
sessions,
soft_interrupt_queues,
client_connections,
swarm_members,
swarms_by_id,
event_history,
event_counter,
swarm_event_tx,
client_event_tx: &client_event_tx,
},
)
.await;
}
Request::GetWakeReceipt { id, receipt_id } => {
let event = match super::wake_receipts::get(&receipt_id) {
Ok(Some(receipt))
if !super::wake_receipts::target_is_allowed(&receipt.session_id) =>
{
super::wake_receipts::error_event(id, "Wake receipt target is not allowed")
}
Ok(Some(receipt)) => {
// A busy or unattached target leaves the receipt queued at
// submit time. Let a poll advance it, so the caller is not
// required to resubmit an identical request indefinitely.
let status = if receipt.state == super::wake_receipts::WakeState::Queued {
let started = super::live_turn::run_receipt_turn_if_idle(
&receipt.session_id,
&receipt.message,
&receipt.receipt_id,
sessions,
super::live_turn::LiveTurnSwarmContext::new(
swarm_members,
swarms_by_id,
event_history,
event_counter,
swarm_event_tx,
),
)
.await;
if !started {
crate::logging::debug(&format!(
"wake receipt turn not started for {receipt_id}: target busy or already awakened"
));
}
super::wake_receipts::reread_or(&receipt_id, receipt)
} else {
receipt
};
super::wake_receipts::status_event(id, status)
}
Ok(None) => super::wake_receipts::error_event(id, "Unknown wake receipt"),
Err(error) => super::wake_receipts::error_event(id, &error.to_string()),
};
super::wake_receipts::send_event(&client_event_tx, event);
}
Request::AppletAction {
id,
session_id,
Expand Down
50 changes: 49 additions & 1 deletion crates/jcode-app-core/src/server/live_turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,18 @@ pub(super) async fn idle_live_agent(
/// `failed` when it finishes. A synthetic terminal `Done { id: 0 }` (or
/// `Error { id: 0, .. }`) is fanned out to attached clients so their UI can
/// finish rendering the externally started turn.
#[expect(
clippy::too_many_arguments,
reason = "a tracked wake turn carries routing, display, status and receipt identity plus the swarm context it fans out to"
)]
pub(super) async fn spawn_tracked_live_turn(
session_id: &str,
mut agent: OwnedMutexGuard<Agent>,
message: String,
system_reminder: Option<String>,
display_role: Option<crate::session::StoredDisplayRole>,
status_detail: Option<String>,
receipt_id: Option<String>,
swarm: LiveTurnSwarmContext,
) {
update_member_status(
Expand All @@ -120,7 +125,11 @@ pub(super) async fn spawn_tracked_live_turn(
tokio::spawn(async move {
let start_message_index = agent.message_count();
let (result, stop_reason) = catch_live_turn_panic(async {
if let Some(display_role) = display_role {
if let Some(receipt_id) = receipt_id {
agent
.run_once_streaming_mpsc_with_receipt(&message, &receipt_id, event_tx.clone())
.await
} else if let Some(display_role) = display_role {
agent
.run_once_streaming_mpsc_with_display_role(
&message,
Expand Down Expand Up @@ -220,6 +229,7 @@ pub(super) async fn run_live_turn_if_idle(
system_reminder,
None,
detail,
None,
swarm,
)
.await;
Expand All @@ -243,6 +253,44 @@ pub(super) async fn run_live_system_turn_if_idle(
None,
Some(crate::session::StoredDisplayRole::System),
detail,
None,
swarm,
)
.await;
true
}

/// Retryable native receipt wake. Busy or unattached targets stay queued.
pub(super) async fn run_receipt_turn_if_idle(
session_id: &str,
message: &str,
receipt_id: &str,
sessions: &SessionAgents,
swarm: LiveTurnSwarmContext,
) -> bool {
let Some(agent) = idle_live_agent(session_id, sessions, &swarm.members).await else {
return false;
};
// The caller's queued snapshot may predate a completed turn. The agent
// reservation serializes live turns; re-read the durable receipt only now.
if !matches!(
super::wake_receipts::get(receipt_id),
Ok(Some(receipt))
if receipt.session_id == session_id
&& receipt.message == message
&& receipt.state == super::wake_receipts::WakeState::Queued
) {
return false;
}
let detail = Some(truncate_detail(message, 120));
spawn_tracked_live_turn(
session_id,
agent,
message.to_string(),
None,
Some(crate::session::StoredDisplayRole::System),
detail,
Some(receipt_id.to_string()),
swarm,
)
.await;
Expand Down
2 changes: 2 additions & 0 deletions crates/jcode-app-core/src/server/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock, broadcast, mpsc};
use tokio::time::timeout;

mod native_wake_receipt_tests;

struct EnvGuard {
prev_home: Option<OsString>,
prev_runtime_dir: Option<OsString>,
Expand Down
Loading
Loading