Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
fix: resolve review findings in cancel target parsing, kwant token cleanup, and cumulative discussion context
Oleksandr Ivanchenkoca2bb60479f2
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 84554471..3e615d5a 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -21,6 +21,8 @@ export const App: React.FC = () => {const [isStreaming, setIsStreaming] = useState(false);const [discussionState, setDiscussionState] = useState<DiscussionState>({ inProgress: false });const discussionInProgressRef = useRef(false);+ const kwantsRef = useRef<Kwant[]>(kwants);+ kwantsRef.current = kwants;const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);const [tokensUsed, setTokensUsed] = useState(0);@@ -116,18 +118,22 @@ export const App: React.FC = () => {playSfx('alert');break;case 'discussion_started':- case 'DiscussionStarted':+ case 'DiscussionStarted': {discussionInProgressRef.current = true;+ const initialSpeakerId = event.data?.speakers?.[0];+ const initialSpeakerName =+ kwantsRef.current.find((k) => k.id === initialSpeakerId)?.name || initialSpeakerId;setDiscussionState({inProgress: true,teamName: event.data?.team_name,totalTurns: event.data?.total_turns,- currentSpeaker: event.data?.speakers?.[0],+ currentSpeaker: initialSpeakerName,currentTurn: 1,});setIsStreaming(true);playSfx('alert');break;+ }case 'discussion_turn_started':case 'DiscussionTurnStarted':discussionInProgressRef.current = true;diff --git a/src/server/routes.rs b/src/server/routes.rsindex a8afa390..8d7890b5 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -128,22 +128,23 @@ pub async fn delete_team(}}+#[derive(Debug, Deserialize)]+pub struct CancelPayload {+ pub session_id: Option<String>,+ pub channel_id: Option<String>,+ pub team_id: Option<String>,+ pub kwant_id: Option<String>,+}+pub async fn cancel_chat(State(state): State<AppState>,body: axum::body::Bytes,) -> Result<Json<serde_json::Value>, StatusCode> {let mut tokens = state.active_cancellations.lock().await;let maybe_session_id = if !body.is_empty() {- if let Ok(val) = serde_json::from_slice::<serde_json::Value>(&body) {- val.get("session_id")- .or_else(|| val.get("channel_id"))- .or_else(|| val.get("team_id"))- .or_else(|| val.get("kwant_id"))- .and_then(|s| s.as_str())- .map(|s| s.to_string())- } else {- None- }+ serde_json::from_slice::<CancelPayload>(&body)+ .ok()+ .and_then(|p| p.session_id.or(p.channel_id).or(p.team_id).or(p.kwant_id))} else {None};@@ -151,10 +152,6 @@ pub async fn cancel_chat(if let Some(session_id) = maybe_session_id {if let Some(token) = tokens.remove(&session_id) {token.cancel();- } else {- for (_, token) in tokens.drain() {- token.cancel();- }}} else {for (_, token) in tokens.drain() {@@ -201,13 +198,14 @@ fn execute_single_turn(cancel_token: CancellationToken,session_id: String,team_keys: Option<(String, String)>,+ kwant_id: Option<String>,) {let event_broadcast = state.event_sender.clone();let db = state.db.clone();let router = state.router.clone();let active_cancellations = state.active_cancellations.clone();let channel_id = payload.channel_id.clone();- let kwant_id = payload.kwant_id.clone();+ let kwant_id = kwant_id.or_else(|| payload.kwant_id.clone());let prompt = payload.prompt.clone();tokio::spawn(async move {@@ -301,6 +299,9 @@ fn execute_single_turn(if let Some(cid) = &channel_id {tokens.remove(cid);}+ if let Some(kid) = &kwant_id {+ tokens.remove(kid);+ }if let Some((team_id, team_name)) = &team_keys {tokens.remove(team_id);tokens.remove(team_name);@@ -448,6 +449,7 @@ pub async fn send_chat(target_kwant.name, target_kwant.title, reason)));+ let kwant_id_cleanup = payload.kwant_id.clone();execute_single_turn(state.clone(),target_kwant.clone(),@@ -455,6 +457,7 @@ pub async fn send_chat(cancel_token,session_id,Some((team.id.clone(), team.name.clone())),+ kwant_id_cleanup,);Ok(Json(json!({@@ -503,7 +506,7 @@ pub async fn send_chat(plan: plan_clone.clone(),});- let mut previous_turn_output: Option<(String, String)> = None;+ let mut cumulative_transcript: Vec<(String, String)> = Vec::new();for (turn_idx, speaker_id) in speakers_clone.iter().enumerate() {if cancel_token_clone.is_cancelled() {@@ -518,13 +521,19 @@ pub async fn send_chat(}};- let speaker_prompt = if let Some((prev_name, prev_text)) = &previous_turn_output {+ let speaker_prompt = if cumulative_transcript.is_empty() {+ prompt.clone()+ } else {+ let turns_formatted = cumulative_transcript+ .iter()+ .enumerate()+ .map(|(idx, (name, text))| format!("### Turn {} ({})\n{}", idx + 1, name, text))+ .collect::<Vec<_>>()+ .join("\n\n");format!(- "Original query: {}\n\nPrevious response from {}:\n{}\n\nPlease provide your analysis, critique, or next steps according to the discussion plan.",- prompt, prev_name, prev_text+ "Original user query: {}\n\nDiscussion so far:\n{}\n\nPlease provide your analysis, critique, or synthesis according to the discussion plan.",+ prompt, turns_formatted)- } else {- prompt.clone()};let _ = event_broadcast.send(RuntimeEvent::DiscussionTurnStarted {@@ -612,7 +621,7 @@ pub async fn send_chat(tokens_used: output.tokens_used as i64,};let _ = db.insert_message(&asst_msg).await;- previous_turn_output = Some((speaker.name.clone(), output.text));+ cumulative_transcript.push((speaker.name.clone(), output.text));}}@@ -625,6 +634,9 @@ pub async fn send_chat(if let Some(cid) = &channel_id {tokens.remove(cid);}+ if let Some(kid) = &kwant_id {+ tokens.remove(kid);+ }tokens.remove(&team_clone.id);tokens.remove(&team_clone.name);});@@ -668,6 +680,7 @@ pub async fn send_chat(}.ok_or(StatusCode::BAD_REQUEST)?;+ let kwant_id_cleanup = payload.kwant_id.clone();execute_single_turn(state.clone(),target_kwant.clone(),@@ -675,6 +688,7 @@ pub async fn send_chat(cancel_token,session_id,None,+ kwant_id_cleanup,);Ok(Json(json!({diff --git a/tests/server_test.rs b/tests/server_test.rsindex 515439f0..5c54fa24 100644--- a/tests/server_test.rs+++ b/tests/server_test.rs@@ -230,3 +230,54 @@ async fn test_chat_routing_with_team_mention_and_cancellation() {assert_eq!(cancel_resp.status(), StatusCode::OK);}+#[tokio::test]+async fn test_cancel_chat_with_null_fields_only_cancels_target_kwant() {+ use tokio_util::sync::CancellationToken;++ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config::default();+ let tools = ToolRunner::new(tmp.path().join("workspace"));+ let broker = PermissionBroker::new();+ let router = LayaRouter::new(config.laya_url.clone());++ let state = AppState::new(config, db, tools, broker, router);+ let app = create_router(state.clone());++ // Insert two distinct tokens in active_cancellations+ let target_token = CancellationToken::new();+ let other_token = CancellationToken::new();+ {+ let mut tokens = state.active_cancellations.lock().await;+ tokens.insert("test-kwant".to_string(), target_token.clone());+ tokens.insert("other-session".to_string(), other_token.clone());+ }++ // Cancel with payload containing null channel_id and team_id, but specific kwant_id+ let cancel_body = json!({+ "channel_id": null,+ "kwant_id": "test-kwant",+ "team_id": null+ });+ let req = Request::builder()+ .method("POST")+ .uri("/api/chat/cancel")+ .header("content-type", "application/json")+ .body(Body::from(serde_json::to_vec(&cancel_body).unwrap()))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ // Target token must be cancelled+ assert!(target_token.is_cancelled(), "Target kwant token should be cancelled");++ // Other token must NOT be cancelled (no global drain!)+ assert!(!other_token.is_cancelled(), "Other session token must NOT be cancelled by targeted cancellation");++ // active_cancellations map must still contain other_token and not test-kwant+ let tokens = state.active_cancellations.lock().await;+ assert!(!tokens.contains_key("test-kwant"));+ assert!(tokens.contains_key("other-session"));+}++